Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add export upscalers and weight templates

Bittie7ae85999b56
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 1f191d9..b4024cd 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -32,6 +32,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
## Fixes and improvements
+- Image and video export offer None, Real-ESRGAN and SeedVR2 upscaling through SlopFab. Download their models from the new Other weights section in Settings → Generator.
- Image export offers sizes closest to the selected image's actual aspect ratio, even when project or saved generation settings differ.
- Click a work queue job to open its image, scene, reference, generator download or export. Navigation works across projects and preserves unsaved project edits.
- Character Sheet offers Debug prompt when debug options are enabled, exposing the separate compiled prompt for each of its four views.
diff --git a/src/components/OtherWeightsSettings.test.tsx b/src/components/OtherWeightsSettings.test.tsx
new file mode 100644
index 0000000..19bcb32
--- /dev/null
+++ b/src/components/OtherWeightsSettings.test.tsx
@@ -0,0 +1,27 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { invoke } from "@tauri-apps/api/core";
+import { OtherWeightsSettings } from "./OtherWeightsSettings";
+import { OTHER_WEIGHT_TEMPLATES, upscaleConfig } from "../lib/upscalers";
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn().mockResolvedValue(() => {}) }));
+vi.mock("../lib/persistence", () => ({ isTauri: () => true }));
+afterEach(() => { cleanup(); localStorage.clear(); vi.clearAllMocks(); });
+
+it("downloads the SeedVR2 model and VAE as one template and resolves both export paths", async () => {
+ vi.mocked(invoke).mockImplementation(async (name, args) => {
+ if (name === "find_downloaded_weights") return {} as never;
+ if (name === "download_weight") return `C:/weights/${(args as { url: string }).url.split("/").at(-1)}` as never;
+ return undefined as never;
+ });
+ expect(() => upscaleConfig("seedvr2")).toThrow("Other weights");
+ render(<OtherWeightsSettings desktop />);
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("find_downloaded_weights", expect.anything()));
+ fireEvent.click(screen.getByRole("button", { name: "Download SeedVR2" }));
+ await waitFor(() => expect(screen.getByRole("button", { name: "Downloaded" })).toBeDisabled());
+ for (const file of OTHER_WEIGHT_TEMPLATES[1].files) expect(invoke).toHaveBeenCalledWith("download_weight", expect.objectContaining({ url: file.url }));
+ expect(upscaleConfig("seedvr2")).toEqual({ method: "seedvr2", modelPath: "C:/weights/seedvr2_3b_int8_convrot.safetensors", vaePath: "C:/weights/seedvr2_ema_vae_fp16.safetensors" });
+ expect(upscaleConfig("none")).toBeUndefined();
+});
diff --git a/src/components/OtherWeightsSettings.tsx b/src/components/OtherWeightsSettings.tsx
new file mode 100644
index 0000000..9090f15
--- /dev/null
+++ b/src/components/OtherWeightsSettings.tsx
@@ -0,0 +1,27 @@
+import { useEffect, useState } from "react";
+import { OTHER_WEIGHT_TEMPLATES, cancelOtherDownload, downloadOtherWeights, otherDownloadState, otherWeightPaths, refreshOtherWeights, subscribeOtherWeights } from "../lib/upscalers";
+import { InfoBar, ProgressBar, SettingsCard, SettingsGroup } from "./ui";
+import { Image20 } from "./ui/icons";
+
+export function OtherWeightsSettings({ desktop }: { desktop: boolean }) {
+ const [, refresh] = useState(0);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => subscribeOtherWeights(() => refresh((value) => value + 1)), []);
+ useEffect(() => { void refreshOtherWeights().catch((reason) => setError(String(reason))); }, []);
+ const paths = otherWeightPaths();
+ const download = otherDownloadState();
+ return <SettingsGroup heading="Other weights">
+ {OTHER_WEIGHT_TEMPLATES.map((template) => {
+ const ready = template.files.every((file) => paths[file.url]);
+ const active = download?.active && download.templateId === template.id;
+ return <SettingsCard key={template.id} icon={<Image20 />} header={template.name}
+ description={active ? `Downloading ${download.file}` : ready ? "Ready for image and video export" : template.files.map((file) => file.name).join(" · ")}>
+ {active ? <><ProgressBar value={download.progress} aria-label={`Downloading ${template.name} weights`} />
+ <button type="button" onClick={() => void cancelOtherDownload().catch((reason) => setError(String(reason)))}>Cancel</button></>
+ : <button type="button" className="secondary-button" disabled={!desktop || ready || download?.active}
+ onClick={() => void downloadOtherWeights(template.id)}>{ready ? "Downloaded" : `Download ${template.name}`}</button>}
+ </SettingsCard>;
+ })}
+ {(error || download?.error) && <InfoBar severity="error" title="Couldn’t download weights" message={error ?? download!.error!} />}
+ </SettingsGroup>;
+}
diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsx
index 99f2dca..9565df5 100644
--- a/src/components/SettingsView.tsx
+++ b/src/components/SettingsView.tsx
@@ -1,5 +1,6 @@
import { AdditionalSafetensorsEditor } from "./AdditionalSafetensorsEditor";
import { GeneratorSharing } from "./GeneratorSharing";
+import { OtherWeightsSettings } from "./OtherWeightsSettings";
import {
Add20, Agent16, Agent16Filled, Agent20, Back16, Check14, Check16, Check20, ChevronRight20, Delete16, Diagnostics16,
Diagnostics16Filled, Download16, Download20, Error16, Error20, Flash20, Folder20, Gauge20, Gpu20, Image20, ModelFile20, More16,
@@ -617,6 +618,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBar
</div>
</SettingsGroup>)}
<LoraLibrary onAdd={() => setEditingLoraId(`lora-${crypto.randomUUID()}`)} onEdit={setEditingLoraId} />
+ <OtherWeightsSettings desktop={desktop} />
</>;
const current = TABS.find((item) => item.id === tab)!;
diff --git a/src/components/workspace/ExportView.test.tsx b/src/components/workspace/ExportView.test.tsx
index 1b7b82c..96fb5e7 100644
--- a/src/components/workspace/ExportView.test.tsx
+++ b/src/components/workspace/ExportView.test.tsx
@@ -93,6 +93,10 @@ describe("the export view where nothing can encode", () => {
fireEvent.click(screen.getByRole("combobox", { name: "Frame rate" }));
fireEvent.click(screen.getByRole("option", { name: "30 fps" }));
expect(screen.getByText("60 frames at 30 fps")).toBeTruthy();
+ const upscaler = screen.getByRole("combobox", { name: "Upscaler" });
+ expect(optionNames(upscaler)).toEqual(["None", "Real-ESRGAN", "SeedVR2"]);
+ chooseOption(upscaler, "SeedVR2");
+ expect(upscaler.textContent).toContain("SeedVR2");
});
});
diff --git a/src/components/workspace/ExportView.tsx b/src/components/workspace/ExportView.tsx
index 9ac2c38..0f81b06 100644
--- a/src/components/workspace/ExportView.tsx
+++ b/src/components/workspace/ExportView.tsx
@@ -41,6 +41,7 @@ import { askNative, messageNative, revealInExplorer } from "../../lib/nativeShel
import { formatTimecode, frameAt, frameStartMs } from "../../lib/timeline";
import { ProgramMonitor } from "./ProgramMonitor";
import { ProjectStatus } from "./ProjectStatus";
+import { UPSCALERS, type Upscaler } from "../../lib/upscalers";
import type { ProjectConfig } from "../../lib/project";
import { ComboBox, InfoBar, ProgressBar, PropRow, PropSection, Slider, Splitter, tooltipProps, usePaneSize } from "../ui";
@@ -447,6 +448,11 @@ export function ExportView({ config, folderPath, onClose }: {
/>
</PropRow>
+ <PropRow label="Upscaler" htmlFor="export-upscaler">
+ <ComboBox id="export-upscaler" value={settings.upscaler ?? "none"} disabled={runningHere}
+ options={[...UPSCALERS]} onChange={(value) => setSettings({ ...settings, upscaler: value as Upscaler })} />
+ </PropRow>
+
<PropRow label="Format" htmlFor="export-codec">
<ComboBox
id="export-codec"
diff --git a/src/components/workspace/ImageExportView.test.tsx b/src/components/workspace/ImageExportView.test.tsx
index 7ce477b..02f0ea4 100644
--- a/src/components/workspace/ImageExportView.test.tsx
+++ b/src/components/workspace/ImageExportView.test.tsx
@@ -8,6 +8,7 @@ import * as persistence from "../../lib/persistence";
import { invoke } from "@tauri-apps/api/core";
import { ImageExportView } from "./ImageExportView";
import { imageGenerationSnapshot } from "../../lib/imageHistory";
+import { OTHER_WEIGHT_TEMPLATES } from "../../lib/upscalers";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
afterEach(() => { cleanup(); localStorage.clear(); vi.restoreAllMocks(); });
@@ -43,6 +44,24 @@ it("refuses to export a draft and says why", () => {
expect(screen.getByText("The image is a draft")).toBeInTheDocument();
});
+it.each(OTHER_WEIGHT_TEMPLATES)("exports with the selected $name model paths", async (template) => {
+ vi.spyOn(persistence, "isTauri").mockReturnValue(true);
+ vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);
+ vi.mocked(invoke).mockResolvedValue(true);
+ localStorage.setItem("slopus.other-weights.v1", JSON.stringify(Object.fromEntries(template.files.map((file) => [file.url, `C:/weights/${file.id}`]))));
+ render(<ImageExportView config={withOutput({ width: 64, height: 32 })} folderPath="D:/Images" />);
+ const selector = screen.getByRole("combobox", { name: "Upscaler" });
+ expect(selector).toHaveTextContent("None");
+ fireEvent.click(selector);
+ expect(screen.getAllByRole("option").map((option) => option.textContent)).toEqual(["None", "Real-ESRGAN", "SeedVR2"]);
+ fireEvent.click(screen.getByRole("option", { name: template.name }));
+ fireEvent.click(screen.getByRole("button", { name: "Export…" }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", expect.objectContaining({
+ options: expect.objectContaining({ width: 64, height: 32, upscale: { method: template.id, modelPath: "C:/weights/model",
+ ...(template.id === "seedvr2" ? { vaePath: "C:/weights/vae" } : {}) } }),
+ })));
+});
+
it("sends the chosen size, format and JPG quality, and hides quality for PNG", async () => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);
diff --git a/src/components/workspace/ImageExportView.tsx b/src/components/workspace/ImageExportView.tsx
index 6dea0d8..fb51f45 100644
--- a/src/components/workspace/ImageExportView.tsx
+++ b/src/components/workspace/ImageExportView.tsx
@@ -7,6 +7,7 @@ import { ComboBox, EmptyState, InfoBar, PropRow, PropSection, Slider, Splitter,
import { Image32 } from "../ui/icons";
import { ImageBar } from "./ImageBar";
import { ReferenceImage } from "./ReferenceImage";
+import { UPSCALERS, upscaleConfig, type Upscaler } from "../../lib/upscalers";
/* The image project's Export tab: the same page as the video export (see
export.css) — the image on the stage, filling it, and the resizable settings
@@ -30,6 +31,7 @@ function loadPreferences(): { format: ImageFormat; quality: number } {
export function ImageExportView({ config, folderPath }: { config: ProjectConfig; folderPath: string }) {
const settingsPane = usePaneSize("export.settings", 340, { min: 280, max: 560 });
const [exporting, setExporting] = useState(false);
+ const [upscaler, setUpscaler] = useState<Upscaler>("none");
const [error, setError] = useState<string | null>(null);
/* Which image to export is this page's own choice: it starts on the one open
in the Editor, and picking another here leaves the Editor where it was. */
@@ -68,7 +70,8 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;
await invoke("export_generated_image", {
folderPath,
relativePath: output.relativePath,
- options: { format: preferences.format, width: size?.width, height: size?.height, quality: preferences.format === "jpg" ? preferences.quality : undefined },
+ options: { format: preferences.format, width: size?.width, height: size?.height, quality: preferences.format === "jpg" ? preferences.quality : undefined,
+ ...(upscaler !== "none" ? { upscale: upscaleConfig(upscaler) } : {}) },
});
}
catch (reason) { setError(String(reason)); }
@@ -115,6 +118,10 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;
options={[{ value: "jpg", label: "JPG" }, { value: "png", label: "PNG · lossless" }]}
/>
</PropRow>
+ <PropRow label="Upscaler" htmlFor="image-export-upscaler">
+ <ComboBox id="image-export-upscaler" value={upscaler} disabled={exporting}
+ options={[...UPSCALERS]} onChange={(value) => setUpscaler(value as Upscaler)} />
+ </PropRow>
{preferences.format === "jpg" && <PropRow label="Quality" value={preferences.quality} defaultValue={DEFAULT_QUALITY} onReset={exporting ? undefined : () => choose({ quality: DEFAULT_QUALITY })} resetLabel="Reset quality">
<Slider aria-label="JPG quality" min={1} max={100} step={1} value={preferences.quality} disabled={exporting} onChange={(quality) => choose({ quality })} />
<span className="export-quality__value">{preferences.quality}</span>
diff --git a/src/lib/export.ts b/src/lib/export.ts
index 5660973..67a07dd 100644
--- a/src/lib/export.ts
+++ b/src/lib/export.ts
@@ -34,6 +34,7 @@ export type OutputCodecId = "h264" | "vp9" | "av1";
export type QualityId = "draft" | "balanced" | "high";
export interface ExportSettings {
+ upscaler?: import("./upscalers").Upscaler;
/** The encoded frame, in pixels: the project's own size or a standard one. */
width: number;
height: number;
diff --git a/src/lib/exportPipeline.test.ts b/src/lib/exportPipeline.test.ts
index 694d3cb..e6c7895 100644
--- a/src/lib/exportPipeline.test.ts
+++ b/src/lib/exportPipeline.test.ts
@@ -7,6 +7,8 @@ import externalFixture from "../../fixtures/project-v1-external-media.json";
import { audioMixBytes, buildExportPlan, defaultExportSettings } from "./export";
import { parseProjectConfig, type ProjectAsset } from "./project";
import { demux, ExportCancelled, PreviewSources, probeCompositor, runExport } from "./exportPipeline";
+import * as upscaleBridge from "./upscaleExport";
+import { OTHER_WEIGHT_TEMPLATES } from "./upscalers";
// Every IPC call is captured rather than performed: what the export DISPATCHES
// is the thing under test.
@@ -819,6 +821,31 @@ const PATHS = {
const audioProject = () => parseProjectConfig(audioFixture);
+it("routes every composed frame through the selected upscaler while retaining the soundtrack", async () => {
+ const harness = installWebCodecs({ decodes: true });
+ const dispose = vi.fn().mockResolvedValue(undefined);
+ const finish = vi.fn().mockResolvedValue(undefined);
+ const upscale = vi.spyOn(upscaleBridge, "startUpscaleExport").mockImplementation(async (options) => {
+ let index = 0;
+ return { push: async (frame) => options.output(frame, index++), finish, dispose };
+ });
+ try {
+ localStorage.setItem("slopus.other-weights.v1", JSON.stringify({ [OTHER_WEIGHT_TEMPLATES[0].files[0].url]: "C:/weights/model.safetensors" }));
+ const config = audioProject();
+ const settings = { ...defaultExportSettings(config), upscaler: "realesrgan" as const };
+ serveFiles({ video: await sampleFile(120, 24), score: scoreFile(), voice: wavFile({ seconds: 3, sample: () => 0.2 }) });
+ const plan = buildExportPlan(config, settings);
+ const result = await runExport({ folderPath: AUDIO_FOLDER, config, settings, plan, bitrate: 5_000_000,
+ onProgress: () => {}, cancelled: () => false });
+ expect(upscale).toHaveBeenCalledWith(expect.objectContaining({ config: { method: "realesrgan", modelPath: "C:/weights/model.safetensors" },
+ width: plan.width, height: plan.height, frameCount: plan.frameCount }));
+ expect(harness.recorded.videoChunks).toBe(plan.frameCount);
+ expect(result.audio).toBe(true);
+ expect(finish).toHaveBeenCalledOnce();
+ expect(dispose).toHaveBeenCalledOnce();
+ } finally { upscale.mockRestore(); harness.restore(); localStorage.removeItem("slopus.other-weights.v1"); }
+});
+
/** The IPC layer, answering with real files per path. Anything unasked-for
* throws, so a read the export should not have made shows up as a failure
* rather than as a convenient default. */
diff --git a/src/lib/exportPipeline.ts b/src/lib/exportPipeline.ts
index 7bee94d..c88af3b 100644
--- a/src/lib/exportPipeline.ts
+++ b/src/lib/exportPipeline.ts
@@ -39,6 +39,9 @@ import { applyChromaKey, keyColor, KEY_FEATHER, RGB_DISTANCE_SCALE } from "./chr
import { hasVideoEffects } from "./effectSettings";
import { createVideoEffectsProcessor } from "./videoEffectsGpu";
import { previewEngine } from "./previewEngine";
+import { outputDimensions } from "./export";
+import { upscaleConfig } from "./upscalers";
+import { startUpscaleExport } from "./upscaleExport";
/* ---------------------------------------------------------------------------
What this machine can do
@@ -1010,6 +1013,13 @@ function describeSoundtrack(
export async function runExport(options: ExportRunOptions): Promise<ExportResult> {
const { plan, settings, config, folderPath, bitrate, onProgress, cancelled } = options;
+ const upscale = upscaleConfig(settings.upscaler ?? "none");
+ const projectSize = outputDimensions(config.settings.resolution, config.settings.aspectRatio);
+ const renderScale = upscale ? Math.min(1, projectSize.width / plan.width, projectSize.height / plan.height,
+ upscale.method === "realesrgan" ? 4096 / Math.max(plan.width, plan.height) : 1) : 1;
+ const renderWidth = Math.max(1, Math.round(plan.width * renderScale));
+ const renderHeight = Math.max(1, Math.round(plan.height * renderScale));
+ let upscaler: Awaited<ReturnType<typeof startUpscaleExport>> | undefined;
const support = detectExportSupport();
if (!support.encoder || !support.decoder) {
throw new Error("This webview has no WebCodecs VideoEncoder/VideoDecoder, so Slopus cannot encode video here.");
@@ -1089,7 +1099,7 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
picture on the same geometry. Which one ran is reported, never assumed —
and so is WHY, because "WebGPU was unavailable" on its own is a sentence
nobody can act on. */
- const attempt = await createWebGpuCompositor(plan.width, plan.height, plan.backgroundColor).catch(
+ const attempt = await createWebGpuCompositor(renderWidth, renderHeight, plan.backgroundColor).catch(
(reason: unknown) => ({
compositor: null,
reason: `Starting the GPU compositor failed: ${reason instanceof Error ? reason.message : String(reason)}`,
@@ -1098,7 +1108,7 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
const stage: { compositor: Compositor; detail: string } = attempt.compositor
? { compositor: attempt.compositor, detail: attempt.reason ?? "" }
: {
- compositor: createCanvasCompositor(plan.width, plan.height, plan.backgroundColor),
+ compositor: createCanvasCompositor(renderWidth, renderHeight, plan.backgroundColor),
detail: attempt.reason,
};
const paint = (pictures: { frame: VideoFrame; style: ClipFrameStyle }[]) => {
@@ -1112,7 +1122,7 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
} catch (reason) {
if (stage.compositor.kind === "canvas2d") throw reason;
stage.compositor.dispose();
- stage.compositor = createCanvasCompositor(plan.width, plan.height, plan.backgroundColor);
+ stage.compositor = createCanvasCompositor(renderWidth, renderHeight, plan.backgroundColor);
stage.detail = `The GPU compositor gave out ${framesDone} frames in and the rest was composited on a 2D canvas: ${reason instanceof Error ? reason.message : String(reason)}`;
}
draw();
@@ -1146,10 +1156,13 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
timestampUs(outputIndex),
timestampUs(outputIndex + 1) - timestampUs(outputIndex),
);
- try { encoder.encode(composited, { keyFrame: outputIndex % keyFrameInterval === 0 }); }
+ try {
+ if (upscaler) await upscaler.push(composited);
+ else encoder.encode(composited, { keyFrame: outputIndex % keyFrameInterval === 0 });
+ }
finally { composited.close(); }
framesDone += 1;
- if (framesDone % 5 === 0 || framesDone === plan.frameCount) {
+ if (!upscaler && (framesDone % 5 === 0 || framesDone === plan.frameCount)) {
report("rendering", framesDone, `Rendering frame ${framesDone} of ${plan.frameCount}.`);
}
// Yield so the encoder's own queue drains and the window stays alive.
@@ -1351,6 +1364,17 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
try {
encoder.configure(encoderConfig(probe.codecString, plan, bitrate));
+ if (upscale) {
+ report("preparing", 0, "Loading upscaler weights…");
+ upscaler = await startUpscaleExport({ config: upscale, inputWidth: renderWidth, inputHeight: renderHeight,
+ width: plan.width, height: plan.height, frameRate: plan.frameRate, frameCount: plan.frameCount, cancelled,
+ output: async (frame, index) => {
+ encoderWait.check();
+ encoder.encode(frame, { keyFrame: index % keyFrameInterval === 0 });
+ report("rendering", index + 1, `Upscaling frame ${index + 1} of ${plan.frameCount}.`);
+ await waitForCodec(() => encoder.encodeQueueSize <= 8, encoderWait);
+ } });
+ }
for (const segment of plan.segments) {
stopIfCancelled();
if (segment.kind === "gap") {
@@ -1362,6 +1386,7 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
}
}
+ await upscaler?.finish();
if (soundtrack) {
report("finishing", framesDone, `Encoding the mixed soundtrack as AAC…`);
await encodeAudio(soundtrack, (chunk, meta) => muxer.addAudioChunk(chunk, meta), encoderWait.check);
@@ -1380,10 +1405,16 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResult
audioProblems,
audioShortfalls,
};
+ } catch (reason) {
+ stopIfCancelled();
+ throw reason;
} finally {
- releaseLoaded();
- if (encoder.state !== "closed") encoder.close();
- stage.compositor.dispose();
+ try { await upscaler?.dispose(); }
+ finally {
+ releaseLoaded();
+ if (encoder.state !== "closed") encoder.close();
+ stage.compositor.dispose();
+ }
}
}
diff --git a/src/lib/upscaleExport.test.ts b/src/lib/upscaleExport.test.ts
new file mode 100644
index 0000000..768c030
--- /dev/null
+++ b/src/lib/upscaleExport.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from "vitest";
+import { invoke } from "@tauri-apps/api/core";
+import { startUpscaleExport } from "./upscaleExport";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+it("pumps segmented native output concurrently, preserving every frame timestamp", async () => {
+ const pending: ((value: ArrayBuffer) => void)[] = [];
+ const queued: ArrayBuffer[] = [];
+ const deliver = (bytes: ArrayBuffer) => { const resolve = pending.shift(); if (resolve) resolve(bytes); else queued.push(bytes); };
+ let inputs = 0;
+ vi.mocked(invoke).mockImplementation(async (name, args) => {
+ if (name === "read_export_upscale") return (queued.length ? queued.shift() : new Promise((resolve) => pending.push(resolve))) as never;
+ if (name === "push_export_upscale") {
+ expect(args).toBeInstanceOf(Uint8Array);
+ if (++inputs === 5) for (let i = 0; i < 5; i++) deliver(new Uint8Array(4 * 2 * 4).buffer);
+ }
+ if (name === "finish_export_upscale") { deliver(new Uint8Array(4 * 2 * 4).buffer); deliver(new ArrayBuffer(0)); }
+ return undefined as never;
+ });
+ const frames: { timestamp: number; duration: number; close: ReturnType<typeof vi.fn> }[] = [];
+ vi.stubGlobal("VideoFrame", class {
+ timestamp: number; duration: number; close = vi.fn();
+ constructor(_bytes: unknown, options: { timestamp: number; duration: number }) {
+ this.timestamp = options.timestamp; this.duration = options.duration; frames.push(this);
+ }
+ });
+ const output = vi.fn().mockResolvedValue(undefined);
+ const stream = await startUpscaleExport({ config: { method: "seedvr2", modelPath: "model", vaePath: "vae" },
+ inputWidth: 2, inputHeight: 1, width: 4, height: 2, frameRate: 24, frameCount: 6, cancelled: () => false, output });
+ const frame = { copyTo: vi.fn().mockResolvedValue([]) } as unknown as VideoFrame;
+ for (let i = 0; i < 6; i++) await stream.push(frame);
+ await stream.finish();
+ await stream.dispose();
+ expect(output).toHaveBeenCalledTimes(6);
+ expect(frames.map((frame) => frame.timestamp)).toEqual([0, 41667, 83333, 125000, 166667, 208333]);
+ expect(frames.every((frame) => frame.close.mock.calls.length === 1)).toBe(true);
+ expect(invoke).toHaveBeenCalledWith("cancel_export_upscale", expect.anything());
+});
+
+it("surfaces native errors and closes the session", async () => {
+ vi.mocked(invoke).mockImplementation(async (name) => {
+ if (name === "read_export_upscale") throw new Error("Model could not be loaded");
+ return undefined as never;
+ });
+ const stream = await startUpscaleExport({ config: { method: "realesrgan", modelPath: "model" },
+ inputWidth: 2, inputHeight: 2, width: 8, height: 8, frameRate: 24, frameCount: 1, cancelled: () => false, output: vi.fn() });
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledWith("cancel_export_upscale", expect.anything()));
+ await expect(stream.finish()).rejects.toThrow("Model could not be loaded");
+ await stream.dispose();
+});
+
+it("cancels a native stream even while waiting for its first output", async () => {
+ let rejectRead: (reason: Error) => void = () => {};
+ let cancelled = false;
+ vi.mocked(invoke).mockImplementation(async (name) => {
+ if (name === "read_export_upscale") return new Promise((_resolve, reject) => { rejectRead = reject; }) as never;
+ if (name === "cancel_export_upscale") rejectRead(new Error("Upscaling cancelled."));
+ return undefined as never;
+ });
+ const stream = await startUpscaleExport({ config: { method: "seedvr2", modelPath: "model", vaePath: "vae" },
+ inputWidth: 2, inputHeight: 2, width: 8, height: 8, frameRate: 24, frameCount: 1, cancelled: () => cancelled, output: vi.fn() });
+ cancelled = true;
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledWith("cancel_export_upscale", expect.anything()));
+ await stream.dispose();
+ await expect(stream.finish()).rejects.toThrow(/cancelled/);
+});
diff --git a/src/lib/upscaleExport.ts b/src/lib/upscaleExport.ts
new file mode 100644
index 0000000..94df8f5
--- /dev/null
+++ b/src/lib/upscaleExport.ts
@@ -0,0 +1,58 @@
+import { invoke } from "@tauri-apps/api/core";
+import type { UpscaleConfig } from "./upscalers";
+
+/** Bounded native stream: input and output must be pumped concurrently because
+ * SeedVR2 buffers temporal segments before producing its first restored frame. */
+export async function startUpscaleExport(options: {
+ config: UpscaleConfig; inputWidth: number; inputHeight: number; width: number; height: number;
+ frameRate: number; frameCount: number; cancelled: () => boolean;
+ output: (frame: VideoFrame, index: number) => Promise<void>;
+}) {
+ const id = crypto.randomUUID();
+ const { config, inputWidth, inputHeight, width, height } = options;
+ await invoke("start_export_upscale", { id, config, inputWidth, inputHeight, width, height });
+ let failure: unknown;
+ let frames = 0;
+ let closed = false;
+ const close = async () => {
+ if (closed) return;
+ closed = true;
+ clearInterval(timer);
+ await invoke("cancel_export_upscale", { id });
+ };
+ const check = () => {
+ if (failure) throw failure;
+ if (options.cancelled()) throw new Error("Export cancelled.");
+ };
+ const timer = setInterval(() => { if (options.cancelled()) void close().catch(() => {}); }, 100);
+ const done = (async () => {
+ for (;;) {
+ check();
+ const bytes = new Uint8Array(await invoke<ArrayBuffer>("read_export_upscale", { id }));
+ if (!bytes.length) break;
+ if (bytes.length !== width * height * 4 || frames >= options.frameCount) throw new Error("Upscaler returned invalid frames.");
+ const timestamp = Math.round(frames * 1_000_000 / options.frameRate);
+ const frame = new VideoFrame(bytes, { format: "RGBA", codedWidth: width, codedHeight: height,
+ timestamp, duration: Math.round((frames + 1) * 1_000_000 / options.frameRate) - timestamp });
+ try { await options.output(frame, frames++); } finally { frame.close(); }
+ }
+ if (frames !== options.frameCount) throw new Error(`Upscaler returned ${frames} of ${options.frameCount} frames.`);
+ })().catch(async (reason) => { failure = reason; await close().catch(() => {}); });
+ return {
+ async push(frame: VideoFrame) {
+ check();
+ const bytes = new Uint8Array(inputWidth * inputHeight * 4);
+ await frame.copyTo(bytes, { format: "RGBA" });
+ check();
+ await invoke("push_export_upscale", bytes, { headers: { "x-upscale-id": id } });
+ check();
+ },
+ async finish() {
+ check();
+ await invoke("finish_export_upscale", { id });
+ await done;
+ check();
+ },
+ async dispose() { await close(); await done; },
+ };
+}
diff --git a/src/lib/upscalers.ts b/src/lib/upscalers.ts
new file mode 100644
index 0000000..acc7135
--- /dev/null
+++ b/src/lib/upscalers.ts
@@ -0,0 +1,87 @@
+import { invoke } from "@tauri-apps/api/core";
+import { listen } from "@tauri-apps/api/event";
+import { isTauri } from "./persistence";
+
+export type Upscaler = "none" | "realesrgan" | "seedvr2";
+export const UPSCALERS = [
+ { value: "none", label: "None" },
+ { value: "realesrgan", label: "Real-ESRGAN" },
+ { value: "seedvr2", label: "SeedVR2" },
+] as const;
+export const OTHER_WEIGHT_TEMPLATES = [
+ { id: "realesrgan", name: "Real-ESRGAN", files: [
+ { id: "model", name: "RealESRGAN x4plus", url: "https://huggingface.co/Comfy-Org/Real-ESRGAN_repackaged/resolve/main/RealESRGAN_x4plus.safetensors" },
+ ] },
+ { id: "seedvr2", name: "SeedVR2", files: [
+ { id: "model", name: "SeedVR2 3B INT8", url: "https://huggingface.co/Comfy-Org/SeedVR2/resolve/main/diffusion_models/seedvr2_3b_int8_convrot.safetensors" },
+ { id: "vae", name: "SeedVR2 VAE", url: "https://huggingface.co/Comfy-Org/SeedVR2/resolve/main/vae/seedvr2_ema_vae_fp16.safetensors" },
+ ] },
+] as const;
+const KEY = "slopus.other-weights.v1";
+const EVENT = "slopus:other-weights";
+export function otherWeightPaths(): Record<string, string> {
+ try {
+ const value = JSON.parse(localStorage.getItem(KEY) ?? "{}");
+ return Object.fromEntries(Object.entries(value).filter(([, path]) => typeof path === "string" && path && !/^https?:/i.test(path))) as Record<string, string>;
+ } catch { return {}; }
+}
+const savePaths = (paths: Record<string, string>) => {
+ localStorage.setItem(KEY, JSON.stringify(paths));
+ window.dispatchEvent(new Event(EVENT));
+};
+export function subscribeOtherWeights(listener: () => void) {
+ window.addEventListener(EVENT, listener);
+ window.addEventListener("storage", listener);
+ return () => { window.removeEventListener(EVENT, listener); window.removeEventListener("storage", listener); };
+}
+export interface UpscaleConfig { method: Exclude<Upscaler, "none">; modelPath: string; vaePath?: string }
+export function upscaleConfig(method: Upscaler): UpscaleConfig | undefined {
+ if (method === "none") return undefined;
+ const template = OTHER_WEIGHT_TEMPLATES.find((item) => item.id === method)!;
+ const paths = otherWeightPaths();
+ if (template.files.some((file) => !paths[file.url])) throw new Error(`Download ${template.name} in Settings → Generator → Other weights first.`);
+ return { method, modelPath: paths[template.files[0].url], ...(method === "seedvr2" ? { vaePath: paths[OTHER_WEIGHT_TEMPLATES[1].files[1].url] } : {}) };
+}
+export async function refreshOtherWeights() {
+ if (!isTauri()) return;
+ const urls = OTHER_WEIGHT_TEMPLATES.flatMap((item) => item.files.map((file) => file.url));
+ const found = await invoke<Record<string, string>>("find_downloaded_weights", { urls });
+ if (found) savePaths(found);
+}
+export interface OtherDownload { templateId: string; file: string; progress: number; requestId: string; error?: string; active: boolean }
+let download: OtherDownload | null = null;
+let downloadCancelled = false;
+export const otherDownloadState = () => download;
+const publish = (value: OtherDownload) => { download = value; window.dispatchEvent(new Event(EVENT)); };
+export async function downloadOtherWeights(id: string) {
+ if (!isTauri() || download?.active) return;
+ const template = OTHER_WEIGHT_TEMPLATES.find((item) => item.id === id);
+ if (!template) return;
+ const requestId = crypto.randomUUID();
+ downloadCancelled = false;
+ publish({ templateId: id, file: "", progress: 0, requestId, active: true });
+ let unlisten: (() => void) | undefined;
+ try {
+ let completed = 0;
+ unlisten = await listen<{ requestId: string; downloaded: number; total: number | null }>("weight-download-progress", ({ payload }) => {
+ if (payload.requestId === requestId && download?.active) publish({ ...download,
+ progress: (completed + (payload.total ? payload.downloaded / payload.total : 0)) / template.files.length * 100 });
+ });
+ for (const file of template.files) {
+ if (downloadCancelled) throw new Error("Download cancelled.");
+ publish({ ...download!, file: file.name });
+ const path = await invoke<string>("download_weight", { requestId, url: file.url });
+ if (!path || /^https?:/i.test(path)) throw new Error("The download did not return a local file.");
+ savePaths({ ...otherWeightPaths(), [file.url]: path });
+ completed++;
+ }
+ publish({ ...download!, progress: 100, active: false });
+ } catch (reason) { publish({ ...download!, active: false, error: String(reason) }); }
+ finally { unlisten?.(); }
+}
+export async function cancelOtherDownload() {
+ if (!download?.active) return;
+ const requestId = download.requestId;
+ downloadCancelled = true;
+ await invoke("cancel_weight_download", { requestId });
+}