Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(media-server): stop capcodec processes if startup or the timeout fails
Richie McIlroy641b440f9d22
diff --git a/apps/media-server/Dockerfile b/apps/media-server/Dockerfileindex 576334737..c09234479 100644--- a/apps/media-server/Dockerfile+++ b/apps/media-server/Dockerfile@@ -10,6 +10,7 @@ COPY apps/media-server/package.json apps/media-server/bun.lock ./RUN bun install --frozen-lockfile --productionCOPY apps/media-server/src ./src+COPY apps/media-server/capcodec.md ./capcodec.mdRUN bun test src/__tests__/lib/audio-quality-policy.test.ts src/__tests__/lib/audio-quality.integration.test.ts \&& bun test src/__tests__/lib/audio-quality-formats.integration.test.ts src/__tests__/lib/audio-quality-benchmark.test.ts \@@ -18,7 +19,7 @@ RUN bun test src/__tests__/lib/audio-quality-policy.test.ts src/__tests__/lib/au&& bun test src/__tests__/lib/media-size.test.ts src/__tests__/lib/media-probe.integration.test.ts \&& bun test src/__tests__/lib/media-audio.integration.test.ts \&& bun test src/__tests__/lib/recording-verification.integration.test.ts src/__tests__/lib/job-manager.test.ts \- && bun test src/__tests__/lib/media-transfer.test.ts \+ && bun test src/__tests__/lib/media-transfer.test.ts src/__tests__/lib/capcodec-encoder.test.ts \&& bun test src/__tests__/routes/recording-verification.test.ts \&& bun test src/__tests__/routes/video.test.ts \&& bun test src/__tests__/lib/media-routes-real-world.integration.test.ts \diff --git a/apps/media-server/Dockerfile.standalone b/apps/media-server/Dockerfile.standaloneindex 00de144fa..cd413a925 100644--- a/apps/media-server/Dockerfile.standalone+++ b/apps/media-server/Dockerfile.standalone@@ -10,6 +10,7 @@ COPY package.json bun.lock ./RUN bun install --frozen-lockfile --productionCOPY src ./src+COPY capcodec.md ./capcodec.mdENV PORT=3456EXPOSE 3456diff --git a/apps/media-server/capcodec.md b/apps/media-server/capcodec.mdnew file mode 100644index 000000000..ae9651c2d--- /dev/null+++ b/apps/media-server/capcodec.md@@ -0,0 +1,14 @@+# capcodec in the media server++The published media-server images install ffmpeg and do not include the capcodec executable. Leave `CAP_MEDIA_VIDEO_ENCODER` unset to keep libx264.++To encode with capcodec:++1. Build a capcodec binary for the image architecture (amd64 and arm64 are separate).+2. Mount it into the container, for example `/usr/local/bin/capcodec`.+3. Set `CAP_MEDIA_VIDEO_ENCODER=capcodec`.+4. Set `CAPCODEC_BIN` to that path. When it is on `PATH`, `capcodec` is enough.++Optional overrides: `CAPCODEC_CRF` (0–51), `CAPCODEC_PRESET` (`live`, `fast`, `medium`, `slow`), `CAPCODEC_KEYINT`, and `CAPCODEC_NOISE`. Without those, the job's CRF and preset are used. `ultrafast` maps to `fast`.++Benchmark tables against x264 veryfast are in `capcodec-benchmarks.md`.diff --git a/apps/media-server/src/__tests__/lib/capcodec-encoder.test.ts b/apps/media-server/src/__tests__/lib/capcodec-encoder.test.tsindex 5711e487e..890913d47 100644--- a/apps/media-server/src/__tests__/lib/capcodec-encoder.test.ts+++ b/apps/media-server/src/__tests__/lib/capcodec-encoder.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from "bun:test";import {+ assertCapcodecBinary,buildCapcodecDecodeArgs,buildCapcodecEncodeArgs,capcodecOptionsForJob,@@ -112,6 +113,13 @@ describe("capcodec encoder integration", () => {expect(frameRateFraction(0.0001)).toBe("30/1");});+ test("requires a mounted capcodec binary", async () => {+ await expect(assertCapcodecBinary("/bin/true")).resolves.toBeUndefined();+ await expect(assertCapcodecBinary("/no/such/capcodec")).rejects.toThrow(+ /does not include capcodec/,+ );+ });+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);diff --git a/apps/media-server/src/lib/capcodec-encoder.ts b/apps/media-server/src/lib/capcodec-encoder.tsindex 6fc385f04..70877e77b 100644--- a/apps/media-server/src/lib/capcodec-encoder.ts+++ b/apps/media-server/src/lib/capcodec-encoder.ts@@ -1,4 +1,6 @@-import { file, spawn } from "bun";+import { constants } from "node:fs";+import { access } from "node:fs/promises";+import { file, type Subprocess, spawn } from "bun";import { registerSubprocess, terminateProcess } from "./subprocess";const DEFAULT_CRF = 23;@@ -102,6 +104,19 @@ export function capcodecOptionsForJob(};}+export async function assertCapcodecBinary(binary: string): Promise<void> {+ const resolved = binary.includes("/") ? binary : Bun.which(binary);+ if (resolved) {+ try {+ await access(resolved, constants.X_OK);+ return;+ } catch {}+ }+ throw new Error(+ `capcodec binary "${binary}" is not executable. The media-server image does not include capcodec. Mount a binary and set CAPCODEC_BIN to its path before setting CAP_MEDIA_VIDEO_ENCODER=capcodec. See /app/capcodec.md.`,+ );+}+export function remainingTimeoutMs(timeoutMs: number,elapsedMs: number,@@ -272,53 +287,60 @@ export async function encodeVideoWithCapcodec(job: CapcodecEncodeJob,): Promise<void> {if (job.abortSignal?.aborted) throw cancelled();+ await assertCapcodecBinary(job.options.binary);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);+ let decoder: Subprocess | undefined;+ let encoder: Subprocess | undefined;+ let stopping: Promise<void> | undefined;+ const stop = () => {+ if (!stopping) {+ const procs = [decoder, encoder].filter(+ (proc): proc is Subprocess => proc !== undefined,+ );+ stopping = Promise.all(procs.map((proc) => terminateProcess(proc))).then(+ () => undefined,+ );+ }+ return stopping;+ };+ const onAbort = () => {+ void stop();};- job.abortSignal?.addEventListener("abort", abort, { once: true });- const decoderLines: string[] = [];- const encoderLines: string[] = [];try {+ decoder = registerSubprocess(+ spawn({+ cmd: buildCapcodecDecodeArgs(job, size.width, size.height, fps),+ stdout: "pipe",+ stderr: "pipe",+ }),+ );+ encoder = registerSubprocess(+ spawn({+ cmd: buildCapcodecEncodeArgs(+ job.options,+ job.outputPath,+ size.width,+ size.height,+ fps,+ ),+ stdin: decoder.stdout,+ stdout: "ignore",+ stderr: "pipe",+ }),+ );+ job.abortSignal?.addEventListener("abort", onAbort, { once: true });+ const decoderLines: string[] = [];+ const encoderLines: string[] = [];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),+ collectStderr(decoder.stderr, 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, encoderLines),]);if (job.abortSignal?.aborted) throw cancelled();const [decoderExit, encoderExit] = await Promise.all([@@ -347,8 +369,7 @@ export async function encodeVideoWithCapcodec(if (job.abortSignal?.aborted) throw cancelled();throw error;} finally {- job.abortSignal?.removeEventListener("abort", abort);- await terminateProcess(decoder);- await terminateProcess(encoder);+ job.abortSignal?.removeEventListener("abort", onAbort);+ await stop();}}diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.tsindex 645d8af00..1e03bae0d 100644--- a/apps/media-server/src/lib/media-video.ts+++ b/apps/media-server/src/lib/media-video.ts@@ -1709,25 +1709,25 @@ async function processVideoWithCapcodec(const forwardAbort = () => controller.abort();abortSignal?.addEventListener("abort", forwardAbort, { once: true });const startedAt = performance.now();+ const encodePromise = 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,+ });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(),- );+ await withTimeout(encodePromise, processTimeoutMs, async () => {+ controller.abort();+ await encodePromise.catch(() => undefined);+ });const muxArgs = ["ffmpeg","-hide_banner",