Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Fix generated media persistence

Bitti339466d07521
diff --git a/src-tauri/src/rendered.rs b/src-tauri/src/rendered.rs
index c08578b..faacd1d 100644
--- a/src-tauri/src/rendered.rs
+++ b/src-tauri/src/rendered.rs
@@ -1,9 +1,9 @@
//! What a finished generation leaves behind, between vidfab and the encoder.
//!
-//! vidfab hands back raw pictures — planar RGB floats, one plane after another,
-//! frame after frame — and then frees them when the generation handle is
-//! destroyed. Nothing in this process can turn those into an MP4: encoding is
-//! the webview's job, because WebCodecs is what owns the OS hardware encoder
+//! vidfab hands back raw pictures — planar RGB floats, one channel after
+//! another, with every frame of a channel contiguous — and frees them when the
+//! generation handle is destroyed. Nothing in this process can turn those into
+//! an MP4: encoding is the webview's job, because WebCodecs owns the OS encoder
//! and PolStudio ships no FFmpeg by design (see docs/architecture.md, and
//! CLAUDE.md on the licensing reason).
//!
@@ -125,10 +125,11 @@ impl Range {
/// Turns vidfab's planar float pictures into the RGBA the webview can encode.
///
-/// The layout, from docs/architecture.md and the C API's own fields: `frames`
-/// pictures, each `channels` planes of `height × width` floats, rows top to
-/// bottom. Every plane of a frame is therefore `width * height` apart, which is
-/// what the striding below says.
+/// The C API declares the layout as `[channels][frames][height][width]`: all
+/// red frames first, then all green frames, then all blue frames. In
+/// particular, it is not `[frames][channels][height][width]`. Treating it as
+/// frame-major makes an RGB render look like the same third-length motion clip
+/// played three times, once from each channel plane.
///
/// One channel is greyscale and is written to all three; more than three means
/// the first three are the colour and the rest is not ours to interpret.
@@ -159,13 +160,29 @@ pub fn rgba_from_planar(
video.len()
));
}
- let range = Range::of(&video[..planes * pixels]);
+ let channel_stride = frames * pixels;
+ let range = if (0..planes).any(|channel| {
+ let start = channel * channel_stride;
+ Range::of(&video[start..start + pixels]) == Range::Signed
+ }) {
+ Range::Signed
+ } else {
+ Range::Unit
+ };
let mut rgba = vec![255u8; frames * pixels * 4];
for frame in 0..frames {
- let base = frame * planes * pixels;
- let red = &video[base..base + pixels];
- let green = if planes >= 2 { &video[base + pixels..base + 2 * pixels] } else { red };
- let blue = if planes >= 3 { &video[base + 2 * pixels..base + 3 * pixels] } else { red };
+ let frame_offset = frame * pixels;
+ let red = &video[frame_offset..frame_offset + pixels];
+ let green = if planes >= 2 {
+ &video[channel_stride + frame_offset..channel_stride + frame_offset + pixels]
+ } else {
+ red
+ };
+ let blue = if planes >= 3 {
+ &video[2 * channel_stride + frame_offset..2 * channel_stride + frame_offset + pixels]
+ } else {
+ red
+ };
let out = &mut rgba[frame * pixels * 4..(frame + 1) * pixels * 4];
for pixel in 0..pixels {
out[pixel * 4] = range.to_byte(red[pixel]);
@@ -193,6 +210,16 @@ pub fn from_output(
audio_channels: u32,
audio_sample_rate: u32,
) -> Result<RenderedVideo, String> {
+ if !audio.is_empty()
+ && (audio_channels == 0
+ || audio_sample_rate == 0
+ || audio.len() % audio_channels as usize != 0)
+ {
+ return Err(format!(
+ "The render returned {} audio samples with {audio_channels} channels at {audio_sample_rate} Hz.",
+ audio.len()
+ ));
+ }
Ok(RenderedVideo {
job_id: job_id.to_string(),
width,
@@ -304,11 +331,13 @@ mod tests {
}
#[test]
- fn every_frame_is_read_from_its_own_planes() {
- // Two 1×1 frames, the second twice as bright as the first.
- let video = vec![0.2, 0.2, 0.2, 0.4, 0.4, 0.4];
+ fn channel_major_frames_are_not_read_as_repeated_temporal_blocks() {
+ // [R0, R1, G0, G1, B0, B1], exactly as vidfab's C API returns it.
+ // Distinct channels and frames make a channel/frame transposition
+ // visible instead of letting a greyscale fixture hide it.
+ let video = vec![0.1, 0.4, 0.2, 0.5, 0.3, 0.6];
let rgba = rgba_from_planar(&video, 2, 1, 1, 3).unwrap();
- assert_eq!(rgba, vec![51, 51, 51, 255, 102, 102, 102, 255]);
+ assert_eq!(rgba, vec![26, 51, 77, 255, 102, 128, 153, 255]);
}
#[test]
@@ -349,6 +378,12 @@ mod tests {
assert!(rgba_from_planar(&[], 0, 4, 4, 3).is_err());
}
+ #[test]
+ fn malformed_interleaved_audio_is_refused_at_the_handoff() {
+ assert!(from_output("bad-audio", &[0.5, 0.5, 0.5], &[0.1, 0.2, 0.3], 1, 1, 1, 3, 24.0, 2, 32_000).is_err());
+ assert!(from_output("bad-rate", &[0.5, 0.5, 0.5], &[0.1, 0.2], 1, 1, 1, 3, 24.0, 2, 0).is_err());
+ }
+
fn sample(job_id: &str) -> RenderedVideo {
from_output(job_id, &[0.5, 0.5, 0.5], &[0.25, -0.25], 1, 1, 1, 3, 24.0, 2, 48_000).unwrap()
}
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index 359dc8d..e53192e 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -1,5 +1,5 @@
import { ArrowLeft, BookOpen, Download, Film, Save, Sparkles } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import type { GenerationJob, ProjectConfig, ProjectRecord } from "../lib/project";
import { cancelVidfabGeneration, CHECKING_PROVIDERS, type RuntimeStatus } from "../lib/runtime";
import { ExitGuardDialog, type OngoingGeneration } from "./ExitGuardDialog";
@@ -46,19 +46,68 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
* sees. Optional, so a test can mount the workspace on its own. */
onOngoingGenerationsChange?: (jobs: OngoingGeneration[]) => void;
}) {
- const [config, setConfig] = useState(project.config);
- /* What the engine says about a render, and the saving of the file it
- produces. Mounted HERE, not in the Generator: a render takes minutes, and
- a user who spends them on the timeline used to unmount the only listeners
- there were — the finished frames then arrived at nobody and were dropped. */
- useGenerationEvents({ folderPath: project.folderPath, onChange: (update) => { setConfig(update); setDirty(true); } });
+ const [config, setConfigState] = useState(project.config);
+ const configRef = useRef(config);
+ configRef.current = config;
const [view, setView] = useState<ProjectView>(initialView);
const [selectedGenerationJobId, setSelectedGenerationJobId] = useState<string | undefined>(project.config.generationJobs[0]?.id);
const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
- /* The back control asks before it navigates when there is a run to lose. */
const [leaveGuard, setLeaveGuard] = useState(false);
+ /** Every save is ordered. Without this, an older manual save and a generation
+ * completion save could race and whichever disk write happened to finish
+ * last would win, even if it held the older project. */
+ const saveQueue = useRef<Promise<void>>(Promise.resolve());
+ const pendingSaves = useRef(0);
+ // Measurements also replace the config object, but deliberately do not make
+ // the project dirty. A revision counts only writes that the Save button is
+ // responsible for, so a measurement landing during a save cannot make a
+ // successfully persisted project look unsaved.
+ const dirtyRevision = useRef(0);
+
+ const applyConfig = (next: ConfigUpdate): ProjectConfig => {
+ const resolved = typeof next === "function" ? next(configRef.current) : next;
+ configRef.current = resolved;
+ setConfigState(resolved);
+ return resolved;
+ };
+
+ const persist = (record: ProjectRecord): Promise<void> => {
+ const savedRevision = dirtyRevision.current;
+ pendingSaves.current += 1;
+ setSaving(true);
+ const attempt = saveQueue.current
+ .catch(() => undefined)
+ .then(async () => {
+ setSaveError(null);
+ await onSave(record);
+ });
+ saveQueue.current = attempt.then(() => undefined, () => undefined);
+ return attempt
+ .then(() => {
+ // A later edit did not ride in this write, so its Save button must stay
+ // enabled. Background measurements do not advance this revision.
+ if (dirtyRevision.current === savedRevision) setDirty(false);
+ })
+ .catch((reason) => {
+ setSaveError(reason instanceof Error ? reason.message : String(reason));
+ })
+ .finally(() => {
+ pendingSaves.current -= 1;
+ if (pendingSaves.current === 0) setSaving(false);
+ });
+ };
+
+ /* What the engine says about a render, and the saving of the file it
+ produces. Mounted HERE, not in the Generator: a render takes minutes, and
+ a user who spends them on the timeline used to unmount the only listeners
+ there were — the finished frames then arrived at nobody and were dropped. */
+ useGenerationEvents({
+ folderPath: project.folderPath,
+ onChange: (update) => { applyConfig(update); dirtyRevision.current += 1; setDirty(true); },
+ onCompleted: () => { void persist({ ...project, config: configRef.current }); },
+ });
/* Derived through a key of identity and status rather than from the job
objects: a render in progress rewrites generationJobs on every progress
@@ -96,7 +145,8 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
TimelineView's measurement flush. Views that only ever change the project
from a click still pass a plain value. */
const changeConfig = (next: ConfigUpdate) => {
- setConfig(next);
+ applyConfig(next);
+ dirtyRevision.current += 1;
setDirty(true);
};
@@ -108,19 +158,10 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
lose. Everything measured here is re-derivable from the files themselves,
so a measurement that never rides along with a real save costs a re-decode
and nothing else. */
- const recordMeasurement = (update: (current: ProjectConfig) => ProjectConfig) => setConfig(update);
+ const recordMeasurement = (update: (current: ProjectConfig) => ProjectConfig) => { applyConfig(update); };
const save = async (record?: ProjectRecord) => {
- setSaving(true);
- setSaveError(null);
- try {
- await onSave(record ?? { ...project, config });
- setDirty(false);
- } catch (reason) {
- setSaveError(reason instanceof Error ? reason.message : String(reason));
- } finally {
- setSaving(false);
- }
+ await persist(record ?? { ...project, config: configRef.current });
};
return <div className="project-shell">
@@ -182,7 +223,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
up front reported a saved project even when the write then failed,
and swallowed the reason; save() clears only on success and surfaces
the failure in the toast. */
- onRecord={(record) => { setConfig(record.config); void save(record); }}
+ onRecord={(record) => { applyConfig(record.config); void save(record); }}
/></footer>
{leaveGuard && <ExitGuardDialog jobs={ongoing} destination="library" onConfirm={leave} onCancel={() => setLeaveGuard(false)} />}
{saveError && <div className="toast" role="alert"><strong>Couldn’t save project</strong><span>{saveError}</span><button onClick={() => setSaveError(null)}>Dismiss</button></div>}
diff --git a/src/components/workspace/useGenerationEvents.test.tsx b/src/components/workspace/useGenerationEvents.test.tsx
index cb7d124..2170834 100644
--- a/src/components/workspace/useGenerationEvents.test.tsx
+++ b/src/components/workspace/useGenerationEvents.test.tsx
@@ -33,11 +33,11 @@ afterEach(() => {
/** A project with one draft scene, and a harness that keeps whatever the hook
* writes — the same shape the workspace holds it in. */
-function harness() {
+function harness(onCompleted?: (jobId: string) => void) {
const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
const state = { config: fresh };
function Harness() {
- useGenerationEvents({ folderPath: "C:\\Ceramic Lamp", onChange: (update) => { state.config = update(state.config); } });
+ useGenerationEvents({ folderPath: "C:\\Ceramic Lamp", onChange: (update) => { state.config = update(state.config); }, onCompleted });
return null;
}
render(<Harness />);
@@ -54,7 +54,8 @@ const emit = async (name: string, payload: unknown) => {
describe("what the app does with the engine's events", () => {
it("saves the frames the moment the engine says they are ready, and records the file", async () => {
vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 4_200_000, note: null });
- const { jobId, job, state } = harness();
+ const completed = vi.fn();
+ const { jobId, job, state } = harness(completed);
await emit("vidfab-job", { jobId, state: "framesReady", detail: "Frames and audio are ready to be encoded." });
expect(saveGeneratedScene).toHaveBeenCalledWith(expect.objectContaining({ folderPath: "C:\\Ceramic Lamp", jobId }));
@@ -65,6 +66,7 @@ describe("what the app does with the engine's events", () => {
outputRelativePath: "media/generated/job-01.mp4",
error: null,
});
+ expect(completed).toHaveBeenCalledWith(jobId);
// What was written has to survive a save and a reload, so it has to parse.
expect(parseProjectConfig(state.config)).toBeTruthy();
});
@@ -143,6 +145,15 @@ describe("what the app does with the engine's events", () => {
expect(job().status).toBe("completed");
});
+ it("never rolls overall progress back when a later stage reports a smaller local counter", async () => {
+ const { jobId, job } = harness();
+ await emit("vidfab-progress", { jobId, stage: "denoising", step: 40, totalSteps: 50 });
+ const furthest = job().progress;
+ await emit("vidfab-progress", { jobId, stage: "audioDecode", step: 0, totalSteps: 0 });
+ expect(job().progress).toBe(furthest);
+ expect(job().progress).toBeGreaterThan(0.7);
+ });
+
it("passes queued, failed and cancelled through as themselves", async () => {
const { jobId, job } = harness();
await emit("vidfab-job", { jobId, state: "queued", detail: "Queued behind any active vidfab generation." });
diff --git a/src/components/workspace/useGenerationEvents.ts b/src/components/workspace/useGenerationEvents.ts
index a5d74e3..2aabbfd 100644
--- a/src/components/workspace/useGenerationEvents.ts
+++ b/src/components/workspace/useGenerationEvents.ts
@@ -39,17 +39,24 @@ interface ProgressEvent {
const RENDER_CEILING = 0.9;
const ENCODE_FLOOR = 0.9;
-export function useGenerationEvents({ folderPath, onChange }: {
+export function useGenerationEvents({ folderPath, onChange, onCompleted }: {
folderPath: string;
/** The updater form, always: every write here happens after an await, so the
* config this component last saw is not the one to build from. */
onChange: (update: (current: ProjectConfig) => ProjectConfig) => void;
+ /** Called only after the MP4 path, generated asset, and timeline clip state
+ * have all been committed to the in-memory project. The workspace uses this
+ * exact boundary to persist the finished generation without waiting for the
+ * user to click Save. */
+ onCompleted?: (jobId: string) => void;
}) {
/* Held in refs so the subscription is made ONCE. It has to be: re-subscribing
on every progress tick would drop events in the gap, and these events are
the only record that a render happened at all. */
const write = useRef(onChange);
write.current = onChange;
+ const completed = useRef(onCompleted);
+ completed.current = onCompleted;
const folder = useRef(folderPath);
folder.current = folderPath;
/** Scenes already being encoded, so a repeated event — or a remount in
@@ -65,6 +72,23 @@ export function useGenerationEvents({ folderPath, onChange }: {
generationJobs: current.generationJobs.map((job) => (job.id === jobId ? { ...job, ...updates, updatedAt: new Date().toISOString() } : job)),
}));
};
+ const updateProgress = (jobId: string, progress: number, stage: GenerationJob["stage"]) => {
+ write.current((current) => ({
+ ...current,
+ generationJobs: current.generationJobs.map((job) => {
+ if (job.id !== jobId || job.status === "ready" || job.status === "completed" || job.status === "failed" || job.status === "cancelled") return job;
+ return {
+ ...job,
+ status: "generating",
+ stage,
+ // vidfab stages do not share one counter. A later stage can report
+ // a smaller local percentage, but overall progress cannot regress.
+ progress: Math.max(job.progress, progress),
+ updatedAt: new Date().toISOString(),
+ };
+ }),
+ }));
+ };
/** Encode the frames the engine just finished, and write the file.
*
@@ -115,6 +139,7 @@ export function useGenerationEvents({ folderPath, onChange }: {
})),
},
}));
+ completed.current?.(jobId);
} catch (reason) {
/* The render happened and the file did not. Failed is the honest state:
there is nothing to insert into the timeline, and the only way to get
@@ -135,11 +160,11 @@ export function useGenerationEvents({ folderPath, onChange }: {
const progress = payload.totalSteps > 0
? Math.min(RENDER_CEILING - 0.02, 0.12 + (Math.max(0, payload.step) / payload.totalSteps) * (RENDER_CEILING - 0.14))
: payload.stage === "delivering" ? RENDER_CEILING - 0.02 : 0.08;
- updateJob(payload.jobId, {
- status: "generating",
- stage: payload.stage === "starting" || payload.stage === "transformerLoad" ? "preparing" : "generating",
+ updateProgress(
+ payload.jobId,
progress,
- });
+ payload.stage === "starting" || payload.stage === "transformerLoad" ? "preparing" : "generating",
+ );
}),
listen<JobEvent>("vidfab-job", ({ payload }) => {
if (disposed) return;
diff --git a/src/lib/generatedVideo.test.ts b/src/lib/generatedVideo.test.ts
index a955266..8230e32 100644
--- a/src/lib/generatedVideo.test.ts
+++ b/src/lib/generatedVideo.test.ts
@@ -2,10 +2,25 @@
import { invoke } from "@tauri-apps/api/core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { releaseRendered, renderedSummary, saveGeneratedScene } from "./generatedVideo";
+import { audioSamplesFromIpc, bytesFromIpc, releaseRendered, renderedSummary, resampleInterleaved, saveGeneratedScene } from "./generatedVideo";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+const muxed = vi.hoisted(() => ({
+ configs: [] as Array<Record<string, unknown>>,
+ audioChunks: 0,
+ videoChunks: 0,
+}));
+vi.mock("mp4-muxer", () => ({
+ ArrayBufferTarget: class { buffer = new Uint8Array([1, 2, 3, 4]).buffer; },
+ Muxer: class {
+ constructor(config: Record<string, unknown>) { muxed.configs.push(config); }
+ addVideoChunk() { muxed.videoChunks += 1; }
+ addAudioChunk() { muxed.audioChunks += 1; }
+ finalize() { /* the fake target already owns its test bytes */ }
+ },
+}));
+
const invoked = vi.mocked(invoke);
const scope = globalThis as unknown as Record<string, unknown>;
@@ -19,14 +34,21 @@ const desktop = () => { scope.__TAURI_INTERNALS__ = {}; };
beforeEach(() => {
invoked.mockReset();
+ muxed.configs.length = 0;
+ muxed.audioChunks = 0;
+ muxed.videoChunks = 0;
delete scope.__TAURI_INTERNALS__;
delete scope.VideoEncoder;
delete scope.VideoFrame;
+ delete scope.AudioEncoder;
+ delete scope.AudioData;
});
afterEach(() => {
delete scope.__TAURI_INTERNALS__;
delete scope.VideoEncoder;
delete scope.VideoFrame;
+ delete scope.AudioEncoder;
+ delete scope.AudioData;
});
/* jsdom has no WebCodecs, so nothing here encodes anything — and that is
@@ -91,3 +113,130 @@ describe("what the app asks Rust about a render", () => {
await expect(releaseRendered("job-01")).resolves.toBe(false);
});
});
+
+describe("generated audio at the Rust/webview boundary", () => {
+ it("reads raw response bytes as little-endian float samples, not as byte-valued samples", () => {
+ const original = new Float32Array([0.25, -0.5, 0.75, -1]);
+ const rawBytes = Array.from(new Uint8Array(original.buffer));
+ expect(Array.from(audioSamplesFromIpc(rawBytes, 4))).toEqual(Array.from(original));
+ });
+
+ it("keeps the exact window of an IPC byte view", () => {
+ const backing = new Uint8Array([99, 1, 2, 3, 4, 88]);
+ expect(Array.from(bytesFromIpc(backing.subarray(1, 5)))).toEqual([1, 2, 3, 4]);
+ });
+
+ it("refuses a truncated or mismatched PCM body", () => {
+ expect(() => audioSamplesFromIpc([0, 0, 0], 1)).toThrow(/whole 32-bit PCM/);
+ expect(() => audioSamplesFromIpc([0, 0, 0, 0], 2)).toThrow(/promised 2 audio samples/);
+ });
+
+ it("resamples every interleaved channel without crossing channel boundaries", () => {
+ const stereo = new Float32Array([0, 10, 1, 11, 2, 12]);
+ expect(Array.from(resampleInterleaved(stereo, 2, 3, 6))).toEqual([
+ 0, 10,
+ 0.5, 10.5,
+ 1, 11,
+ 1.5, 11.5,
+ 2, 12,
+ 2, 12,
+ ]);
+ });
+
+ it("still saves the pictures when this webview cannot encode AAC", async () => {
+ desktop();
+
+ class FakeVideoFrame { close() { /* owned by the test */ } }
+ class FakeVideoEncoder {
+ static isConfigSupported = async (config: unknown) => ({ supported: true, config });
+ state = "configured";
+ encodeQueueSize = 0;
+ private output: (chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata) => void;
+ constructor(init: VideoEncoderInit) { this.output = init.output; }
+ configure() { /* accepted */ }
+ encode() { this.output({} as EncodedVideoChunk); }
+ async flush() { /* synchronous fake output */ }
+ close() { this.state = "closed"; }
+ }
+ class FakeAudioEncoder {
+ static isConfigSupported = async () => ({ supported: false });
+ }
+ scope.VideoFrame = FakeVideoFrame;
+ scope.VideoEncoder = FakeVideoEncoder;
+ scope.AudioData = class {};
+ scope.AudioEncoder = FakeAudioEncoder;
+
+ invoked.mockImplementation(async (command: string) => {
+ if (command === "generated_summary") return summary({ width: 1, height: 1, frameCount: 1, audioSampleRate: 32_000, audioSamples: 4 });
+ if (command === "generated_frame") return [1, 2, 3, 255];
+ if (command === "write_generated_video") return { relativePath: "media/generated/job-01.mp4", bytes: 4 };
+ return true;
+ });
+
+ await expect(saveGeneratedScene({ folderPath: "C:\\Project", jobId: "job-01" })).resolves.toMatchObject({
+ relativePath: "media/generated/job-01.mp4",
+ note: expect.stringMatching(/without sound/),
+ });
+ expect(invoked).not.toHaveBeenCalledWith("generated_audio", expect.anything());
+ expect(muxed.configs[0]).not.toHaveProperty("audio");
+ expect(muxed.videoChunks).toBe(1);
+ expect(invoked).toHaveBeenCalledWith("release_generated_frames", { jobId: "job-01" });
+ });
+
+ it("encodes vidfab's interleaved PCM and adds an AAC track to the saved MP4", async () => {
+ desktop();
+ const audioData: Array<Record<string, unknown>> = [];
+
+ class FakeVideoFrame { close() { /* owned by the test */ } }
+ class FakeVideoEncoder {
+ static isConfigSupported = async (config: unknown) => ({ supported: true, config });
+ state = "configured";
+ encodeQueueSize = 0;
+ private output: (chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata) => void;
+ constructor(init: VideoEncoderInit) { this.output = init.output; }
+ configure() { /* accepted */ }
+ encode() { this.output({} as EncodedVideoChunk); }
+ async flush() { /* synchronous fake output */ }
+ close() { this.state = "closed"; }
+ }
+ class FakeAudioData {
+ constructor(init: AudioDataInit) { audioData.push(init as unknown as Record<string, unknown>); }
+ close() { /* owned by the test */ }
+ }
+ class FakeAudioEncoder {
+ static isConfigSupported = async (config: unknown) => ({ supported: true, config });
+ state = "configured";
+ encodeQueueSize = 0;
+ private output: (chunk: EncodedAudioChunk, meta?: EncodedAudioChunkMetadata) => void;
+ constructor(init: AudioEncoderInit) { this.output = init.output; }
+ configure() { /* accepted */ }
+ encode() { this.output({} as EncodedAudioChunk); }
+ async flush() { /* synchronous fake output */ }
+ close() { this.state = "closed"; }
+ }
+ scope.VideoFrame = FakeVideoFrame;
+ scope.VideoEncoder = FakeVideoEncoder;
+ scope.AudioData = FakeAudioData;
+ scope.AudioEncoder = FakeAudioEncoder;
+
+ const pcm = new Float32Array([0.25, -0.5, 0.75, -1]);
+ invoked.mockImplementation(async (command: string) => {
+ if (command === "generated_summary") return summary({ width: 1, height: 1, frameCount: 1, audioSampleRate: 32_000, audioSamples: pcm.length });
+ if (command === "generated_frame") return [1, 2, 3, 255];
+ if (command === "generated_audio") return Array.from(new Uint8Array(pcm.buffer));
+ if (command === "write_generated_video") return { relativePath: "media/generated/job-01.mp4", bytes: 4 };
+ return true;
+ });
+
+ await expect(saveGeneratedScene({ folderPath: "C:\\Project", jobId: "job-01" })).resolves.toMatchObject({
+ relativePath: "media/generated/job-01.mp4",
+ note: null,
+ });
+ expect(muxed.videoChunks).toBe(1);
+ expect(muxed.audioChunks).toBeGreaterThan(0);
+ expect(muxed.configs[0]).toMatchObject({ audio: { codec: "aac", numberOfChannels: 2, sampleRate: 32_000 } });
+ expect(audioData[0]).toMatchObject({ format: "f32", numberOfChannels: 2, numberOfFrames: 2, sampleRate: 32_000, timestamp: 0 });
+ expect(Array.from(audioData[0].data as Float32Array)).toEqual(Array.from(pcm));
+ expect(invoked).toHaveBeenCalledWith("release_generated_frames", { jobId: "job-01" });
+ });
+});
diff --git a/src/lib/generatedVideo.ts b/src/lib/generatedVideo.ts
index 15611ab..b7581c8 100644
--- a/src/lib/generatedVideo.ts
+++ b/src/lib/generatedVideo.ts
@@ -65,14 +65,43 @@ export async function renderedSummary(jobId: string): Promise<RenderedSummary |
return invoke<RenderedSummary | null>("generated_summary", { jobId });
}
+type IpcBytes = ArrayBuffer | ArrayBufferView | number[];
+
+/** Tauri's raw response is an ArrayBuffer in the desktop webview, while its
+ * test/mock transports and some older runtimes expose the same body as a byte
+ * array. Normalize both without ever treating byte values as PCM samples. */
+export function bytesFromIpc(raw: IpcBytes): Uint8Array {
+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
+ if (ArrayBuffer.isView(raw)) return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
+ return Uint8Array.from(raw);
+}
+
/** One frame's pixels, RGBA, straight out of the render. */
async function renderedFrame(jobId: string, index: number): Promise<Uint8Array> {
- return new Uint8Array(await invoke<ArrayBuffer>("generated_frame", { jobId, index }));
+ return bytesFromIpc(await invoke<IpcBytes>("generated_frame", { jobId, index }));
+}
+
+/** Turns the raw IPC body into the interleaved samples vidfab produced. */
+export function audioSamplesFromIpc(raw: IpcBytes, expectedSamples: number): Float32Array {
+ const bytes = bytesFromIpc(raw);
+ if (bytes.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0) {
+ throw new Error(`The render's audio buffer has ${bytes.byteLength} bytes, which is not whole 32-bit PCM.`);
+ }
+ // Copy the exact view. Constructing Float32Array from Uint8Array would turn
+ // each byte into a sample; constructing it from an offset view can also fail
+ // alignment. vidfab and Rust both use native little-endian f32 PCM.
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ const samples = new Float32Array(copy.buffer);
+ if (samples.length !== expectedSamples) {
+ throw new Error(`The render promised ${expectedSamples} audio samples, but ${samples.length} came back.`);
+ }
+ return samples;
}
/** The render's soundtrack, interleaved, as Rust holds it. */
-async function renderedAudio(jobId: string): Promise<Float32Array> {
- return new Float32Array(await invoke<ArrayBuffer>("generated_audio", { jobId }));
+async function renderedAudio(jobId: string, expectedSamples: number): Promise<Float32Array> {
+ return audioSamplesFromIpc(await invoke<IpcBytes>("generated_audio", { jobId }), expectedSamples);
}
/** Gives the frames back. Called on the way out whether or not a file was
@@ -156,19 +185,47 @@ function frameFactory(width: number, height: number) {
};
}
-/** Whether this machine will encode the render's own sound as AAC. The render
- * decides the rate and the channel count, so the question is asked with those
- * numbers rather than with the export pipeline's 48 kHz stereo. */
-async function audioSupported(summary: RenderedSummary): Promise<boolean> {
- if (summary.audioSamples === 0 || summary.audioChannels <= 0 || summary.audioSampleRate <= 0) return false;
- if (typeof AudioEncoder === "undefined" || typeof AudioData === "undefined") return false;
- const support = await AudioEncoder.isConfigSupported({
- codec: AUDIO_CODEC,
- sampleRate: summary.audioSampleRate,
- numberOfChannels: summary.audioChannels,
- bitrate: AUDIO_BITRATE,
- }).catch(() => ({ supported: false }));
- return Boolean(support.supported);
+/** The render's own AAC configuration, or null for a genuinely silent render.
+ * Sound that exists is never quietly omitted from the MP4. */
+async function audioConfig(summary: RenderedSummary): Promise<AudioEncoderConfig | null> {
+ if (summary.audioSamples === 0) return null;
+ if (summary.audioChannels <= 0 || summary.audioSampleRate <= 0 || summary.audioSamples % summary.audioChannels !== 0) {
+ throw new Error("The render returned audio with invalid channel or sample-rate metadata.");
+ }
+ if (typeof AudioEncoder === "undefined" || typeof AudioData === "undefined") return null;
+ for (const sampleRate of [...new Set([summary.audioSampleRate, 48_000, 44_100])]) {
+ const config: AudioEncoderConfig = {
+ codec: AUDIO_CODEC,
+ sampleRate,
+ numberOfChannels: summary.audioChannels,
+ bitrate: AUDIO_BITRATE,
+ };
+ const support = await AudioEncoder.isConfigSupported(config).catch(() => ({ supported: false }));
+ if (support.supported) return config;
+ }
+ return null;
+}
+
+/** Linear PCM resampling is enough here: vidfab's soundtrack is already the
+ * final mix, and this only adapts its rate to an AAC configuration the OS
+ * exposes. Channels remain interleaved throughout. */
+export function resampleInterleaved(samples: Float32Array, channels: number, fromRate: number, toRate: number): Float32Array {
+ if (fromRate === toRate) return samples;
+ const inputFrames = Math.floor(samples.length / channels);
+ const outputFrames = Math.max(1, Math.round(inputFrames * toRate / fromRate));
+ const output = new Float32Array(outputFrames * channels);
+ for (let frame = 0; frame < outputFrames; frame += 1) {
+ const source = Math.min(inputFrames - 1, frame * fromRate / toRate);
+ const left = Math.floor(source);
+ const right = Math.min(inputFrames - 1, left + 1);
+ const mix = source - left;
+ for (let channel = 0; channel < channels; channel += 1) {
+ const a = samples[left * channels + channel];
+ const b = samples[right * channels + channel];
+ output[frame * channels + channel] = a + (b - a) * mix;
+ }
+ }
+ return output;
}
/** Feeds the render's interleaved samples to the AAC encoder, in the blocks
@@ -176,40 +233,34 @@ async function audioSupported(summary: RenderedSummary): Promise<boolean> {
async function encodeAudio(
summary: RenderedSummary,
samples: Float32Array,
+ config: AudioEncoderConfig,
add: (chunk: EncodedAudioChunk, meta?: EncodedAudioChunkMetadata) => void,
-): Promise<void> {
+): Promise<number> {
const channels = summary.audioChannels;
- const total = Math.floor(samples.length / channels);
+ const sampleRate = config.sampleRate ?? summary.audioSampleRate;
+ const prepared = resampleInterleaved(samples, channels, summary.audioSampleRate, sampleRate);
+ const total = Math.floor(prepared.length / channels);
const failure: { reason: Error | null } = { reason: null };
+ let chunks = 0;
const encoder = new AudioEncoder({
- output: (chunk, meta) => add(chunk, meta),
+ output: (chunk, meta) => { chunks += 1; add(chunk, meta); },
error: (reason) => { failure.reason = reason instanceof Error ? reason : new Error(String(reason)); },
});
- encoder.configure({
- codec: AUDIO_CODEC,
- sampleRate: summary.audioSampleRate,
- numberOfChannels: channels,
- bitrate: AUDIO_BITRATE,
- });
+ encoder.configure(config);
try {
for (let offset = 0; offset < total; offset += AUDIO_BLOCK) {
if (failure.reason) throw failure.reason;
const count = Math.min(AUDIO_BLOCK, total - offset);
- // f32-planar: every channel's block laid end to end, de-interleaved from
- // the way vidfab returns them.
- const planar = new Float32Array(count * channels);
- for (let channel = 0; channel < channels; channel += 1) {
- for (let frame = 0; frame < count; frame += 1) {
- planar[channel * count + frame] = samples[(offset + frame) * channels + channel];
- }
- }
+ // vidfab's C API returns [frame0-L, frame0-R, frame1-L, frame1-R, ...].
+ // WebCodecs calls that layout `f32`; `f32-planar` means something else.
+ const interleaved = prepared.slice(offset * channels, (offset + count) * channels);
const data = new AudioData({
- format: "f32-planar",
- sampleRate: summary.audioSampleRate,
+ format: "f32",
+ sampleRate,
numberOfFrames: count,
numberOfChannels: channels,
- timestamp: Math.round((offset * 1_000_000) / summary.audioSampleRate),
- data: planar,
+ timestamp: Math.round((offset * 1_000_000) / sampleRate),
+ data: interleaved,
});
encoder.encode(data);
data.close();
@@ -217,6 +268,8 @@ async function encodeAudio(
}
await encoder.flush();
if (failure.reason) throw failure.reason;
+ if (chunks === 0) throw new Error("The AAC encoder finished without producing a soundtrack.");
+ return chunks;
} finally {
if (encoder.state !== "closed") encoder.close();
}
@@ -252,7 +305,21 @@ export async function saveGeneratedScene(options: {
const fps = summary.fps > 0 ? summary.fps : 24;
const bitrate = bitrateFor(summary.width, summary.height, fps, GENERATED_QUALITY);
const { codec } = await pickCodec(summary.width, summary.height, fps, bitrate);
- const withAudio = await audioSupported(summary);
+ const sound = await audioConfig(summary);
+ const audioChunks: Array<{ chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }> = [];
+ let note: string | null = null;
+ if (summary.audioSamples > 0) {
+ if (sound) {
+ try {
+ await encodeAudio(summary, await renderedAudio(jobId, summary.audioSamples), sound, (chunk, meta) => audioChunks.push({ chunk, meta }));
+ } catch (reason) {
+ note = `Saved without sound: ${describe(reason)}`;
+ }
+ } else {
+ note = "Saved without sound: this computer's encoder would not take the render's audio.";
+ }
+ }
+ const withAudio = audioChunks.length > 0;
const { ArrayBufferTarget, Muxer } = await import("mp4-muxer");
const target = new ArrayBufferTarget();
@@ -260,7 +327,7 @@ export async function saveGeneratedScene(options: {
target,
video: { codec: outputCodec("h264").muxer, width: summary.width, height: summary.height, frameRate: Math.round(fps) },
...(withAudio
- ? { audio: { codec: "aac" as const, numberOfChannels: summary.audioChannels, sampleRate: summary.audioSampleRate } }
+ ? { audio: { codec: "aac" as const, numberOfChannels: summary.audioChannels, sampleRate: sound!.sampleRate! } }
: {}),
fastStart: "in-memory",
});
@@ -300,14 +367,7 @@ export async function saveGeneratedScene(options: {
if (encoder.state !== "closed") encoder.close();
}
- let note: string | null = null;
- if (withAudio) {
- await encodeAudio(summary, await renderedAudio(jobId), (chunk, meta) => muxer.addAudioChunk(chunk, meta));
- } else if (summary.audioSamples > 0) {
- // The render HAD sound and the file does not: say so rather than hand
- // back a silent video that looks complete.
- note = "Saved without sound: this computer's encoder would not take the render's audio.";
- }
+ audioChunks.forEach(({ chunk, meta }) => muxer.addAudioChunk(chunk, meta));
muxer.finalize();
const written = await writeGeneratedVideo(folderPath, jobId, new Uint8Array(target.buffer));