Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(render-farm): remux H.264 sources with frequent keyframes instead of re-encoding

Richie McIlroy735aac5cf955
diff --git a/apps/render-farm/src/transcode.test.ts b/apps/render-farm/src/transcode.test.ts
index 1666e234b..a89825c19 100644
--- a/apps/render-farm/src/transcode.test.ts
+++ b/apps/render-farm/src/transcode.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { encodedSeconds, transcodeArgs } from "./transcode";
+import { canRemux, encodedSeconds, transcodeArgs } from "./transcode";
describe("transcodeArgs", () => {
test("NVENC keeps frames on the GPU and forces one-second IDR frames", () => {
@@ -38,3 +38,31 @@ describe("encodedSeconds", () => {
expect(encodedSeconds("out_time=00:00:01.000000")).toBeNull();
});
});
+
+describe("canRemux", () => {
+ const packets = (codec: string, keyframes: number[], end: number) =>
+ [
+ `codec_name=${codec}|pix_fmt=yuv420p`,
+ ...Array.from({ length: end * 10 + 1 }, (_, index) => {
+ const time = index / 10;
+ return `pts_time=${time.toFixed(6)}|flags=${keyframes.includes(time) ? "K__" : "___"}`;
+ }),
+ ].join("\n");
+
+ test("copies H.264 with keyframes at most four seconds apart", () => {
+ expect(canRemux(packets("h264", [0, 2, 4, 6, 8], 10))).toBe(true);
+ });
+
+ test("re-encodes WebM codecs and sparse keyframes", () => {
+ expect(canRemux(packets("vp8", [0, 1, 2], 3))).toBe(false);
+ expect(canRemux(packets("h264", [0], 10))).toBe(false);
+ expect(canRemux(packets("h264", [0, 2, 4], 10))).toBe(false);
+ });
+
+ test("rejects H.264 outside 4:2:0 and sources with no keyframes", () => {
+ expect(
+ canRemux(packets("h264", [0, 2], 3).replace("yuv420p", "yuv444p")),
+ ).toBe(false);
+ expect(canRemux(packets("h264", [], 3))).toBe(false);
+ });
+});
diff --git a/apps/render-farm/src/transcode.ts b/apps/render-farm/src/transcode.ts
index 4e63dc574..b293a6419 100644
--- a/apps/render-farm/src/transcode.ts
+++ b/apps/render-farm/src/transcode.ts
@@ -53,3 +53,73 @@ export function encodedSeconds(line: string) {
const match = line.match(/^out_time_(?:us|ms)=(\d+)$/);
return match ? Number(match[1]) / 1_000_000 : null;
}
+
+/** Longest keyframe gap a source may have and still be remuxed as-is. */
+export const MAX_REMUX_KEYFRAME_GAP_SECONDS = 4;
+
+/** ffprobe arguments listing the video codec and every packet's flags. */
+export function probeArgs(input: string) {
+ return [
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=codec_name,pix_fmt:packet=pts_time,flags",
+ "-of",
+ "compact=p=0:nk=0",
+ input,
+ ];
+}
+
+/**
+ * Whether a probed source can be copied into an indexed MP4 without
+ * re-encoding: H.264 4:2:0 (what browsers record as MP4) whose keyframes are
+ * close enough together for chunks to start near any point.
+ */
+export function canRemux(probe: string) {
+ const codec = probe.match(/codec_name=([^|\n]+)/)?.[1];
+ const pixelFormat = probe.match(/pix_fmt=([^|\n]+)/)?.[1];
+ if (codec !== "h264" || (pixelFormat && pixelFormat !== "yuv420p")) {
+ return false;
+ }
+ const keyframes: number[] = [];
+ let last = 0;
+ for (const match of probe.matchAll(/pts_time=([0-9.]+)\|flags=([A-Z_]+)/g)) {
+ const time = Number(match[1]);
+ last = Math.max(last, time);
+ if (match[2]?.includes("K")) keyframes.push(time);
+ }
+ if (keyframes.length === 0) return false;
+ keyframes.sort((a, b) => a - b);
+ let previous = 0;
+ for (const time of [...keyframes, last]) {
+ if (time - previous > MAX_REMUX_KEYFRAME_GAP_SECONDS) return false;
+ previous = time;
+ }
+ return true;
+}
+
+/** ffmpeg arguments that copy the video track into a faststart MP4. */
+export function remuxArgs(input: string, output: string) {
+ return [
+ "-hide_banner",
+ "-nostdin",
+ "-y",
+ "-loglevel",
+ "error",
+ "-progress",
+ "pipe:1",
+ "-nostats",
+ "-i",
+ input,
+ "-map",
+ "0:v:0",
+ "-an",
+ "-c:v",
+ "copy",
+ "-movflags",
+ "+faststart",
+ output,
+ ];
+}
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
index a5f669f8c..e0c7d2f88 100644
--- a/apps/render-farm/src/worker.ts
+++ b/apps/render-farm/src/worker.ts
@@ -19,7 +19,13 @@ import {
type WorkItem,
} from "./protocol";
import { mediaS3ConfigFromEnv, S3 } from "./s3";
-import { encodedSeconds, transcodeArgs } from "./transcode";
+import {
+ canRemux,
+ encodedSeconds,
+ probeArgs,
+ remuxArgs,
+ transcodeArgs,
+} from "./transcode";
const s3 = new S3(mediaS3ConfigFromEnv());
const COORDINATOR = (
@@ -672,15 +678,27 @@ async function runTranscode(task: TranscodeTask, slot: number) {
progress.set(slot, entry);
try {
const output = join(dir, "output.mp4");
+ const input = await s3.presignFresh("GET", task.source, 6 * 3600);
+ const probe = Bun.spawn(["ffprobe", ...probeArgs(input)], {
+ stdout: "pipe",
+ stderr: "ignore",
+ });
+ const probed = await new Response(probe.stdout).text();
+ // H.264 with frequent keyframes (Chrome, Edge and Safari recordings)
+ // only needs its container rewritten; anything else is re-encoded.
+ const remux = (await probe.exited) === 0 && canRemux(probed);
+ console.log(`${task.taskId}: ${remux ? "remuxing" : "transcoding"}`);
const ffmpeg = Bun.spawn(
[
"ffmpeg",
- ...transcodeArgs(
- await s3.presignFresh("GET", task.source, 6 * 3600),
- output,
- task.keyframeSeconds,
- TRANSCODE_ENCODER,
- ),
+ ...(remux
+ ? remuxArgs(input, output)
+ : transcodeArgs(
+ input,
+ output,
+ task.keyframeSeconds,
+ TRANSCODE_ENCODER,
+ )),
],
{ stdout: "pipe", stderr: "pipe" },
);