Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Speed up Space video preparation

Anand Baburajan46aa1c6c25d6
diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsx
index 0ae4dd790c..60c5c949f4 100644
--- a/web/apps/space/src/components/PostComposer.tsx
+++ b/web/apps/space/src/components/PostComposer.tsx
@@ -117,6 +117,13 @@ export const SpacePostComposer: React.FC<{
!preparingRef.current.has(draft.id),
);
pending.forEach((draft) => preparingRef.current.add(draft.id));
+ if (pending.some((draft) => isSpaceVideoFile(draft.file))) {
+ void import("utils/video-encoding/web")
+ .then(({ preloadVideoEncoderWeb }) => preloadVideoEncoderWeb())
+ .catch((error: unknown) =>
+ log.warn("Failed to preload video encoder", error),
+ );
+ }
void (async () => {
for (const draft of pending) {
if (!isActiveDraft(draft.id)) continue;
diff --git a/web/apps/space/src/utils/video-encoding/web-codecs.ts b/web/apps/space/src/utils/video-encoding/web-codecs.ts
index 582ed4f717..cb13b4d30c 100644
--- a/web/apps/space/src/utils/video-encoding/web-codecs.ts
+++ b/web/apps/space/src/utils/video-encoding/web-codecs.ts
@@ -100,13 +100,12 @@ export const encodeVideoWithWebCodecs = async (
const stream = probe.streams[0];
if (
!probe.format.format_name.split(",").includes("mov") ||
- stream?.codec_name !== "h264" ||
- !["avc1", "avc3"].includes(stream.codec_tag_string) ||
- stream.pix_fmt !== "yuv420p" ||
- ["smpte2084", "arib-std-b67"].includes(
- stream.color_transfer ?? "",
- ) ||
- stream.color_primaries === "bt2020" ||
+ !stream ||
+ !(stream.codec_name === "h264"
+ ? ["avc1", "avc3"].includes(stream.codec_tag_string)
+ : stream.codec_name === "hevc" &&
+ ["hvc1", "hev1"].includes(stream.codec_tag_string)) ||
+ !["yuv420p", "yuvj420p", "yuv420p10le"].includes(stream.pix_fmt) ||
(stream.sample_aspect_ratio &&
stream.sample_aspect_ratio !== "1:1") ||
Number(stream.start_time ?? 0) !== 0
@@ -165,13 +164,41 @@ export const encodeVideoWithWebCodecs = async (
"-",
]);
const description = await readBytes(descriptionPath);
- if (description.length < 7 || description[0] !== 1) return;
- const decoderConfig: VideoDecoderConfig = {
- codec:
+ const hevc = stream.codec_name === "hevc";
+ if (description.length < (hevc ? 23 : 7) || description[0] !== 1)
+ return;
+ let codec: string;
+ if (hevc) {
+ const profile = description[1]!;
+ const compatibility = new DataView(
+ description.buffer,
+ description.byteOffset,
+ description.byteLength,
+ ).getUint32(2);
+ const reversedCompatibility = parseInt(
+ compatibility
+ .toString(2)
+ .padStart(32, "0")
+ .split("")
+ .reverse()
+ .join(""),
+ 2,
+ );
+ const constraints = Array.from(description.slice(6, 12), (value) =>
+ value.toString(16).padStart(2, "0"),
+ )
+ .join(".")
+ .replace(/(\.00)+$/, "");
+ codec = `${stream.codec_tag_string}.${["", "A", "B", "C"][profile >> 6]}${profile & 31}.${reversedCompatibility.toString(16)}.${profile & 32 ? "H" : "L"}${description[12]}.${constraints}`;
+ } else {
+ codec =
"avc1." +
Array.from(description.slice(1, 4), (value) =>
value.toString(16).padStart(2, "0"),
- ).join(""),
+ ).join("");
+ }
+ const decoderConfig: VideoDecoderConfig = {
+ codec,
description,
hardwareAcceleration: "prefer-hardware",
};
@@ -205,6 +232,11 @@ export const encodeVideoWithWebCodecs = async (
edit.start,
frameCount,
rotation,
+ stream.pix_fmt === "yuv420p10le" ||
+ stream.color_primaries === "bt2020" ||
+ ["smpte2084", "arib-std-b67"].includes(
+ stream.color_transfer ?? "",
+ ),
decoderConfig,
encoderConfig,
signal,
@@ -264,6 +296,7 @@ const encodeFrames = async (
start: number,
frameCount: number,
rotation: number,
+ convertColor: boolean,
decoderConfig: VideoDecoderConfig,
encoderConfig: VideoEncoderConfig,
signal?: AbortSignal,
@@ -302,11 +335,13 @@ const encodeFrames = async (
let previous: VideoFrame | undefined;
let encoded = 0;
const chunks: Uint8Array<ArrayBuffer>[] = [];
- const canvas = rotation
- ? new OffscreenCanvas(encoderConfig.width, encoderConfig.height)
- : undefined;
- const context = canvas?.getContext("2d");
- if (canvas && !context) throw new Error("Couldn't rotate the video");
+ const canvas =
+ rotation || convertColor
+ ? new OffscreenCanvas(encoderConfig.width, encoderConfig.height)
+ : undefined;
+ const context = canvas?.getContext("2d", { colorSpace: "srgb" });
+ if (canvas && !context)
+ throw new Error("Couldn't prepare the video frames");
const encoder = new VideoEncoder({
output(chunk) {
if (chunk.timestamp !== frameTime(chunks.length)) {
diff --git a/web/apps/space/src/utils/video-encoding/web.ts b/web/apps/space/src/utils/video-encoding/web.ts
index 22a042c945..91f7d387e8 100644
--- a/web/apps/space/src/utils/video-encoding/web.ts
+++ b/web/apps/space/src/utils/video-encoding/web.ts
@@ -36,6 +36,10 @@ const createFFmpeg = async (signal?: AbortSignal) => {
}
};
+export const preloadVideoEncoderWeb = async () => {
+ await ffmpegLazy();
+};
+
export const determineVideoDurationWeb = async (
blob: Blob,
signal?: AbortSignal,
diff --git a/web/apps/space/tests/video-export.test.ts b/web/apps/space/tests/video-export.test.ts
index 3011b40ef7..199c17bdf9 100644
--- a/web/apps/space/tests/video-export.test.ts
+++ b/web/apps/space/tests/video-export.test.ts
@@ -69,6 +69,41 @@ test("uses WebCodecs output without running the software encoder", async () => {
expect(mocks.workers[0]!.unmount).toHaveBeenCalled();
});
+test("preloading and posting share the same in-flight engine load", async () => {
+ let finish!: () => void;
+ mocks.load.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { preloadVideoEncoderWeb } =
+ await import("../src/utils/video-encoding/web");
+ const first = preloadVideoEncoderWeb();
+ const second = preloadVideoEncoderWeb();
+ const bytes = new Uint8Array([1, 2]);
+ mocks.encode.mockResolvedValue(bytes);
+ const posted = (await exporter())();
+ expect(mocks.load).toHaveBeenCalledTimes(1);
+ expect(mocks.encode).not.toHaveBeenCalled();
+ finish();
+ await Promise.all([first, second]);
+ expect(await posted).toBe(bytes);
+ expect(mocks.load).toHaveBeenCalledTimes(1);
+ expect(mocks.workers).toHaveLength(1);
+});
+
+test("posting can retry after a failed preload", async () => {
+ mocks.load.mockRejectedValueOnce(new Error("Offline"));
+ const { preloadVideoEncoderWeb } =
+ await import("../src/utils/video-encoding/web");
+ await expect(preloadVideoEncoderWeb()).rejects.toThrow("Offline");
+ mocks.encode.mockResolvedValue(new Uint8Array([2]));
+ expect(await (await exporter())()).toEqual(new Uint8Array([2]));
+ expect(mocks.workers[0]!.terminate).toHaveBeenCalled();
+ expect(mocks.load).toHaveBeenCalledTimes(2);
+});
+
test.each(["unsupported", "failed", "missing API"])(
"keeps the software exporter available when WebCodecs is %s",
async (mode) => {
diff --git a/web/apps/space/tests/video-webcodecs.test.ts b/web/apps/space/tests/video-webcodecs.test.ts
index 580342528c..22dc3797c3 100644
--- a/web/apps/space/tests/video-webcodecs.test.ts
+++ b/web/apps/space/tests/video-webcodecs.test.ts
@@ -7,6 +7,26 @@ let encodedSources: number[];
let encoderFailure: boolean;
let stallEncoder: (() => void) | undefined;
let supported: boolean;
+let decoderConfig: VideoDecoderConfig;
+let canvasOptions: CanvasRenderingContext2DSettings[];
+
+class Canvas {
+ sourceTime = 0;
+ constructor(
+ public width: number,
+ public height: number,
+ ) {}
+ getContext(_type: string, options: CanvasRenderingContext2DSettings) {
+ canvasOptions.push(options);
+ return {
+ setTransform: vi.fn(),
+ rotate: vi.fn(),
+ drawImage: (frame: Frame) => {
+ this.sourceTime = frame.sourceTime;
+ },
+ };
+ }
+}
class Frame {
timestamp: number;
@@ -34,7 +54,8 @@ class Decoder extends EventTarget {
constructor(private init: VideoDecoderInit) {
super();
}
- configure() {
+ configure(config: VideoDecoderConfig) {
+ decoderConfig = config;
this.state = "configured";
}
decode(chunk: EncodedVideoChunk) {
@@ -94,6 +115,8 @@ beforeEach(() => {
encoderFailure = false;
stallEncoder = undefined;
supported = true;
+ canvasOptions = [];
+ vi.stubGlobal("OffscreenCanvas", Canvas);
vi.stubGlobal("VideoFrame", Frame);
vi.stubGlobal("VideoEncoder", Encoder);
vi.stubGlobal("VideoDecoder", Decoder);
@@ -111,7 +134,11 @@ beforeEach(() => {
});
afterEach(() => vi.unstubAllGlobals());
-const fixture = (fps = 30, streamChanges = {}) => {
+const fixture = (
+ fps = 30,
+ streamChanges = {},
+ description = new Uint8Array([1, 100, 0, 40, 255, 225, 0]),
+) => {
const files = new Map<string, Uint8Array | string>();
const packets = Array.from({ length: Math.ceil(fps * 20) }, (_, index) => ({
pts_time: (index / fps).toFixed(6),
@@ -156,10 +183,7 @@ const fixture = (fps = 30, streamChanges = {}) => {
},
exec: vi.fn((args: string[]) => {
if (args[0] === "-dump_attachment:v:0")
- files.set(
- args[1]!,
- new Uint8Array([1, 100, 0, 40, 255, 225, 0]),
- );
+ files.set(args[1]!, description);
else files.set(args.at(-1)!, new Uint8Array([1, 2, 3]));
return 0;
}),
@@ -210,11 +234,7 @@ test("29.97 fps and fractional selections never export more than the selected du
expect(encodedSources).toHaveLength(299);
});
-test("HDR and unsupported hardware are left to the existing exporter", async () => {
- const hdr = fixture(30, { color_transfer: "smpte2084" });
- expect(await hdr.encode(0, 10)).toBeUndefined();
- expect(hdr.ffmpeg.exec).not.toHaveBeenCalled();
- expect(hdr.files.size).toBe(0);
+test("unsupported hardware is left to the existing exporter", async () => {
supported = false;
expect(await fixture().encode(0, 10)).toBeUndefined();
expect(encodedSources).toHaveLength(0);
@@ -239,3 +259,71 @@ test("codec failures release resources and reject instead of leaving the export
expect(frames.every((frame) => frame.closed)).toBe(true);
expect(files.size).toBe(0);
});
+
+test("full-range 8-bit H.264 uses WebCodecs", async () => {
+ const { encode, files } = fixture(30, { pix_fmt: "yuvj420p" });
+ expect(await encode(0, 10)).toBeDefined();
+ expect(encodedSources).toHaveLength(300);
+ expect(frames.every((frame) => frame.closed)).toBe(true);
+ expect(files.size).toBe(0);
+});
+
+test.each(["hvc1", "hev1"])(
+ "decodes HEVC %s with its configuration record",
+ async (tag) => {
+ const description = new Uint8Array([
+ 1, 1, 96, 0, 0, 0, 176, 0, 0, 0, 0, 0, 153, 240, 0, 252, 253, 248,
+ 248, 0, 0, 15, 0,
+ ]);
+ const { encode } = fixture(
+ 60,
+ { codec_name: "hevc", codec_tag_string: tag },
+ description,
+ );
+ expect(await encode(0, 10)).toBeDefined();
+ expect(decoderConfig.codec).toBe(`${tag}.1.6.L153.b0`);
+ expect(decoderConfig.description).toBe(description);
+ expect(encodedSources).toHaveLength(300);
+ expect(canvasOptions).toHaveLength(0);
+ },
+);
+
+test.each(["arib-std-b67", "smpte2084"])(
+ "converts HEVC %s frames to SDR before encoding",
+ async (transfer) => {
+ const description = new Uint8Array([
+ 1, 2, 32, 0, 0, 0, 144, 0, 0, 0, 0, 0, 153, 240, 0, 252, 253, 250,
+ 250, 0, 0, 15, 0,
+ ]);
+ const { encode, files } = fixture(
+ 30,
+ {
+ codec_name: "hevc",
+ codec_tag_string: "hvc1",
+ pix_fmt: "yuv420p10le",
+ color_primaries: "bt2020",
+ color_transfer: transfer,
+ },
+ description,
+ );
+ expect(await encode(0, 10)).toBeDefined();
+ expect(decoderConfig.codec).toBe("hvc1.2.4.L153.90");
+ expect(canvasOptions).toEqual([{ colorSpace: "srgb" }]);
+ expect(encodedSources).toEqual(
+ Array.from({ length: 300 }, (_, i) =>
+ Math.round((i * 1_000_000) / 30),
+ ),
+ );
+ expect(frames.every((frame) => frame.closed)).toBe(true);
+ expect(files.size).toBe(0);
+ },
+);
+
+test("a truncated HEVC configuration is left to the existing exporter", async () => {
+ const { encode } = fixture(30, {
+ codec_name: "hevc",
+ codec_tag_string: "hvc1",
+ });
+ expect(await encode(0, 10)).toBeUndefined();
+ expect(encodedSources).toHaveLength(0);
+});