Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(media-server): transcode with capcodec when the encoder flag is set
Richie McIlroycdb12fd88583
diff --git a/apps/media-server/capcodec-benchmarks.md b/apps/media-server/capcodec-benchmarks.mdnew file mode 100644index 000000000..5d3ec74bc--- /dev/null+++ b/apps/media-server/capcodec-benchmarks.md@@ -0,0 +1,194 @@+# capcodec vs x264 veryfast++Measurements from the capcodec bench harness for the binary `CAP_MEDIA_VIDEO_ENCODER=capcodec` runs. This repository's CI does not regenerate them. A speed ratio above 1 means capcodec is faster. A BD-rate below 0 means capcodec uses fewer bits at the same quality.++The 12-clip speed table is main `00fecf7` (read-ahead, CABAC, intra minIndex), retimed with other processes stopped. `--bframes 0` matches that encoder. Concurrent B-frames are the default after that measurement. Screen clips stay almost entirely P frames, so those speed rows still describe the default. full_motion was retimed with concurrent B-frames: 4-thread wall is 1.35-1.40x medium and 1.44-1.50x live (the same sessions measured the previous encoder at 1.09-1.10x and 1.19-1.21x). The other 11 clips were not retimed. full_motion quality below is the pre-concurrent-B bitstream.++`rd-next` (`d0cce5e`) and SSIM round 3 (`b72e995`) are not in the binary this flag runs. The media server's `ultrafast` preset maps to capcodec `fast`. Job CRF and preset apply unless `CAPCODEC_CRF` or `CAPCODEC_PRESET` is set.++| Metric | Result |+|---|---|+| Keyframe-only CPU | 1.06-1.76x at 1 and 4 threads; busy_ui uses 12% more bits in all-intra |+| Peak RSS, 4 threads | 34-308 MiB vs 141-1304 MiB on the speed rerun |+| Output delay | live 2 frames (5 with B-frames), medium 10 (steady 13), zerolatency 0; x264 17-19 frames at 4 threads |+| Startup | 0.9-1.2 ms vs 1.3-1.5 ms on a 64x64 frame |+| Decode CPU of the output | 0.58-1.54 s vs 1.59-2.40 s on the measured clips |+| Binary | 561,312 bytes at `00fecf7`; 609,152 bytes with concurrent B-frames. Minimal x264 build is 1.29 MB |+| Build CPU | about 12 s vs 36 s (minimal x264) |+| Bitrate error at Cap targets | two-pass 4.9% vs 5.5%; one-pass 7.7% vs 5.5% (one-pass rate control is not in this binary) |++Quality measured 2026-10-09 on main `fff504d`. Speed remeasured the same day on main `00fecf7` (read-ahead, pin7 intra minIndex, CABAC table). Those commits match the `fff504d` bitstreams, so the quality tables still describe this encoder. Pending quality branch `rd-next` `d0cce5e`. All 12 corpus clips.++How to reproduce (in the capcodec tree; these scripts are not in this repository):++- Quality: `CAPCODEC_BIN_UNCHECKED=<binary> python3 bench/bench.py standard --quality-only --encoders capcodec-medium,capcodec-live,capcodec-live-zerolatency,x264-veryfast,x264-veryfast-zerolatency --out <dir>` (1080p, 10 s per clip; code_4k is scaled to 1080p here). capcodec's CRF ladder runs 20-44 so its VMAF range covers x264's CRF 18-33; the overlap column shows how much of the two curves BD-rate compares (it was 15-24% on screen clips with the old 20-36 ladder).+- Speed: `bench/lane.sh start`, then `bench/lane.sh run "python3 bench/speedcmp.py --binary <binary> --clips all --modes medium,live,zerolatency --retime bench/out/speedcmp-fff504d-v2 --out <dir>"`. The rerun reuses the CRF that matched x264 CRF 23 (bitstreams are unchanged, so the match stands). 5 shuffled, interleaved rounds at 1 and 4 threads; every other process is stopped for each timed run (about 690 processes stopped, frozen median). code_4k runs at native 4K for 5 s. Output: `bench/out/speedcmp-00fecf7`.+- Tables: `python3 bench/scoreboard.py --quality LABEL=<dir> --speed LABEL=<dir> --out SCOREBOARD.md`.++### main fff504d: capcodec-medium vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)++| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |+|---|---|---|---|---|+| busy_ui | +5.4% lose | +5.1% lose | +14.8% lose | 52% |+| busy_ui_60fps | +2.6% lose | +2.0% lose | +16.8% lose | 74% |+| code_4k | -3.3% win | +1.0% lose | +9.2% lose | 72% |+| code_editor | -0.5% win | +4.9% lose | +7.3% lose | 76% |+| dark_mode | -17.2% win | -16.9% win | -11.9% win | 75% |+| dashboard | +7.9% lose | +12.3% lose | +25.9% lose | 59% |+| full_motion | -12.2% win | -10.0% win | +4.8% lose | 44% |+| idle | -8.8% win | -6.3% win | -3.4% win | 73% |+| slides | -18.0% win | +0.5% lose | -3.6% win | 66% |+| slow_typing | -0.8% win | +4.5% lose | +8.6% lose | 80% |+| text_scroll | -15.5% win | -14.8% win | -14.9% win | 88% |+| webcam_overlay | -20.0% win | -4.3% win | -4.0% win | 69% |++19 wins, 17 losses across 12 clips x 3 metrics.++### main fff504d: capcodec-live vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)++| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |+|---|---|---|---|---|+| busy_ui | +5.7% lose | +5.7% lose | +15.6% lose | 51% |+| busy_ui_60fps | +3.5% lose | +2.9% lose | +18.1% lose | 73% |+| code_4k | +0.2% lose | +5.3% lose | +13.4% lose | 72% |+| code_editor | +2.8% lose | +8.6% lose | +11.2% lose | 76% |+| dark_mode | -16.6% win | -16.2% win | -10.9% win | 75% |+| dashboard | +10.8% lose | +15.7% lose | +29.3% lose | 61% |+| full_motion | -7.8% win | -1.9% win | +12.0% lose | 43% |+| idle | -8.4% win | -6.2% win | -3.0% win | 72% |+| slides | -20.0% win | -1.5% win | -6.4% win | 65% |+| slow_typing | +1.1% lose | +4.8% lose | +9.1% lose | 78% |+| text_scroll | -15.1% win | -14.7% win | -14.8% win | 88% |+| webcam_overlay | -18.7% win | -3.8% win | -1.7% win | 67% |++17 wins, 19 losses across 12 clips x 3 metrics.++### main fff504d: capcodec-live-zerolatency vs x264-veryfast-zerolatency (BD-rate, negative = capcodec needs fewer bits)++| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |+|---|---|---|---|---|+| busy_ui | +1.6% lose | +2.3% lose | +6.7% lose | 23% |+| busy_ui_60fps | +2.0% lose | +1.9% lose | +9.2% lose | 30% |+| code_4k | -1.2% win | +2.4% lose | +7.9% lose | 36% |+| code_editor | -0.5% win | +8.0% lose | +5.8% lose | 36% |+| dark_mode | -22.3% win | -21.6% win | -21.3% win | 35% |+| dashboard | +0.2% lose | +2.3% lose | +7.4% lose | 27% |+| full_motion | -3.1% win | -1.0% win | +15.1% lose | 98% |+| idle | -17.2% win | -17.8% win | -15.6% win | 28% |+| slides | -30.8% win | -22.7% win | -20.8% win | 40% |+| slow_typing | -0.8% win | +3.8% lose | +4.8% lose | 37% |+| text_scroll | -16.3% win | -17.6% win | -20.7% win | 33% |+| webcam_overlay | -74.8% win | -64.5% win | -54.8% win | 42% |++20 wins, 16 losses across 12 clips x 3 metrics.++### rd-next d0cce5e: capcodec-medium vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)++| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |+|---|---|---|---|---|+| busy_ui | -17.0% win | -2.4% win | +6.5% lose | 65% |+| busy_ui_60fps | -18.8% win | -3.8% win | +6.4% lose | 42% |+| code_4k | -23.0% win | -1.4% win | +5.0% lose | 57% |+| code_editor | -22.7% win | -3.7% win | +2.5% lose | 57% |+| dark_mode | -35.0% win | -19.9% win | -13.5% win | 58% |+| dashboard | -12.3% win | +3.2% lose | +12.8% lose | 77% |+| full_motion | -21.6% win | -8.9% win | +1.5% lose | 52% |+| idle | -24.0% win | -11.8% win | -2.9% win | 66% |+| slides | -33.6% win | -13.3% win | -10.2% win | 81% |+| slow_typing | -22.4% win | -4.1% win | +2.2% lose | 43% |+| text_scroll | -31.1% win | -19.6% win | -14.3% win | 54% |+| webcam_overlay | -34.1% win | -14.0% win | +3.4% lose | 87% |++27 wins, 9 losses across 12 clips x 3 metrics.++### rd-next d0cce5e: capcodec-live vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)++| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |+|---|---|---|---|---|+| busy_ui | -17.3% win | -2.3% win | +6.5% lose | 64% |+| busy_ui_60fps | -18.9% win | -3.7% win | +6.5% lose | 42% |+| code_4k | -22.7% win | -1.3% win | +5.2% lose | 58% |+| code_editor | -22.1% win | -3.7% win | +2.7% lose | 57% |+| dark_mode | -34.4% win | -19.6% win | -13.0% win | 59% |+| dashboard | -12.4% win | +3.8% lose | +14.0% lose | 73% |+| full_motion | -18.0% win | -2.6% win | +6.8% lose | 51% |+| idle | -23.8% win | -11.7% win | -2.7% win | 67% |+| slides | -35.3% win | -15.6% win | -12.6% win | 83% |+| slow_typing | -21.3% win | -4.1% win | +2.2% lose | 43% |+| text_scroll | -31.0% win | -19.6% win | -14.3% win | 54% |+| webcam_overlay | -34.1% win | -14.9% win | +1.2% lose | 88% |++27 wins, 9 losses across 12 clips x 3 metrics.++### rd-next d0cce5e: capcodec-live-zerolatency vs x264-veryfast-zerolatency (BD-rate, negative = capcodec needs fewer bits)++| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |+|---|---|---|---|---|+| busy_ui | -21.3% win | -6.6% win | +1.0% lose | 48% |+| busy_ui_60fps | -18.9% win | -6.2% win | +3.0% lose | 64% |+| code_4k | -20.7% win | -0.8% win | +5.4% lose | 62% |+| code_editor | -22.6% win | -3.7% win | +2.8% lose | 62% |+| dark_mode | -37.4% win | -26.1% win | -22.1% win | 58% |+| dashboard | -21.6% win | -7.8% win | -0.1% win | 45% |+| full_motion | -15.6% win | -0.3% win | +7.4% lose | 62% |+| idle | -33.5% win | -25.2% win | -13.5% win | 46% |+| slides | -46.6% win | -35.0% win | -23.4% win | 58% |+| slow_typing | -21.3% win | -6.2% win | +0.5% lose | 70% |+| text_scroll | -32.6% win | -24.5% win | -20.8% win | 53% |+| webcam_overlay | -80.6% win | -64.2% win | -43.9% win | 58% |++30 wins, 6 losses across 12 clips x 3 metrics.++### main 00fecf7: speed at matched VMAF (x264 / capcodec, interleaved medians, other work paused)++| clip | mode | VMAF | CPU 1t | wall 1t | CPU 4t | wall 4t | peak RSS 4t capcodec / x264 MiB |+|---|---|---|---|---|---|---|---|+| busy_ui | live | 94.5 | 7.42x win | 6.55x win | 8.25x win | 4.40x win | 46 / 377 |+| busy_ui_60fps | live | 93.2 | 8.20x win | 7.23x win | 9.21x win | 4.17x win | 46 / 374 |+| code_4k | live | 95.2 | 8.92x win | 7.96x win | 9.73x win | 4.58x win | 176 / 1304 |+| code_editor | live | 94.4 | 7.36x win | 6.52x win | 7.97x win | 4.49x win | 49 / 382 |+| dark_mode | live | 93.4 | 7.33x win | 6.54x win | 6.80x win | 4.59x win | 48 / 393 |+| dashboard | live | 94.4 | 3.86x win | 3.51x win | 4.25x win | 2.10x win | 51 / 384 |+| full_motion | live | 88.2 | 1.61x win | 1.54x win | 1.37x win | 1.21x win | 80 / 379 |+| idle | live | 95.3 | 9.18x win | 8.11x win | 10.19x win | 4.55x win | 44 / 379 |+| slides | live | 95.0 | 5.15x win | 4.64x win | 4.61x win | 3.24x win | 74 / 391 |+| slow_typing | live | 95.2 | 7.87x win | 6.88x win | 8.82x win | 4.15x win | 45 / 387 |+| text_scroll | live | 95.0 | 4.88x win | 4.40x win | 3.84x win | 3.10x win | 53 / 384 |+| webcam_overlay | live | 95.4 | 4.64x win | 4.21x win | 4.55x win | 3.46x win | 74 / 391 |+| busy_ui | medium | 94.5 | 7.30x win | 6.31x win | 7.77x win | 4.11x win | 77 / 371 |+| busy_ui_60fps | medium | 93.2 | 8.08x win | 7.13x win | 8.77x win | 4.09x win | 77 / 372 |+| code_4k | medium | 95.2 | 7.96x win | 7.13x win | 8.78x win | 3.89x win | 308 / 1279 |+| code_editor | medium | 94.4 | 7.01x win | 6.17x win | 7.88x win | 4.13x win | 83 / 379 |+| dark_mode | medium | 93.4 | 7.25x win | 6.48x win | 6.37x win | 4.24x win | 79 / 386 |+| dashboard | medium | 94.4 | 3.59x win | 3.21x win | 3.82x win | 1.75x win | 85 / 382 |+| full_motion | medium | 88.2 | 1.39x win | 1.33x win | 1.22x win | 1.06x win | 103 / 375 |+| idle | medium | 95.3 | 9.37x win | 8.30x win | 10.28x win | 4.54x win | 73 / 385 |+| slides | medium | 95.0 | 4.86x win | 4.40x win | 4.34x win | 2.90x win | 98 / 384 |+| slow_typing | medium | 95.2 | 7.94x win | 6.94x win | 8.26x win | 3.97x win | 76 / 384 |+| text_scroll | medium | 95.0 | 4.39x win | 3.88x win | 3.64x win | 2.89x win | 88 / 385 |+| webcam_overlay | medium | 95.4 | 4.32x win | 3.92x win | 4.20x win | 3.01x win | 99 / 386 |+| busy_ui | zerolatency | 96.0 | 6.79x win | 5.96x win | 6.92x win | 3.85x win | 34 / 144 |+| busy_ui_60fps | zerolatency | 95.5 | 7.75x win | 6.82x win | 7.96x win | 3.95x win | 34 / 150 |+| code_4k | zerolatency | 96.0 | 7.51x win | 6.58x win | 7.06x win | 3.92x win | 113 / 458 |+| code_editor | zerolatency | 95.8 | 6.32x win | 5.51x win | 6.38x win | 3.61x win | 34 / 146 |+| dark_mode | zerolatency | 95.5 | 6.51x win | 5.67x win | 5.00x win | 3.76x win | 34 / 151 |+| dashboard | zerolatency | 96.1 | 3.44x win | 3.08x win | 3.64x win | 2.17x win | 37 / 150 |+| full_motion | zerolatency | 88.1 | 1.65x win | 1.58x win | 1.21x win | 1.49x win | 46 / 142 |+| idle | zerolatency | 96.4 | 9.40x win | 8.32x win | 8.89x win | 4.40x win | 34 / 141 |+| slides | zerolatency | 96.2 | 4.84x win | 4.34x win | 3.86x win | 2.95x win | 39 / 149 |+| slow_typing | zerolatency | 96.4 | 7.15x win | 6.15x win | 7.16x win | 3.53x win | 34 / 148 |+| text_scroll | zerolatency | 96.3 | 3.90x win | 3.45x win | 3.12x win | 2.78x win | 38 / 149 |+| webcam_overlay | zerolatency | 96.2 | 5.17x win | 4.73x win | 4.60x win | 4.27x win | 39 / 142 |+- live 1 thread cpu: geometric mean 5.83x, min 1.61x (12/12 clips faster)+- live 1 thread wall: geometric mean 5.23x, min 1.54x (12/12 clips faster)+- live 4 threads cpu: geometric mean 5.87x, min 1.37x (12/12 clips faster)+- live 4 threads wall: geometric mean 3.46x, min 1.21x (12/12 clips faster)+- medium 1 thread cpu: geometric mean 5.53x, min 1.39x (12/12 clips faster)+- medium 1 thread wall: geometric mean 4.94x, min 1.33x (12/12 clips faster)+- medium 4 threads cpu: geometric mean 5.51x, min 1.22x (12/12 clips faster)+- medium 4 threads wall: geometric mean 3.15x, min 1.06x (12/12 clips faster)+- zerolatency 1 thread cpu: geometric mean 5.39x, min 1.65x (12/12 clips faster)+- zerolatency 1 thread wall: geometric mean 4.80x, min 1.58x (12/12 clips faster)+- zerolatency 4 threads cpu: geometric mean 4.90x, min 1.21x (12/12 clips faster)+- zerolatency 4 threads wall: geometric mean 3.26x, min 1.49x (12/12 clips faster)+diff --git a/apps/media-server/src/__tests__/lib/capcodec-encoder.test.ts b/apps/media-server/src/__tests__/lib/capcodec-encoder.test.tsnew file mode 100644index 000000000..5711e487e--- /dev/null+++ b/apps/media-server/src/__tests__/lib/capcodec-encoder.test.ts@@ -0,0 +1,166 @@+import { describe, expect, test } from "bun:test";+import {+ buildCapcodecDecodeArgs,+ buildCapcodecEncodeArgs,+ capcodecOptionsForJob,+ capcodecOptionsFromEnv,+ fitEvenSize,+ frameRateFraction,+ remainingTimeoutMs,+} from "../../lib/capcodec-encoder";++const enabled = { CAP_MEDIA_VIDEO_ENCODER: "capcodec" };++describe("capcodec encoder integration", () => {+ test("is disabled unless CAP_MEDIA_VIDEO_ENCODER is capcodec", () => {+ expect(capcodecOptionsFromEnv({})).toBeNull();+ expect(+ capcodecOptionsFromEnv({ CAP_MEDIA_VIDEO_ENCODER: "x264" }),+ ).toBeNull();+ expect(capcodecOptionsForJob({ crf: 18, preset: "slow" }, {})).toBeNull();+ });++ test("uses the job CRF and preset unless the environment sets them", () => {+ expect(+ capcodecOptionsForJob({ crf: 18, preset: "ultrafast" }, enabled),+ ).toEqual({+ binary: "capcodec",+ crf: 18,+ preset: "fast",+ keyint: 250,+ noise: 3,+ });+ expect(+ capcodecOptionsForJob(+ { crf: 18, preset: "slow" },+ {+ ...enabled,+ CAPCODEC_BIN: "/opt/capcodec",+ CAPCODEC_CRF: "26.5",+ CAPCODEC_PRESET: "live",+ CAPCODEC_KEYINT: "120",+ CAPCODEC_NOISE: "0",+ },+ ),+ ).toEqual({+ binary: "/opt/capcodec",+ crf: 26.5,+ preset: "live",+ keyint: 120,+ noise: 0,+ });+ });++ test("ignores blank or out-of-range encoder settings", () => {+ expect(+ capcodecOptionsForJob(+ { crf: 20, preset: "medium" },+ {+ ...enabled,+ CAPCODEC_BIN: " ",+ CAPCODEC_CRF: "80",+ CAPCODEC_PRESET: "",+ CAPCODEC_KEYINT: "0",+ CAPCODEC_NOISE: "-1",+ },+ ),+ ).toEqual({+ binary: "capcodec",+ crf: 20,+ preset: "medium",+ keyint: 250,+ noise: 3,+ });+ expect(+ capcodecOptionsFromEnv({+ ...enabled,+ CAPCODEC_CRF: "nope",+ CAPCODEC_PRESET: "placebo",+ }),+ ).toMatchObject({ crf: 23, preset: "slow" });+ });++ test("fits the media server's 1080p box like the libx264 scale filter", () => {+ expect(fitEvenSize(3840, 2160, 1920, 1080)).toEqual({+ width: 1920,+ height: 1080,+ });+ expect(fitEvenSize(1280, 720, 1920, 1080)).toEqual({+ width: 1280,+ height: 720,+ });+ expect(fitEvenSize(2560, 1600, 1920, 1080)).toEqual({+ width: 1728,+ height: 1080,+ });+ expect(fitEvenSize(1001, 563, 1920, 1080)).toEqual({+ width: 1000,+ height: 562,+ });+ expect(() => fitEvenSize(0, 1080, 1920, 1080)).toThrow(+ "Video dimensions must be positive",+ );+ });++ test("expresses frame rates as exact fractions", () => {+ expect(frameRateFraction(30)).toBe("30/1");+ expect(frameRateFraction(23.976)).toBe("24000/1001");+ expect(frameRateFraction(29.97)).toBe("30000/1001");+ expect(frameRateFraction(59.94)).toBe("60000/1001");+ expect(frameRateFraction(12.5)).toBe("25/2");+ expect(frameRateFraction(Number.NaN)).toBe("30/1");+ expect(frameRateFraction(0.0001)).toBe("30/1");+ });++ test("leaves the mux the time the encode did not use", () => {+ expect(remainingTimeoutMs(10_000, 4_000)).toBe(6_000);+ expect(remainingTimeoutMs(10_000, 10_000)).toBe(1);+ expect(remainingTimeoutMs(10_000, 0)).toBe(10_000);+ });++ test("pipes raw frames from ffmpeg into capcodec", () => {+ const decode = buildCapcodecDecodeArgs(+ { inputPath: "in.webm", extraInputArgs: [] },+ 1920,+ 1080,+ "30/1",+ );+ expect(decode.slice(-4)).toEqual(["yuv420p", "-progress", "pipe:2", "-"]);+ expect(decode).toContain("rawvideo");+ const encode = buildCapcodecEncodeArgs(+ {+ binary: "capcodec",+ crf: 23.5,+ preset: "medium",+ keyint: 250,+ noise: 3,+ },+ "out.mp4",+ 1920,+ 1080,+ "30/1",+ );+ expect(encode).toEqual([+ "capcodec",+ "encode",+ "--input",+ "-",+ "--width",+ "1920",+ "--height",+ "1080",+ "--fps",+ "30/1",+ "--crf",+ "23.5",+ "--preset",+ "medium",+ "--keyint",+ "250",+ "--noise",+ "3",+ "--output",+ "out.mp4",+ ]);+ });+});diff --git a/apps/media-server/src/lib/capcodec-encoder.ts b/apps/media-server/src/lib/capcodec-encoder.tsnew file mode 100644index 000000000..6fc385f04--- /dev/null+++ b/apps/media-server/src/lib/capcodec-encoder.ts@@ -0,0 +1,354 @@+import { file, spawn } from "bun";+import { registerSubprocess, terminateProcess } from "./subprocess";++const DEFAULT_CRF = 23;+const DEFAULT_KEYINT = 250;+const DEFAULT_NOISE = 3;+const CAPCODEC_PRESETS = new Set(["live", "fast", "medium", "slow"]);++export interface CapcodecOptions {+ binary: string;+ crf: number;+ preset: string;+ keyint: number;+ noise: number;+}++export interface CapcodecEncodeJob {+ inputPath: string;+ outputPath: string;+ width: number;+ height: number;+ fps: number;+ maxWidth: number;+ maxHeight: number;+ extraInputArgs: string[];+ options: CapcodecOptions;+ totalDurationUs: number;+ onProgress?: (progress: number, message: string) => void;+ abortSignal?: AbortSignal;+}++export function mapCapcodecPreset(preset: string): string {+ const normalized = preset.trim().toLowerCase();+ if (+ normalized === "ultrafast" ||+ normalized === "superfast" ||+ normalized === "veryfast" ||+ normalized === "faster"+ ) {+ return "fast";+ }+ if (+ normalized === "slower" ||+ normalized === "veryslow" ||+ normalized === "placebo"+ ) {+ return "slow";+ }+ if (CAPCODEC_PRESETS.has(normalized)) return normalized;+ return "medium";+}++function parseCrf(raw: string | undefined): number | undefined {+ if (raw === undefined || raw.trim() === "") return undefined;+ const value = Number(raw);+ if (!Number.isFinite(value) || value < 0 || value > 51) return undefined;+ return value;+}++function parseBoundedInt(+ raw: string | undefined,+ min: number,+ max: number,+): number | undefined {+ if (raw === undefined || raw.trim() === "") return undefined;+ const value = Number(raw);+ if (!Number.isInteger(value) || value < min || value > max) return undefined;+ return value;+}++function clampCrf(crf: number): number {+ if (!Number.isFinite(crf)) return DEFAULT_CRF;+ return Math.min(51, Math.max(0, crf));+}++export function capcodecOptionsFromEnv(+ env: Record<string, string | undefined> = process.env,+): CapcodecOptions | null {+ if (env.CAP_MEDIA_VIDEO_ENCODER !== "capcodec") return null;+ return {+ binary: env.CAPCODEC_BIN?.trim() || "capcodec",+ crf: parseCrf(env.CAPCODEC_CRF) ?? DEFAULT_CRF,+ preset: mapCapcodecPreset(env.CAPCODEC_PRESET ?? "medium"),+ keyint: parseBoundedInt(env.CAPCODEC_KEYINT, 1, 100_000) ?? DEFAULT_KEYINT,+ noise: parseBoundedInt(env.CAPCODEC_NOISE, 0, 255) ?? DEFAULT_NOISE,+ };+}++export function capcodecOptionsForJob(+ job: { crf: number; preset: string },+ env: Record<string, string | undefined> = process.env,+): CapcodecOptions | null {+ const base = capcodecOptionsFromEnv(env);+ if (!base) return null;+ const presetOverride = env.CAPCODEC_PRESET?.trim();+ return {+ ...base,+ crf: parseCrf(env.CAPCODEC_CRF) ?? clampCrf(job.crf),+ preset: presetOverride+ ? mapCapcodecPreset(presetOverride)+ : mapCapcodecPreset(job.preset),+ };+}++export function remainingTimeoutMs(+ timeoutMs: number,+ elapsedMs: number,+): number {+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return 1;+ if (!Number.isFinite(elapsedMs) || elapsedMs <= 0) return timeoutMs;+ return Math.max(1, timeoutMs - elapsedMs);+}++export function fitEvenSize(+ width: number,+ height: number,+ maxWidth: number,+ maxHeight: number,+): { width: number; height: number } {+ if (!(width > 0) || !(height > 0) || !(maxWidth > 0) || !(maxHeight > 0)) {+ throw new Error("Video dimensions must be positive");+ }+ const boxWidth = Math.min(maxWidth, width);+ const boxHeight = Math.min(maxHeight, height);+ const scale = Math.min(boxWidth / width, boxHeight / height);+ const scaledWidth = Math.round(width * scale);+ const scaledHeight = Math.round(height * scale);+ return {+ width: Math.max(2, Math.trunc(scaledWidth / 2) * 2),+ height: Math.max(2, Math.trunc(scaledHeight / 2) * 2),+ };+}++export function frameRateFraction(fps: number): string {+ if (!Number.isFinite(fps) || fps <= 0) return "30/1";+ const ntsc = [24, 30, 60].find(+ (base) => Math.abs(fps - (base * 1000) / 1001) < 0.01,+ );+ if (ntsc !== undefined) return `${ntsc * 1000}/1001`;+ const rounded = Math.round(fps * 1000);+ if (!Number.isFinite(rounded) || rounded <= 0) return "30/1";+ const divisor = gcd(rounded, 1000);+ return `${rounded / divisor}/${1000 / divisor}`;+}++function gcd(a: number, b: number): number {+ let x = Math.abs(a);+ let y = Math.abs(b);+ while (y !== 0) {+ const t = y;+ y = x % y;+ x = t;+ }+ return x;+}++function formatCrf(crf: number): string {+ if (Number.isInteger(crf)) return String(crf);+ return String(Math.round(crf * 1000) / 1000);+}++export function buildCapcodecDecodeArgs(+ job: Pick<CapcodecEncodeJob, "inputPath" | "extraInputArgs">,+ width: number,+ height: number,+ fps: string,+): string[] {+ return [+ "ffmpeg",+ "-hide_banner",+ "-nostdin",+ "-threads",+ "2",+ ...job.extraInputArgs,+ "-i",+ job.inputPath,+ "-map",+ "0:v:0",+ "-vf",+ `scale=${width}:${height}:flags=bicubic,format=yuv420p`,+ "-fps_mode",+ "cfr",+ "-r",+ fps,+ "-f",+ "rawvideo",+ "-pix_fmt",+ "yuv420p",+ "-progress",+ "pipe:2",+ "-",+ ];+}++export function buildCapcodecEncodeArgs(+ options: CapcodecOptions,+ outputPath: string,+ width: number,+ height: number,+ fps: string,+): string[] {+ return [+ options.binary,+ "encode",+ "--input",+ "-",+ "--width",+ String(width),+ "--height",+ String(height),+ "--fps",+ fps,+ "--crf",+ formatCrf(options.crf),+ "--preset",+ options.preset,+ "--keyint",+ String(options.keyint),+ "--noise",+ String(options.noise),+ "--output",+ outputPath,+ ];+}++function parseOutTimeUs(line: string): number | null {+ const match = line.match(/^out_time_us=(\d+)/);+ if (!match?.[1]) return null;+ return Number.parseInt(match[1], 10);+}++function pushStderrLine(lines: string[], line: string): void {+ lines.push(line);+ if (lines.length > 50) lines.shift();+}++async function collectStderr(+ stream: ReadableStream<Uint8Array>,+ lines: string[],+ onLine?: (line: string) => void,+): Promise<void> {+ const reader = stream.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ const parts = buffer.split("\n");+ buffer = parts.pop() ?? "";+ for (const line of parts) {+ pushStderrLine(lines, line);+ onLine?.(line);+ }+ }+ buffer += decoder.decode();+ if (buffer.length > 0) {+ pushStderrLine(lines, buffer);+ onLine?.(buffer);+ }+ } finally {+ reader.releaseLock();+ }+}++function cancelled(): Error {+ return new Error("Video processing was cancelled");+}++export async function encodeVideoWithCapcodec(+ job: CapcodecEncodeJob,+): Promise<void> {+ if (job.abortSignal?.aborted) throw cancelled();+ const size = fitEvenSize(job.width, job.height, job.maxWidth, job.maxHeight);+ const fps = frameRateFraction(job.fps);+ const decoder = registerSubprocess(+ spawn({+ cmd: buildCapcodecDecodeArgs(job, size.width, size.height, fps),+ stdout: "pipe",+ stderr: "pipe",+ }),+ );+ const encoder = registerSubprocess(+ spawn({+ cmd: buildCapcodecEncodeArgs(+ job.options,+ job.outputPath,+ size.width,+ size.height,+ fps,+ ),+ stdin: decoder.stdout as ReadableStream<Uint8Array>,+ stdout: "ignore",+ stderr: "pipe",+ }),+ );+ const abort = () => {+ void terminateProcess(decoder);+ void terminateProcess(encoder);+ };+ job.abortSignal?.addEventListener("abort", abort, { once: true });+ const decoderLines: string[] = [];+ const encoderLines: string[] = [];+ try {+ await Promise.all([+ collectStderr(+ decoder.stderr as ReadableStream<Uint8Array>,+ decoderLines,+ (line) => {+ const outTime = parseOutTimeUs(line);+ if (outTime !== null && job.onProgress && job.totalDurationUs > 0) {+ const progress = Math.min(+ 100,+ (outTime / job.totalDurationUs) * 100,+ );+ job.onProgress(progress, `Encoding: ${Math.round(progress)}%`);+ }+ },+ ),+ collectStderr(encoder.stderr as ReadableStream<Uint8Array>, encoderLines),+ ]);+ if (job.abortSignal?.aborted) throw cancelled();+ const [decoderExit, encoderExit] = await Promise.all([+ decoder.exited,+ encoder.exited,+ ]);+ if (job.abortSignal?.aborted) throw cancelled();+ if (decoderExit !== 0 || encoderExit !== 0) {+ const parts: string[] = [];+ if (decoderExit !== 0) {+ parts.push(+ `FFmpeg decode for capcodec exited with code ${decoderExit}. Last stderr: ${decoderLines.slice(-10).join(" | ")}`,+ );+ }+ if (encoderExit !== 0) {+ parts.push(+ `capcodec exited with code ${encoderExit}. Last stderr: ${encoderLines.slice(-10).join(" | ")}`,+ );+ }+ throw new Error(parts.join(" "));+ }+ if ((await file(job.outputPath).size) === 0) {+ throw new Error("capcodec produced an empty output file");+ }+ } catch (error) {+ if (job.abortSignal?.aborted) throw cancelled();+ throw error;+ } finally {+ job.abortSignal?.removeEventListener("abort", abort);+ await terminateProcess(decoder);+ await terminateProcess(encoder);+ }+}diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.tsindex 8f87ca0ce..645d8af00 100644--- a/apps/media-server/src/lib/media-video.ts+++ b/apps/media-server/src/lib/media-video.ts@@ -3,6 +3,12 @@ import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";import { isAbsolute, join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { type BunFile, file, spawn } from "bun";+import {+ type CapcodecOptions,+ capcodecOptionsForJob,+ encodeVideoWithCapcodec,+ remainingTimeoutMs,+} from "./capcodec-encoder";import { uploadDriveResumable } from "./drive-resumable-upload";import type { VideoMetadata } from "./job-manager";import {@@ -1521,6 +1527,29 @@ export async function processVideo(metadata.duration,opts.timeoutMs,);+ const capcodec =+ videoTranscode && !normalizeH264Level ? capcodecOptionsForJob(opts) : null;+ if (capcodec) {+ try {+ await processVideoWithCapcodec(+ inputPath,+ metadata,+ opts,+ capcodec,+ outputTempFile.path,+ audioTranscode,+ extraInputArgs,+ extraOutputArgs,+ processTimeoutMs,+ onProgress,+ abortSignal,+ );+ return outputTempFile;+ } catch (err) {+ await outputTempFile.cleanup();+ throw err;+ }+ }const ffmpegArgs: string[] = ["ffmpeg","-threads",@@ -1662,6 +1691,91 @@ export async function processVideo(}}+async function processVideoWithCapcodec(+ inputPath: string,+ metadata: VideoMetadata,+ opts: Required<VideoProcessingOptions>,+ capcodec: CapcodecOptions,+ outputPath: string,+ audioTranscode: boolean,+ extraInputArgs: string[],+ extraOutputArgs: string[],+ processTimeoutMs: number,+ onProgress?: ProgressCallback,+ abortSignal?: AbortSignal,+): Promise<void> {+ const videoOnly = await createTempFile(".mp4");+ const controller = new AbortController();+ const forwardAbort = () => controller.abort();+ abortSignal?.addEventListener("abort", forwardAbort, { once: true });+ const startedAt = performance.now();+ try {+ await withTimeout(+ encodeVideoWithCapcodec({+ inputPath,+ outputPath: videoOnly.path,+ width: metadata.width,+ height: metadata.height,+ fps: metadata.fps,+ maxWidth: opts.maxWidth,+ maxHeight: opts.maxHeight,+ extraInputArgs,+ options: capcodec,+ totalDurationUs: metadata.duration * 1_000_000,+ onProgress,+ abortSignal: controller.signal,+ }),+ processTimeoutMs,+ async () => controller.abort(),+ );+ const muxArgs = [+ "ffmpeg",+ "-hide_banner",+ "-nostdin",+ "-i",+ videoOnly.path,+ ];+ if (metadata.audioCodec) {+ muxArgs.push(+ ...extraInputArgs,+ "-i",+ inputPath,+ "-map",+ "0:v:0",+ "-map",+ "1:a:0",+ "-c:v",+ "copy",+ );+ if (audioTranscode) {+ muxArgs.push("-c:a", "aac", "-b:a", opts.audioBitrate);+ } else {+ muxArgs.push("-c:a", "copy");+ }+ } else {+ muxArgs.push("-map", "0:v:0", "-c:v", "copy", "-an");+ }+ muxArgs.push(+ "-movflags",+ "+faststart",+ ...extraOutputArgs,+ "-y",+ outputPath,+ );+ await runFfmpegCommand(+ muxArgs,+ remainingTimeoutMs(processTimeoutMs, performance.now() - startedAt),+ abortSignal,+ );+ if ((await file(outputPath).size) === 0) {+ throw new Error("capcodec mux produced an empty output file");+ }+ } finally {+ abortSignal?.removeEventListener("abort", forwardAbort);+ await videoOnly.cleanup();+ }+}+function getThumbnailTimestamp(duration: number,requestedTimestamp: number,