8000 fix(render): probe VideoFrame upload before claiming WebGPU by johannboehme · Pull Request #31 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions frontend/src/local/capabilities.test.ts
Original file line number Diff line number Diff line change
Expan 8000 d Up @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
detectCapabilities,
meetsMinRequirements,
probeWebGPUVideoFrameUpload,
supportsLargeMediaFiles,
LEGACY_BROWSER_MAX_FILE_BYTES,
type Capabilities,
Expand Down Expand Up @@ -236,3 +237,76 @@ describe("detectCapabilities — gpu-related fields", () => {
expect(caps.webgl2).toBe(false);
});
});

describe("probeWebGPUVideoFrameUpload", () => {
// jsdom hat weder OffscreenCanvas noch VideoFrame — wir mocken minimal,
// damit der Probe-Pfad einmal mit "upload geht" und einmal mit "upload
// wirft" durchläuft. Modelliert Firefox 148, das einen Adapter hat aber
// bei copyExternalImageToTexture(VideoFrame) wirft.

const FakeOffscreenCanvas = class {
width: number;
height: number;
constructor(w: number, h: number) {
this.width = w;
this.height = h;
}
getContext() {
return {
fillStyle: "",
fillRect: () => undefined,
};
}
};
const FakeVideoFrame = class {
constructor(_src: unknown, _opts: unknown) {}
close() {}
};

function makeAdapter(opts: { uploadThrows: boolean }): GPUAdapter {
const fakeQueue = {
copyExternalImageToTexture: () => {
if (opts.uploadThrows) {
throw new TypeError(
"GPUQueue.copyExternalImageToTexture: 'source' member …",
);
}
},
};
const fakeDevice = {
queue: fakeQueue,
pushErrorScope: () => undefined,
popErrorScope: async () => null,
createTexture: () => ({ destroy: () => undefined }),
destroy: () => undefined,
};
return {
requestDevice: async () => fakeDevice,
} as unknown as GPUAdapter;
}

beforeEach(() => {
vi.stubGlobal("OffscreenCanvas", FakeOffscreenCanvas);
vi.stubGlobal("VideoFrame", FakeVideoFrame);
vi.stubGlobal("GPUTextureUsage", {
COPY_DST: 1,
TEXTURE_BINDING: 4,
});
});

it("returns true when copyExternalImageToTexture accepts a VideoFrame", async () => {
const adapter = makeAdapter({ uploadThrows: false });
expect(await probeWebGPUVideoFrameUpload(adapter)).toBe(true);
});

it("returns false when copyExternalImageToTexture throws (Firefox today)", async () => {
const adapter = makeAdapter({ uploadThrows: true });
expect(await probeWebGPUVideoFrameUpload(adapter)).toBe(false);
});

it("returns false when VideoFrame is missing in the environment", async () => {
vi.stubGlobal("VideoFrame", undefined);
const adapter = makeAdapter({ uploadThrows: false });
expect(await probeWebGPUVideoFrameUpload(adapter)).toBe(false);
});
});
74 changes: 63 additions & 11 deletions frontend/src/local/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,32 +92,84 @@ export function detectCapabilities(): Capabilities {
let webgpuProbeCache: Promise<boolean> | null = null;

/**
* Real WebGPU probe: actually calls `navigator.gpu.requestAdapter()`.
* This is the only way to know if the platform has a usable adapter
* (Linux Chrome / FF can have `navigator.gpu` but no compatible
* adapter). Cached — call as many times as you like.
*
* Usage at app boot:
* const caps = detectCapabilities();
* caps.webgpu = await probeWebGPU();
* // … pass `caps` to consumers (compositor, factory, etc.)
* Real WebGPU probe: actually calls `navigator.gpu.requestAdapter()`,
* then verifies that `queue.copyExternalImageToTexture` accepts a
* `VideoFrame`. The video-source probe matters because the renderer
* uploads `VideoFrame`s every tick — Firefox 148 ships an adapter but
* its impl of `copyExternalImageToTexture` only accepts ImageBitmap /
* HTMLImageElement / HTMLCanvasElement / OffscreenCanvas, so passing a
* `VideoFrame` throws TypeError on every tick. Reporting webgpu=false
* for that case lets the WebGL2 fallback take over cleanly.
*/
export function probeWebGPU(): Promise<boolean> {
if (webgpuProbeCache) return webgpuProbeCache;
webgpuProbeCache = (async () => {
if (typeof navigator === "undefined") return false;
const nav = navigator as Navigator & { gpu?: GPU };
if (!nav.gpu) return false;
let adapter: GPUAdapter | null = null;
try {
const adapter = await nav.gpu.requestAdapter();
return adapter != null;
adapter = await nav.gpu.requestAdapter();
} catch {
return false;
}
if (!adapter) return false;
return await probeWebGPUVideoFrameUpload(adapter);
})();
return webgpuProbeCache;
}

/**
* Tries `queue.copyExternalImageToTexture({ source: VideoFrame })` once.
* Returns false if the impl throws (Firefox today) or rejects (anything
* unexpected). On success the device + texture are cleaned up.
*
* Exported so the render worker (which does its own `requestAdapter()`
* before spawning the compositor) can reuse the same check.
*/
export async function probeWebGPUVideoFrameUpload(
adapter: GPUAdapter,
): Promise<boolean> {
if (typeof OffscreenCanvas === "undefined") return false;
if (typeof VideoFrame === "undefined") {
// No VideoFrame in this browser — nothing to render anyway. Refuse
// WebGPU so the WebGL2 fallback (which uploads via `<video>`) runs.
return false;
}
let device: GPUDevice | null = null;
let frame: VideoFrame | null = null;
let tex: GPUTexture | null = null;
try {
device = await adapter.requestDevice();
const canvas = new OffscreenCanvas(2, 2);
const ctx = canvas.getContext("2d");
if (!ctx) return false;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 2, 2);
frame = new VideoFrame(canvas, { timestamp: 0 });
tex = device.createTexture({
label: "webgpu-probe",
size: { width: 2, height: 2, depthOrArrayLayers: 1 },
format: "rgba8unorm",
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
});
device.pushErrorScope("validation");
device.queue.copyExternalImageToTexture(
{ source: frame, flipY: false },
{ texture: tex },
{ width: 2, height: 2, depthOrArrayLayers: 1 },
);
const err = await device.popErrorScope();
return err === null;
} catch {
return false;
} finally {
frame?.close();
tex?.destroy();
device?.destroy();
}
}

/** Test-only: clear the WebGPU probe cache. Used so a test that
* monkey-patches `navigator.gpu` can re-probe without bleeding cache
* state into the next test. */
Expand Down
11 changes: 6 additions & 5 deletions frontend/src/local/render/edit.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
import { opfs } from "../../storage/opfs";
import { loadAsset } from "../asset-source";
import type { BackendCapabilities } from "../../editor/render/factory";
import { probeWebGPUVideoFrameUpload } from "../capabilities";
import { ShowwavesVisualizer } from "./visualizer/showwaves";
import { ShowfreqsVisualizer } from "./visualizer/showfreqs";
import type { Visualizer } from "./visualizer/types";
Expand Down Expand Up @@ -122,9 +123,9 @@ const ctx = self as unknown as DedicatedWorkerGlobalScope;
/** Detect render-backend capabilities inside the worker. The compositor
* uses these to pick WebGPU → WebGL2 → Canvas2D in the Factory ladder.
* - webgl2: sync probe via OffscreenCanvas.getContext.
* - webgpu: async probe via requestAdapter — null means "API exists
* but no compatible adapter on this platform" (Linux-Chrome
* without dedicated GPU is the typical fail case). */
* - webgpu: async probe via requestAdapter() + a VideoFrame upload
* check. The upload step matters because Firefox 148 has an
* adapter but rejects VideoFrame in copyExternalImageToTexture. */
async function probeBackendCapabilities(): Promise<BackendCapabilities> {
let webgl2 = false;
try {
Expand All @@ -138,9 +139,9 @@ async function probeBackendCapabilities(): Promise<BackendCapabilities> {
if (gpu) {
try {
const adapter = await gpu.requestAdapter();
webgpu = adapter != null;
if (adapter) webgpu = await probeWebGPUVideoFrameUpload(adapter);
} catch {
/* requestAdapter threw — leave webgpu=false */
/* requestAdapter or upload-probe threw — leave webgpu=false */
}
}
return { webgl2, webgpu };
Expand Down
Loading
0