Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: enhance recording audio from the existing local media output
Richie McIlroy5791c91e7c6f
diff --git a/.github/workflows/docker-build-media-server.yml b/.github/workflows/docker-build-media-server.ymlindex 82378eb1e..72e42b64a 100644--- a/.github/workflows/docker-build-media-server.yml+++ b/.github/workflows/docker-build-media-server.yml@@ -109,7 +109,7 @@ jobs:src/__tests__/lib/audio-quality-formats.integration.test.ts \src/__tests__/lib/audio-quality-benchmark.test.tsdocker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \- src/__tests__/lib/audio-levels-route.integration.test.ts+ src/__tests__/lib/audio-levels.integration.test.tsdocker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \src/__tests__/lib/recording-verification.integration.test.ts \src/__tests__/lib/job-manager.test.tsdiff --git a/apps/media-server/Dockerfile b/apps/media-server/Dockerfileindex 7621ff844..c268146dd 100644--- a/apps/media-server/Dockerfile+++ b/apps/media-server/Dockerfile@@ -13,7 +13,7 @@ COPY apps/media-server/src ./srcRUN 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 \- && bun test src/__tests__/lib/audio-levels-route.integration.test.ts \+ && bun test src/__tests__/lib/audio-levels.integration.test.ts \&& bun test src/__tests__/lib/drive-resumable-upload.test.ts src/__tests__/lib/storage-upload.test.ts src/__tests__/lib/container-memory.test.ts \&& bun test src/__tests__/lib/media-size.test.ts src/__tests__/lib/media-probe.integration.test.ts \&& bun test src/__tests__/lib/recording-verification.integration.test.ts src/__tests__/lib/job-manager.test.ts \diff --git a/apps/media-server/src/__tests__/lib/audio-levels-route.integration.test.ts b/apps/media-server/src/__tests__/lib/audio-levels-route.integration.test.tsdeleted file mode 100644index 19d6b02f1..000000000--- a/apps/media-server/src/__tests__/lib/audio-levels-route.integration.test.ts+++ /dev/null@@ -1,182 +0,0 @@-import {- afterAll,- afterEach,- beforeAll,- describe,- expect,- test,-} from "bun:test";-import { mkdtemp, readFile, rm } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import audioLevels from "../../routes/audio-levels";--let directory: string;-let source: Uint8Array;-const originalFetch = globalThis.fetch;-const originalSecret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;-const request = {- sourceUrl: "https://storage.test/source.mp4",- sourceIdentity: '"source"',- sourceSize: 1,- outputUrl: "https://storage.test/output.mp4",- verificationUrl: "https://storage.test/output.mp4",-};--beforeAll(async () => {- directory = await mkdtemp(join(tmpdir(), "cap-audio-route-"));- const path = join(directory, "source.mp4");- const proc = Bun.spawn(- [- "ffmpeg",- "-v",- "error",- "-f",- "lavfi",- "-i",- "testsrc2=size=160x90:rate=15:duration=4",- "-f",- "lavfi",- "-i",- "aevalsrc=0.02*sin(2*PI*440*t):s=48000:d=4",- "-c:v",- "libx264",- "-preset",- "ultrafast",- "-c:a",- "aac",- "-threads",- "1",- path,- ],- { stdout: "ignore", stderr: "pipe" },- );- const [code, error] = await Promise.all([- proc.exited,- new Response(proc.stderr).text(),- ]);- if (code !== 0) throw new Error(error);- source = await readFile(path);-});-afterEach(() => {- globalThis.fetch = originalFetch;- if (originalSecret === undefined)- delete process.env.MEDIA_SERVER_WEBHOOK_SECRET;- else process.env.MEDIA_SERVER_WEBHOOK_SECRET = originalSecret;-});-afterAll(async () => {- await rm(directory, { recursive: true, force: true });-});--function call(- body = { ...request, sourceSize: source.byteLength },- authorized = true,-) {- process.env.MEDIA_SERVER_WEBHOOK_SECRET = "test-secret";- return audioLevels.request("https://media.test/levels", {- method: "POST",- headers: {- "Content-Type": "application/json",- ...(authorized ? { "x-media-server-secret": "test-secret" } : {}),- },- body: JSON.stringify(body),- });-}--function storage(- options: {- changedSource?: boolean;- corruptUpload?: boolean;- download?: () => Promise<void>;- } = {},-) {- let output: ArrayBuffer | undefined;- let uploads = 0;- globalThis.fetch = Object.assign(- async (input: string | URL | Request, init?: RequestInit) => {- const url = String(input);- if (url === request.sourceUrl) {- await options.download?.();- expect(new Headers(init?.headers).get("If-Match")).toBe(- request.sourceIdentity,- );- return new Response(Buffer.from(source), {- headers: { ETag: options.changedSource ? '"changed"' : '"source"' },- });- }- expect(url).toBe(request.outputUrl);- if (init?.method === "PUT") {- expect(new Headers(init.headers).get("If-None-Match")).toBe("*");- output = await new Response(init.body).arrayBuffer();- uploads++;- return new Response(null, { headers: { ETag: '"output"' } });- }- if (!output) throw new Error("Output not uploaded");- const bytes = output.slice(0);- if (options.corruptUpload) new Uint8Array(bytes)[0] ^= 1;- return new Response(init?.method === "HEAD" ? null : bytes, {- headers: {- ETag: '"output"',- "Content-Length": String(bytes.byteLength),- "Content-Type": "video/mp4",- },- });- },- { preconnect: originalFetch.preconnect },- );- return { uploads: () => uploads };-}--describe("audio levels serving boundary", () => {- test("publishes only after packet, audio and remote-byte verification", async () => {- const objects = storage();- const response = await call();- const result = await response.json();- expect(result.status).toBe("verified");- expect(result.outputLufs).toBeGreaterThan(result.inputLufs + 1);- expect(result.truePeak).toBeLessThanOrEqual(-1);- expect(objects.uploads()).toBe(1);- });- test("retains the original when stored output bytes differ", async () => {- storage({ corruptUpload: true });- expect((await (await call()).json()).status).toBe("unchanged");- });- test("does not process a changed source identity", async () => {- const objects = storage({ changedSource: true });- expect((await (await call()).json()).status).toBe("unchanged");- expect(objects.uploads()).toBe(0);- });- test("rejects oversized source and unauthorized requests", async () => {- expect(- (await call({ ...request, sourceSize: 257 * 1024 * 1024 })).status,- ).toBe(400);- expect((await call(undefined, false)).status).toBe(401);- });- test("limits enhancement concurrency without rejecting the recording", async () => {- let release: () => void = () => {};- let entered: () => void = () => {};- const started = new Promise<void>((resolve) => {- entered = resolve;- });- const pending = new Promise<void>((resolve) => {- release = resolve;- });- storage({- download: async () => {- entered();- await pending;- },- });- const first = call();- await started;- try {- expect(await (await call()).json()).toEqual({- status: "unchanged",- reason: "capacity",- });- } finally {- release();- }- expect((await (await first).json()).status).toBe("verified");- });-});diff --git a/apps/media-server/src/__tests__/lib/audio-levels.integration.test.ts b/apps/media-server/src/__tests__/lib/audio-levels.integration.test.tsnew file mode 100644index 000000000..475f831c0--- /dev/null+++ b/apps/media-server/src/__tests__/lib/audio-levels.integration.test.ts@@ -0,0 +1,364 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ spyOn,+ test,+} from "bun:test";+import { createHash } from "node:crypto";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { enhanceLocalRecording } from "../../lib/audio-levels";+import * as jobManager from "../../lib/job-manager";+import * as operations from "../../lib/media-operations";+import { probeVideoFile } from "../../lib/media-probe";+import { withMediaTransfers } from "../../lib/media-transfer";+import { processVideo } from "../../lib/media-video";+import {+ getActiveDirectVideoProcessCount,+ tryAcquireDirectVideoProcessSlot,+} from "../../lib/video-capacity";++let directory: string;+let source: Uint8Array;+const originalFetch = globalThis.fetch;+const originalSecret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;+let capacity: ReturnType<typeof spyOn>;+let audioCapacity: ReturnType<typeof spyOn>;+const request = {+ videoId: "video",+ userId: "owner",+ jobId: "job",+ sourceKey: "owner/video/result.mp4",+ webhookUrl: "https://web.test/progress",+ webhookSecret: "secret",+ duration: 4,+ sourceIdentity: '"source"',+ outputUrl: "https://storage.test/output.mp4",+ verificationUrl: "https://storage.test/output.mp4",+};++beforeAll(async () => {+ directory = await mkdtemp(join(tmpdir(), "cap-audio-route-"));+ const path = join(directory, "source.mp4");+ const proc = Bun.spawn(+ [+ "ffmpeg",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "testsrc2=size=160x90:rate=15:duration=4",+ "-f",+ "lavfi",+ "-i",+ "aevalsrc=0.02*sin(2*PI*440*t):s=48000:d=4",+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-c:a",+ "aac",+ "-threads",+ "1",+ path,+ ],+ { stdout: "ignore", stderr: "pipe" },+ );+ const [code, error] = await Promise.all([+ proc.exited,+ new Response(proc.stderr).text(),+ ]);+ if (code !== 0) throw new Error(error);+ source = await readFile(path);+});+beforeEach(() => {+ capacity = spyOn(jobManager, "canAcceptNewVideoProcess").mockReturnValue(+ true,+ );+ audioCapacity = spyOn(+ operations,+ "canAcceptNewAudioOperation",+ ).mockReturnValue(true);+});+afterEach(() => {+ capacity.mockRestore();+ audioCapacity.mockRestore();+ globalThis.fetch = originalFetch;+ if (originalSecret === undefined)+ delete process.env.MEDIA_SERVER_WEBHOOK_SECRET;+ else process.env.MEDIA_SERVER_WEBHOOK_SECRET = originalSecret;+});+afterAll(async () => {+ await rm(directory, { recursive: true, force: true });+});++function call(+ overrides: Partial<Parameters<typeof enhanceLocalRecording>[0]> = {},+) {+ return enhanceLocalRecording({+ ...request,+ path: join(directory, "source.mp4"),+ ...overrides,+ });+}+function storage(+ options: {+ corruptUpload?: boolean;+ prepare?: (signal?: AbortSignal | null) => Promise<void>;+ unavailable?: boolean;+ rejectPublication?: boolean;+ } = {},+) {+ let output: ArrayBuffer | undefined;+ let uploads = 0;+ let publications = 0;+ let preparations = 0;+ let downloadedBytes = 0;+ let fullDownloads = 0;+ globalThis.fetch = Object.assign(+ async (input: string | URL | Request, init?: RequestInit) => {+ const url = String(input);+ if (url === request.webhookUrl) {+ expect(init?.method).toBe("POST");+ expect(new Headers(init?.headers).get("x-media-server-secret")).toBe(+ request.webhookSecret,+ );+ const body = JSON.parse(String(init?.body));+ if (body.action === "prepare") {+ preparations++;+ await options.prepare?.(init?.signal);+ return Response.json(+ options.unavailable+ ? { status: "unchanged" }+ : {+ status: "prepared",+ outputUrl: request.outputUrl,+ verificationUrl: request.verificationUrl,+ token: "token",+ transferBudgetBytes: 16 * 1024 * 1024,+ },+ );+ }+ publications++;+ expect(output).toBeDefined();+ expect(body.action).toBe("publish");+ return Response.json({+ status: options.rejectPublication ? "unchanged" : "published",+ });+ }+ expect(url).toBe(request.outputUrl);+ if (init?.method === "PUT") {+ expect(new Headers(init.headers).get("If-None-Match")).toBe("*");+ output = await new Response(init.body).arrayBuffer();+ uploads++;+ return new Response(null, { headers: { ETag: '"output"' } });+ }+ if (!output) throw new Error("Output not uploaded");+ if (new Headers(init?.headers).get("range") === "bytes=0-0") {+ downloadedBytes++;+ return new Response(output.slice(0, 1), {+ status: 206,+ headers: {+ ETag: '"output"',+ "Content-Length": "1",+ "Content-Range": `bytes 0-0/${output.byteLength}`,+ },+ });+ }+ const bytes = output.slice(0);+ downloadedBytes += bytes.byteLength;+ fullDownloads++;+ if (options.corruptUpload) new Uint8Array(bytes)[0] ^= 1;+ return new Response(init?.method === "HEAD" ? null : bytes, {+ headers: {+ ETag: '"output"',+ "Content-Length": String(bytes.byteLength),+ "Content-Type": "video/mp4",+ },+ });+ },+ { preconnect: originalFetch.preconnect },+ );+ return {+ uploads: () => uploads,+ publications: () => publications,+ preparations: () => preparations,+ downloadedBytes: () => downloadedBytes,+ fullDownloads: () => fullDownloads,+ };+}+const hash = (bytes: Uint8Array) =>+ createHash("sha256").update(bytes).digest("hex");++describe("local audio levels integration", () => {+ test("publishes from the local file without a source download or source mutation", async () => {+ const objects = storage();+ const result = await call();+ expect(result.status).toBe("published");+ if (result.status !== "published") throw new Error(result.reason);+ expect(result.outputLufs).toBeGreaterThan(result.inputLufs + 1);+ expect(result.truePeak).toBeLessThanOrEqual(-1);+ expect(objects.uploads()).toBe(1);+ expect(objects.publications()).toBe(1);+ expect(objects.fullDownloads()).toBe(1);+ expect(objects.downloadedBytes()).toBe(result.outputSize + 2);+ expect(hash(await readFile(join(directory, "source.mp4")))).toBe(+ hash(source),+ );+ });+ test("uses its reserved verification budget independently of the completed recording job", async () => {+ storage();+ expect((await withMediaTransfers(1, () => call())).status).toBe(+ "published",+ );+ });+ test("retains the original without network access when video capacity is exhausted", async () => {+ capacity.mockReturnValue(false);+ const objects = storage();+ expect(await call()).toEqual({ status: "unchanged", reason: "capacity" });+ expect(objects.preparations()).toBe(0);+ });+ test("retains the original without network access when audio capacity is exhausted", async () => {+ audioCapacity.mockReturnValue(false);+ const objects = storage();+ expect(await call()).toEqual({ status: "unchanged", reason: "capacity" });+ expect(objects.preparations()).toBe(0);+ });+ test("does not publish corrupted stored bytes", async () => {+ const objects = storage({ corruptUpload: true });+ expect((await call()).status).toBe("unchanged");+ expect(objects.publications()).toBe(0);+ });+ test("leaves an occupied conversion slot available to its current owner", async () => {+ const slot = tryAcquireDirectVideoProcessSlot(() => true);+ expect(slot).not.toBeNull();+ try {+ const objects = storage();+ expect(await call()).toEqual({ status: "unchanged", reason: "capacity" });+ expect(objects.preparations()).toBe(0);+ expect(getActiveDirectVideoProcessCount()).toBe(1);+ } finally {+ slot?.release();+ }+ });+ test("cancels optional work on shutdown and releases its processing slot", async () => {+ let entered: () => void = () => {};+ const started = new Promise<void>((resolve) => {+ entered = resolve;+ });+ storage({+ prepare: (signal) =>+ new Promise((_, reject) => {+ signal?.addEventListener(+ "abort",+ () => reject(new Error("Cancelled")),+ { once: true },+ );+ entered();+ }),+ });+ const pending = call();+ await started;+ await operations.cancelAllMediaOperations();+ expect((await pending).status).toBe("unchanged");+ expect(getActiveDirectVideoProcessCount()).toBe(0);+ expect(operations.getActiveAudioOperationCount()).toBe(0);+ expect(hash(await readFile(join(directory, "source.mp4")))).toBe(+ hash(source),+ );+ });+ test("does not render or upload when publication is unavailable", async () => {+ const objects = storage({ unavailable: true });+ expect((await call()).status).toBe("unchanged");+ expect(objects.uploads()).toBe(0);+ });+ test("retains the source if publication is rejected", async () => {+ storage({ rejectPublication: true });+ expect((await call()).status).toBe("unchanged");+ expect(hash(await readFile(join(directory, "source.mp4")))).toBe(+ hash(source),+ );+ });+ test.each([900.001, 0, -1, NaN, Infinity])(+ "skips unsupported duration %s without network access",+ async (duration) => {+ const objects = storage();+ expect((await call({ duration })).status).toBe("unchanged");+ expect(objects.preparations()).toBe(0);+ },+ );+ test("limits local correction concurrency", async () => {+ let release: () => void = () => {};+ let entered: () => void = () => {};+ const started = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const pending = new Promise<void>((resolve) => {+ release = resolve;+ });+ storage({+ prepare: async () => {+ entered();+ await pending;+ },+ });+ const first = call();+ await started;+ try {+ expect(getActiveDirectVideoProcessCount()).toBe(1);+ expect(await call()).toEqual({ status: "unchanged", reason: "capacity" });+ } finally {+ release();+ }+ expect((await first).status).toBe("published");+ expect(getActiveDirectVideoProcessCount()).toBe(0);+ });+ test("corrects the MP4 from the existing Chrome WebM conversion without downloading it", async () => {+ const rawPath = join(directory, "chrome.webm");+ const proc = Bun.spawn(+ [+ "ffmpeg",+ "-v",+ "error",+ "-i",+ join(directory, "source.mp4"),+ "-c:v",+ "libvpx-vp9",+ "-deadline",+ "realtime",+ "-cpu-used",+ "8",+ "-c:a",+ "libopus",+ "-threads",+ "1",+ rawPath,+ ],+ { stdout: "ignore", stderr: "pipe" },+ );+ const [code, error] = await Promise.all([+ proc.exited,+ new Response(proc.stderr).text(),+ ]);+ if (code !== 0) throw new Error(error);+ const rawHash = hash(await readFile(rawPath));+ const metadata = await probeVideoFile(rawPath);+ const mp4 = await processVideo(rawPath, metadata);+ try {+ const before = hash(await readFile(mp4.path));+ storage();+ const result = await call({ path: mp4.path });+ expect(result.status).toBe("published");+ expect(hash(await readFile(mp4.path))).toBe(before);+ expect(hash(await readFile(rawPath))).toBe(rawHash);+ } finally {+ await mp4.cleanup();+ }+ }, 30_000);+});diff --git a/apps/media-server/src/app.ts b/apps/media-server/src/app.tsindex b82788146..e50979955 100644--- a/apps/media-server/src/app.ts+++ b/apps/media-server/src/app.ts@@ -1,7 +1,6 @@import { Hono } from "hono";import { logger } from "hono/logger";import audio from "./routes/audio";-import audioLevels from "./routes/audio-levels";import health from "./routes/health";import video from "./routes/video";@@ -11,7 +10,6 @@ app.use("*", logger());app.route("/health", health);app.route("/audio", audio);-app.route("/audio", audioLevels);app.route("/video", video);app.get("/", (c) => {diff --git a/apps/media-server/src/lib/audio-levels.ts b/apps/media-server/src/lib/audio-levels.tsnew file mode 100644index 000000000..90f4f2a77--- /dev/null+++ b/apps/media-server/src/lib/audio-levels.ts@@ -0,0 +1,176 @@+import { file } from "bun";+import { z } from "zod";+import { createAudioQualityCandidate } from "./audio-quality";+import { canAcceptNewVideoProcess } from "./job-manager";+import {+ canAcceptNewAudioOperation,+ withMediaOperation,+} from "./media-operations";+import { withMediaTransfers } from "./media-transfer";+import { uploadFileToStorage } from "./media-video";+import { verifyRemoteRecordingBytes } from "./recording-verification";+import { tryAcquireDirectVideoProcessSlot } from "./video-capacity";++const preparedSchema = z.object({+ status: z.literal("prepared"),+ outputUrl: z.string().url().startsWith("https://"),+ verificationUrl: z.string().url().startsWith("https://"),+ token: z.string().min(1).max(16_384),+ transferBudgetBytes: z.number().int().positive().safe(),+});++let active = false;++export async function enhanceLocalRecording(input: {+ path: string;+ videoId: string;+ userId: string;+ jobId: string;+ sourceKey: string;+ sourceIdentity?: string;+ duration: number;+ webhookUrl?: string;+ webhookSecret?: string;+}) {+ const unchanged = (reason: string) => {+ console.info("[audio-levels] Original retained", {+ videoId: input.videoId,+ reason,+ });+ return { status: "unchanged" as const, reason };+ };+ if (active || !canAcceptNewAudioOperation() || !canAcceptNewVideoProcess())+ return unchanged("capacity");+ if (+ !input.webhookUrl?.startsWith("https://") ||+ !input.webhookSecret ||+ !input.sourceIdentity+ )+ return unchanged("unavailable");+ if (+ !Number.isFinite(input.duration) ||+ input.duration < 3 ||+ input.duration > 900+ )+ return unchanged("duration");+ let sourceSize: number;+ try {+ sourceSize = file(input.path).size;+ } catch {+ return unchanged("source-unavailable");+ }+ if (!sourceSize || sourceSize > 256 * 1024 * 1024) return unchanged("size");+ const slot = tryAcquireDirectVideoProcessSlot(canAcceptNewVideoProcess);+ if (!slot) return unchanged("capacity");+ const webhookUrl = input.webhookUrl;+ const webhookSecret = input.webhookSecret;+ active = true;+ try {+ return await withMediaOperation("audio", async (setCancel) => {+ const controller = new AbortController();+ setCancel(() => controller.abort());+ const signal = AbortSignal.any([+ controller.signal,+ AbortSignal.timeout(120_000),+ ]);+ const callback = async (body: Record<string, unknown>) => {+ const response = await fetch(webhookUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "x-media-server-secret": webhookSecret,+ },+ body: JSON.stringify({ kind: "audio-levels", ...body }),+ redirect: "error",+ signal,+ });+ if (!response.ok) throw new Error("Audio publication unavailable");+ return await response.json();+ };+ const prepared = preparedSchema.safeParse(+ await callback({+ action: "prepare",+ videoId: input.videoId,+ userId: input.userId,+ jobId: input.jobId,+ sourceKey: input.sourceKey,+ sourceIdentity: input.sourceIdentity,+ sourceSize,+ duration: input.duration,+ }),+ );+ if (!prepared.success) return unchanged("publication-unavailable");+ const candidate = await createAudioQualityCandidate(input.path, {+ mode: "shadow",+ profile: "levels",+ abortSignal: signal,+ maxDurationSeconds: 900,+ });+ if (candidate.status === "unchanged") return unchanged(candidate.reason);+ try {+ if (+ candidate.validationFailures.length ||+ candidate.output.lufs < candidate.input.lufs + 0.5+ )+ return unchanged("validation");+ const outputSize = file(candidate.path).size;+ if (outputSize * 2 + 2 > prepared.data.transferBudgetBytes)+ return unchanged("transfer-budget");+ const receipt = await uploadFileToStorage(+ candidate.path,+ { type: "put", url: prepared.data.outputUrl, ifNoneMatch: "*" },+ "video/mp4",+ signal,+ );+ const outputIdentity = receipt.objectIdentity;+ if (!outputIdentity) throw new Error("Missing output identity");+ const verified = await withMediaTransfers(+ prepared.data.transferBudgetBytes - outputSize,+ () =>+ verifyRemoteRecordingBytes(prepared.data.verificationUrl, {+ expectedSha256: candidate.outputSha256,+ expectedFileSize: outputSize,+ expectedObjectIdentity: outputIdentity,+ abortSignal: signal,+ }),+ );+ const result = {+ sourceSha256: candidate.sourceSha256,+ outputSha256: candidate.outputSha256,+ outputIdentity: verified.objectIdentity,+ outputSize,+ inputLufs: candidate.input.lufs,+ outputLufs: candidate.output.lufs,+ truePeak: candidate.output.truePeak,+ };+ const published = z+ .object({ status: z.literal("published") })+ .safeParse(+ await callback({+ action: "publish",+ token: prepared.data.token,+ ...result,+ }),+ );+ if (!published.success) return unchanged("publication-rejected");+ console.info("[audio-levels] Published", {+ videoId: input.videoId,+ ...result,+ elapsedMs: candidate.elapsedMs,+ });+ return {+ status: "published" as const,+ ...result,+ elapsedMs: candidate.elapsedMs,+ };+ } finally {+ await candidate.cleanup();+ }+ });+ } catch {+ return unchanged("processing-unavailable");+ } finally {+ active = false;+ slot.release();+ }+}diff --git a/apps/media-server/src/routes/audio-levels.ts b/apps/media-server/src/routes/audio-levels.tsdeleted file mode 100644index ef3843a53..000000000--- a/apps/media-server/src/routes/audio-levels.ts+++ /dev/null@@ -1,144 +0,0 @@-import { file } from "bun";-import { Hono } from "hono";-import { z } from "zod";-import { createAudioQualityCandidate } from "../lib/audio-quality";-import { validateMediaServerSecret } from "../lib/auth";-import { canAcceptNewVideoProcess } from "../lib/job-manager";-import {- canAcceptNewAudioOperation,- withMediaOperation,-} from "../lib/media-operations";-import { uploadFileToStorage } from "../lib/media-video";-import { verifyRemoteRecordingBytes } from "../lib/recording-verification";-import { createTempFile } from "../lib/temp-files";--const requestSchema = z.object({- sourceUrl: z.string().url().startsWith("https://"),- sourceIdentity: z.string().min(1).max(1024),- sourceSize: z- .number()- .int()- .positive()- .max(256 * 1024 * 1024),- outputUrl: z.string().url().startsWith("https://"),- verificationUrl: z.string().url().startsWith("https://"),-});--let active = false;-const audioLevels = new Hono();--audioLevels.post("/levels", async (c) => {- if (!validateMediaServerSecret(c))- return c.json({ error: "Unauthorized" }, 401);- const parsed = requestSchema.safeParse(await c.req.json().catch(() => null));- if (!parsed.success) return c.json({ error: "Invalid request" }, 400);- if (active || !canAcceptNewAudioOperation() || !canAcceptNewVideoProcess())- return c.json({ status: "unchanged", reason: "capacity" });- active = true;- try {- return await withMediaOperation("audio", async (setCancel) => {- const controller = new AbortController();- setCancel(() => controller.abort());- const signal = AbortSignal.any([- controller.signal,- c.req.raw.signal,- AbortSignal.timeout(120_000),- ]);- const input = await createTempFile(".mp4");- try {- const request = parsed.data;- const response = await fetch(request.sourceUrl, {- headers: { "If-Match": request.sourceIdentity },- redirect: "error",- signal,- });- if (- !response.ok ||- !response.body ||- response.headers.get("etag") !== request.sourceIdentity- ) {- await response.body?.cancel();- throw new Error("Source identity mismatch");- }- const reader = response.body.getReader();- const writer = file(input.path).writer();- let size = 0;- try {- for (;;) {- const { done, value } = await reader.read();- if (done) break;- size += value.byteLength;- if (size > request.sourceSize)- throw new Error("Source size exceeded");- writer.write(value);- }- } finally {- try {- await reader.cancel();- } finally {- await writer.end();- reader.releaseLock();- }- }- if (size !== request.sourceSize)- throw new Error("Source size mismatch");- const candidate = await createAudioQualityCandidate(input.path, {- mode: "shadow",- profile: "levels",- abortSignal: signal,- });- if (candidate.status === "unchanged") return c.json(candidate);- try {- if (- candidate.validationFailures.length ||- candidate.output.lufs < candidate.input.lufs + 0.5- )- return c.json({ status: "unchanged", reason: "validation" });- const receipt = await uploadFileToStorage(- candidate.path,- {- type: "put",- url: request.outputUrl,- ifNoneMatch: "*",- },- "video/mp4",- signal,- );- if (!receipt.objectIdentity)- throw new Error("Missing output identity");- const verified = await verifyRemoteRecordingBytes(- request.verificationUrl,- {- expectedSha256: candidate.outputSha256,- expectedFileSize: file(candidate.path).size,- expectedObjectIdentity: receipt.objectIdentity,- abortSignal: signal,- },- );- return c.json({- status: "verified",- version: candidate.version,- sourceSha256: candidate.sourceSha256,- outputSha256: candidate.outputSha256,- outputIdentity: verified.objectIdentity,- outputSize: verified.fileSize,- inputLufs: candidate.input.lufs,- outputLufs: candidate.output.lufs,- truePeak: candidate.output.truePeak,- elapsedMs: candidate.elapsedMs,- });- } finally {- await candidate.cleanup();- }- } finally {- await input.cleanup();- }- });- } catch {- return c.json({ status: "unchanged", reason: "processing-unavailable" });- } finally {- active = false;- }-});--export default audioLevels;diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.tsindex 2ba8ff070..3bfc5a731 100644--- a/apps/media-server/src/routes/video.ts+++ b/apps/media-server/src/routes/video.ts@@ -3,6 +3,7 @@ import { link } from "node:fs/promises";import { file } from "bun";import { Hono } from "hono";import { z } from "zod";+import { enhanceLocalRecording } from "../lib/audio-levels";import { validateMediaServerSecret } from "../lib/auth";import type {Job,@@ -110,6 +111,7 @@ const convertSchema = z.object({});const processSchema = z.object({+ audioLevels: z.boolean().optional(),videoId: z.string(),userId: z.string(),videoUrl: z.string().url(),@@ -1352,7 +1354,7 @@ async function processVideoAsync(});await sendWebhook(job);- await uploadFileToS3(+ const uploadReceipt = await uploadFileToS3(outputTempFile.path,outputPresignedUrl,"video/mp4",@@ -1411,6 +1413,19 @@ async function processVideoAsync(await sendWebhook(completedJob);}+ if (options.audioLevels)+ await enhanceLocalRecording({+ path: outputTempFile.path,+ videoId: options.videoId,+ userId: options.userId,+ jobId,+ sourceKey: `${options.userId}/${options.videoId}/result.mp4`,+ sourceIdentity: uploadReceipt?.objectIdentity,+ duration: metadata.duration,+ webhookUrl: options.webhookUrl,+ webhookSecret: options.webhookSecret,+ });+await inputTempFile.cleanup();await outputTempFile.cleanup();await repairedTempFile?.cleanup();@@ -1950,6 +1965,7 @@ async function verifyUploadedRecordingAsync(const muxSegmentsSchema = z.object({+ audioLevels: z.boolean().optional(),...recordingAttemptFields,requiredAudio: z.boolean().optional(),sourceObjects: z@@ -2071,6 +2087,7 @@ type MuxContext = Pick<| "inventorySha256"| "sourceObjects"| "requiredAudio"+ | "audioLevels">;function getMuxSegmentsOutputUpload(@@ -2898,7 +2915,8 @@ async function muxSegmentsAsync(progress: 100,metadata,});- sendCurrentJobWebhook(jobId);+ if (!(context.audioLevels && context.outputKey))+ sendCurrentJobWebhook(jobId);logVideoEvent("video_mux_succeeded", {jobId,videoId,@@ -2906,6 +2924,28 @@ async function muxSegmentsAsync(metadata,resources: getSystemResources(),});+ if (context.audioLevels && context.outputKey) {+ if (processingTimeout) clearTimeout(processingTimeout);+ const completedJob = getJob(jobId);+ if (completedJob) {+ try {+ await sendWebhook(completedJob);+ await enhanceLocalRecording({+ path: resultPath,+ videoId,+ userId: completedJob.userId,+ jobId,+ sourceKey: context.outputKey,+ sourceIdentity: uploadReceipt.objectIdentity,+ duration: metadata.duration,+ webhookUrl: completedJob.webhookUrl,+ webhookSecret: completedJob.webhookSecret,+ });+ } catch {+ console.warn("[audio-levels] Original retained", { videoId });+ }+ }+ }} catch (error: unknown) {logVideoEvent("video_mux_failed", {jobId,diff --git a/apps/web/__tests__/unit/audio-level-publication.test.ts b/apps/web/__tests__/unit/audio-level-publication.test.tsindex 6f152ac52..c44d7a02d 100644--- a/apps/web/__tests__/unit/audio-level-publication.test.ts+++ b/apps/web/__tests__/unit/audio-level-publication.test.ts@@ -4,9 +4,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({db: vi.fn(),access: vi.fn(),+ reserve: vi.fn(),fetch: vi.fn(),}));vi.mock("@cap/database", () => ({ db: mocks.db }));+vi.mock("@/lib/media-processing-budget", () => ({+ reserveMediaProcessingBudget: mocks.reserve,+}));vi.mock("@cap/env", () => ({serverEnv: () => ({MEDIA_SERVER_URL: "https://media.test",@@ -16,9 +20,6 @@ vi.mock("@cap/env", () => ({vi.mock("@cap/web-backend/src/Storage/index", () => ({Storage: { getAccessForVideo: mocks.access },}));-vi.mock("workflow", () => ({- getStepMetadata: () => ({ stepId: "step-test" }),-}));vi.mock("@/lib/video-storage", () => ({decodeStorageVideo: (value: unknown) => value,}));@@ -36,19 +37,20 @@ import {resolveRecordingObjectKey,} from "@cap/web-backend/src/Storage/recording-output";import { Video } from "@cap/web-domain";-import { enhanceRecordingAudio } from "@/workflows/enhance-recording-audio";+import { handleAudioLevelPublication } from "@/lib/audio-level-publication";const sourceKey = "owner/video/.recording/outputs/generation/attempt.mp4";let current: {id: string;ownerId: string;source: {- type: "desktopMP4";+ type: "desktopMP4" | "webMP4";outputKey?: string;audioLevelSourceKey?: string;audioLevelOutputKey?: string;};duration: number;+ orgId: string;bucket: string | null;storageIntegrationId: string | null;};@@ -56,15 +58,16 @@ let sourceIdentity: string;let jobState: string;let uploading: boolean;let writes: Record<string, unknown>[];-let onFetch: () => void;beforeEach(() => {vi.clearAllMocks();+ mocks.reserve.mockResolvedValue(1024 * 1024);current = {id: "video",ownerId: "owner",source: { type: "desktopMP4", outputKey: sourceKey },duration: 120,+ orgId: "org",bucket: null,storageIntegrationId: null,};@@ -72,7 +75,6 @@ beforeEach(() => {jobState = "verified";uploading = false;writes = [];- onFetch = () => {};const connection = {select: () => ({from: (table: unknown) => ({@@ -81,7 +83,7 @@ beforeEach(() => {table === videos? [structuredClone(current)]: table === videoProcessingJobs- ? [{ state: jobState }]+ ? [{ state: jobState, generation: "generation" }]: table === videoUploads && uploading? [{ phase: "processing" }]: [];@@ -95,6 +97,7 @@ beforeEach(() => {set: (value: Record<string, unknown>) => ({where: async () => {writes.push(value);+ Object.assign(current, value);},}),}),@@ -110,7 +113,7 @@ beforeEach(() => {provider: "s3",headObject: (key: string) =>Effect.succeed(- key === sourceKey+ key === sourceKey || key === "owner/video/result.mp4"? { ETag: sourceIdentity, ContentLength: 100 }: { ETag: '"output"', ContentLength: 150 },),@@ -121,110 +124,186 @@ beforeEach(() => {},]),);- mocks.fetch.mockImplementation(async () => {- onFetch();- return Response.json({- status: "verified",- version: "audio-quality-v3",- sourceSha256: "a".repeat(64),- outputSha256: "b".repeat(64),- outputIdentity: '"output"',- outputSize: 150,- inputLufs: -28,- outputLufs: -16,- truePeak: -2,- });- });+ mocks.fetch.mockRejectedValue(new Error("Unexpected web media transfer"));vi.stubGlobal("fetch", mocks.fetch);});+const request = {+ kind: "audio-levels",+ action: "prepare",+ videoId: "video",+ userId: "owner",+ jobId: "job",+ sourceKey,+ sourceIdentity: '"source"',+ sourceSize: 100,+ duration: 120,+};+const result = {+ kind: "audio-levels",+ action: "publish",+ sourceSha256: "a".repeat(64),+ outputSha256: "b".repeat(64),+ outputIdentity: '"output"',+ outputSize: 150,+ inputLufs: -28,+ outputLufs: -16,+ truePeak: -2,+};+async function prepare(overrides: Record<string, unknown> = {}) {+ const prepared = await handleAudioLevelPublication({+ ...request,+ ...overrides,+ });+ if (!("token" in prepared))+ throw new Error(`Preparation failed: ${JSON.stringify(prepared)}`);+ return prepared;+}+describe("audio derivative publication", () => {- it("publishes a separate key while retaining the original verification target", async () => {- await enhanceRecordingAudio("video", "owner");- expect(writes).toHaveLength(1);- const next = { ...current, ...writes[0] } as typeof current;- expect(next.source.outputKey).toBe(sourceKey);- expect(getPublishedRecordingOutputKey(next)).toBe(sourceKey);- expect(resolveRecordingObjectKey(next, sourceKey)).toBe(sourceKey);- expect(resolveRecordingObjectKey(next, "owner/video/result.mp4")).toBe(- next.source.audioLevelOutputKey,- );- expect(Video.getAudioLevelOutputKey(next)).toBe(- next.source.audioLevelOutputKey,- );+ it.each(["desktopMP4", "webMP4"] as const)(+ "publishes %s with the original retained",+ async (type) => {+ current.source.type = type;+ const original = type === "webMP4" ? "owner/video/result.mp4" : sourceKey;+ if (type === "webMP4") delete current.source.outputKey;+ const prepared = await prepare({ sourceKey: original });+ expect(+ await handleAudioLevelPublication({ ...result, token: prepared.token }),+ ).toEqual({ status: "published" });+ expect(writes).toHaveLength(1);+ expect(current.source.audioLevelSourceKey).toBe(original);+ expect(resolveRecordingObjectKey(current, "owner/video/result.mp4")).toBe(+ current.source.audioLevelOutputKey,+ );+ expect(getPublishedRecordingOutputKey(current)).toBe(+ type === "desktopMP4" ? sourceKey : undefined,+ );+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(+ await handleAudioLevelPublication({ ...result, token: prepared.token }),+ ).toEqual({ status: "unchanged" });+ expect(writes).toHaveLength(1);+ },+ );+ it.each([899.999, 900])("accepts a %s-second source", async (duration) => {+ current.duration = duration;+ expect((await prepare({ duration })).status).toBe("prepared");});- it.each(["source", "storage", "owner", "upload", "identity"])(- "does not publish after a concurrent %s change",- async (change) => {- onFetch = () => {- if (change === "source")- current.source.outputKey = "owner/video/.recording/outputs/new.mp4";- if (change === "storage") current.storageIntegrationId = "changed";- if (change === "owner") current.ownerId = "new-owner";- if (change === "upload") uploading = true;- if (change === "identity") sourceIdentity = '"changed"';- };- await enhanceRecordingAudio("video", "owner");+ it.each([900.001, 901, 1800, 0, -1, NaN, Infinity])(+ "rejects invalid duration %s before storage access",+ async (duration) => {+ expect(+ (await handleAudioLevelPublication({ ...request, duration })).status,+ ).toBe("unchanged");+ expect(mocks.access).not.toHaveBeenCalled();expect(writes).toHaveLength(0);},);- it("keeps original audio on capacity, invalid validation, and request failure", async () => {- for (const result of [- { status: "unchanged", reason: "capacity" },- { status: "verified", truePeak: 3 },+ it.each([+ "source",+ "storage",+ "bucket",+ "owner",+ "org",+ "upload",+ "identity",+ ])("rejects a concurrent %s change", async (change) => {+ const prepared = await prepare();+ if (change === "source") current.source.outputKey = "new";+ if (change === "storage") current.storageIntegrationId = "new";+ if (change === "bucket") current.bucket = "new";+ if (change === "owner") current.ownerId = "new";+ if (change === "org") current.orgId = "new";+ if (change === "upload") uploading = true;+ if (change === "identity") sourceIdentity = '"changed"';+ expect(+ (await handleAudioLevelPublication({ ...result, token: prepared.token }))+ .status,+ ).toBe("unchanged");+ expect(writes).toHaveLength(0);+ });+ it("rejects an altered token and unsafe output measurements", async () => {+ const prepared = await prepare();+ for (const overrides of [+ { token: `${prepared.token}0` },+ { truePeak: 0 },+ { outputLufs: -30 },+ { outputSize: 1024 * 1024 },]) {- mocks.fetch.mockResolvedValueOnce(Response.json(result));- await enhanceRecordingAudio("video", "owner");+ expect(+ (+ await handleAudioLevelPublication({+ ...result,+ token: prepared.token,+ ...overrides,+ })+ ).status,+ ).toBe("unchanged");}- mocks.fetch.mockRejectedValueOnce(new Error("timeout"));- await expect(- enhanceRecordingAudio("video", "owner"),- ).resolves.toBeUndefined();expect(writes).toHaveLength(0);});- it.each([899.999, 900])(- "enhances eligible recordings lasting %s seconds",- async (duration) => {- current.duration = duration;- await enhanceRecordingAudio("video", "owner");- expect(mocks.fetch).toHaveBeenCalledTimes(1);- expect(writes).toHaveLength(1);- },- );- it.each([900.001, 901, 1800])(- "skips recordings lasting %s seconds before accessing storage",- async (duration) => {- current.duration = duration;- await enhanceRecordingAudio("video", "owner");- expect(mocks.access).not.toHaveBeenCalled();- expect(mocks.fetch).not.toHaveBeenCalled();+ it("rejects an expired publication token", async () => {+ const prepared = await prepare();+ const now = Date.now();+ const clock = vi.spyOn(Date, "now").mockReturnValue(now + 11 * 60_000);+ try {+ expect(+ (+ await handleAudioLevelPublication({+ ...result,+ token: prepared.token,+ })+ ).status,+ ).toBe("unchanged");expect(writes).toHaveLength(0);- },- );- it("does not enhance unverified, legacy or already enhanced recordings", async () => {+ } finally {+ clock.mockRestore();+ }+ });+ it("retains originals when storage or the transfer budget is unavailable", async () => {+ mocks.reserve.mockRejectedValueOnce(new Error("budget exhausted"));+ expect((await handleAudioLevelPublication(request)).status).toBe(+ "unchanged",+ );+ mocks.access.mockImplementationOnce(() =>+ Effect.fail(new Error("storage unavailable")),+ );+ expect((await handleAudioLevelPublication(request)).status).toBe(+ "unchanged",+ );+ expect(writes).toHaveLength(0);+ });+ it("skips unverified and actively uploading originals", async () => {jobState = "processing";- await enhanceRecordingAudio("video", "owner");+ expect((await handleAudioLevelPublication(request)).status).toBe(+ "unchanged",+ );jobState = "verified";- current.source.outputKey = undefined;- await enhanceRecordingAudio("video", "owner");- current.source.outputKey = sourceKey;- current.source.audioLevelOutputKey = "existing";- await enhanceRecordingAudio("video", "owner");- expect(mocks.fetch).not.toHaveBeenCalled();+ uploading = true;+ expect((await handleAudioLevelPublication(request)).status).toBe(+ "unchanged",+ );+ expect(mocks.access).not.toHaveBeenCalled();});- it("rejects foreign, stale and malformed playback keys", () => {- current.source.audioLevelSourceKey = sourceKey;- for (const key of [- "other/video/.recording/outputs/audio-quality-v3/test.mp4",- "owner/video/.recording/outputs/audio-quality-v3/../test.mp4",- "owner/video/.recording/outputs/unrelated.mp4",- ]) {- current.source.audioLevelOutputKey = key;+ it.each(["desktopMP4", "webMP4"] as const)(+ "rejects foreign and stale %s playback pointers",+ (type) => {+ current.source.type = type;+ current.source.audioLevelSourceKey =+ type === "webMP4" ? "owner/video/result.mp4" : sourceKey;+ for (const key of [+ "other/video/.recording/outputs/audio-quality-v3/x.mp4",+ "owner/video/.recording/outputs/audio-quality-v3/../x.mp4",+ "owner/video/.recording/outputs/unrelated.mp4",+ ]) {+ current.source.audioLevelOutputKey = key;+ expect(Video.getAudioLevelOutputKey(current)).toBeUndefined();+ }+ current.source.audioLevelOutputKey =+ "owner/video/.recording/outputs/audio-quality-v3/x.mp4";+ current.source.audioLevelSourceKey = "stale";expect(Video.getAudioLevelOutputKey(current)).toBeUndefined();- }- current.source.audioLevelOutputKey =- "owner/video/.recording/outputs/audio-quality-v3/test.mp4";- current.source.audioLevelSourceKey = "stale";- expect(Video.getAudioLevelOutputKey(current)).toBeUndefined();- });+ },+ );});diff --git a/apps/web/__tests__/unit/media-server-progress.test.ts b/apps/web/__tests__/unit/media-server-progress.test.tsindex 343d0d630..02928f4d2 100644--- a/apps/web/__tests__/unit/media-server-progress.test.ts+++ b/apps/web/__tests__/unit/media-server-progress.test.ts@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({queue: vi.fn(),transcribe: vi.fn(),invalidateQuota: vi.fn(),+ audio: vi.fn(),tables: {videos: {id: "videos.id",@@ -26,6 +27,9 @@ const mocks = vi.hoisted(() => ({}));vi.mock("@cap/database", () => ({ db: mocks.db }));+vi.mock("@/lib/audio-level-publication", () => ({+ handleAudioLevelPublication: mocks.audio,+}));vi.mock("@cap/database/schema", () => ({videos: mocks.tables.videos,videoProcessingJobs: mocks.tables.jobs,@@ -267,6 +271,7 @@ function request(describe("media-server recording progress webhook", () => {beforeEach(() => {mocks.secret = "media-secret";+ mocks.audio.mockReset().mockResolvedValue({ status: "prepared" });mocks.storage.mockReturnValue(Effect.succeed([{ headObject: mocks.head }]));mocks.head.mockImplementation((key: string) =>key.endsWith(".mp4")@@ -286,6 +291,14 @@ describe("media-server recording progress webhook", () => {vi.spyOn(console, "error").mockImplementation(() => undefined);});+ it("authenticates audio publication before dispatching it without ordinary progress updates", async () => {+ const body = { kind: "audio-levels", action: "prepare" };+ expect((await request(body, "wrong-secret")).status).toBe(401);+ expect(mocks.audio).not.toHaveBeenCalled();+ expect(await (await request(body)).json()).toEqual({ status: "prepared" });+ expect(mocks.audio).toHaveBeenCalledExactlyOnceWith(body);+ });+it.each([null, "wrong-secret", "éééééééééééé"])("rejects unauthenticated callbacks before publication %s",async (secret) => {diff --git a/apps/web/app/api/webhooks/media-server/progress/route.ts b/apps/web/app/api/webhooks/media-server/progress/route.tsindex 106f468ce..cbf7a9510 100644--- a/apps/web/app/api/webhooks/media-server/progress/route.ts+++ b/apps/web/app/api/webhooks/media-server/progress/route.ts@@ -5,6 +5,7 @@ import { serverEnv } from "@cap/env";import type { Video } from "@cap/web-domain";import { eq, sql } from "drizzle-orm";import { type NextRequest, NextResponse } from "next/server";+import { handleAudioLevelPublication } from "@/lib/audio-level-publication";import { SourceCommitPendingError } from "@/lib/desktop-recording-jobs";import { applyDesktopRecordingProgress } from "@/lib/desktop-recording-publication";import { createVerifiedRecordingReceipt } from "@/lib/desktop-recording-upload-status";@@ -100,7 +101,15 @@ export async function POST(request: NextRequest) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}- const payload: ProgressWebhookPayload = await request.json();+ const body: unknown = await request.json();+ if (+ body &&+ typeof body === "object" &&+ "kind" in body &&+ body.kind === "audio-levels"+ )+ return NextResponse.json(await handleAudioLevelPublication(body));+ const payload = body as ProgressWebhookPayload;const recordingProgress = await applyDesktopRecordingProgress(payload);if (recordingProgress.handled) {if (recordingProgress.published) {diff --git a/apps/web/lib/audio-level-publication.ts b/apps/web/lib/audio-level-publication.tsnew file mode 100644index 000000000..ec927b6d9--- /dev/null+++ b/apps/web/lib/audio-level-publication.ts@@ -0,0 +1,276 @@+import { createHash, createHmac, timingSafeEqual } from "node:crypto";+import { db } from "@cap/database";+import {+ videoProcessingJobs,+ videos,+ videoUploads,+} from "@cap/database/schema";+import { serverEnv } from "@cap/env";+import { Storage } from "@cap/web-backend/src/Storage/index";+import { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { Effect } from "effect";+import { z } from "zod";+import { reserveMediaProcessingBudget } from "@/lib/media-processing-budget";+import { decodeStorageVideo } from "@/lib/video-storage";+import { runWorkflowPromise } from "@/lib/workflow-runtime";++const digestSchema = z.string().regex(/^[a-f0-9]{64}$/);+const identitySchema = z.string().min(1).max(1024);+const sizeSchema = z+ .number()+ .int()+ .positive()+ .max(256 * 1024 * 1024);+const prepareSchema = z.object({+ kind: z.literal("audio-levels"),+ action: z.literal("prepare"),+ videoId: z.string().min(1).max(255),+ userId: z.string().min(1).max(255),+ jobId: z.string().min(1).max(255),+ sourceKey: z.string().min(1).max(1024),+ sourceIdentity: identitySchema,+ sourceSize: sizeSchema,+ duration: z.number().finite().min(3).max(900),+});+const tokenSchema = prepareSchema.extend({+ orgId: z.string().nullable(),+ bucket: z.string().nullable(),+ storageIntegrationId: z.string().nullable(),+ source: z.string(),+ outputKey: z.string(),+ transferBudgetBytes: z.number().int().positive().safe(),+ expiresAt: z.number(),+});+const publishSchema = z.object({+ kind: z.literal("audio-levels"),+ action: z.literal("publish"),+ token: z.string().max(16_384),+ sourceSha256: digestSchema,+ outputSha256: digestSchema,+ outputIdentity: identitySchema,+ outputSize: z+ .number()+ .int()+ .positive()+ .max(512 * 1024 * 1024),+ inputLufs: z.number().finite().min(-50).max(-18),+ outputLufs: z.number().finite().max(-14),+ truePeak: z.number().finite().max(-1),+});++const unchanged = (reason: string) => ({+ status: "unchanged" as const,+ reason,+});++function sign(value: string, secret: string) {+ return createHmac("sha256", secret).update(value).digest("hex");+}++function decodeToken(token: string, secret: string) {+ const [encoded, signature, extra] = token.split(".");+ if (!encoded || !signature || extra || !/^[a-f0-9]{64}$/.test(signature))+ throw new Error("Invalid publication token");+ if (+ !timingSafeEqual(+ Buffer.from(signature, "hex"),+ Buffer.from(sign(encoded, secret), "hex"),+ )+ )+ throw new Error("Invalid publication token");+ const context = tokenSchema.parse(+ JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")),+ );+ if (context.expiresAt <= Date.now()) throw new Error("Expired publication");+ return context;+}++function originalKey(video: typeof videos.$inferSelect) {+ if (video.source.type === "webMP4")+ return `${video.ownerId}/${video.id}/result.mp4`;+ if (video.source.type === "desktopMP4")+ return Video.getRetainedRecordingOutputKey(+ video.ownerId,+ video.id,+ video.source.outputKey,+ );+}++export async function handleAudioLevelPublication(payload: unknown) {+ try {+ const secret = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;+ if (!secret) return unchanged("unavailable");+ const prepare = prepareSchema.safeParse(payload);+ if (prepare.success) {+ const request = prepare.data;+ const id = Video.VideoId.make(request.videoId);+ const [video] = await db().select().from(videos).where(eq(videos.id, id));+ if (+ !video ||+ video.ownerId !== request.userId ||+ originalKey(video) !== request.sourceKey ||+ Video.getAudioLevelOutputKey(video) ||+ !video.duration ||+ !Number.isFinite(video.duration) ||+ video.duration < 3 ||+ video.duration > 900+ )+ return unchanged("ineligible");+ const [upload] = await db()+ .select()+ .from(videoUploads)+ .where(eq(videoUploads.videoId, id));+ if (upload) return unchanged("upload-active");+ if (video.source.type === "desktopMP4") {+ const [job] = await db()+ .select()+ .from(videoProcessingJobs)+ .where(eq(videoProcessingJobs.videoId, id));+ if (job?.state !== "verified") return unchanged("unverified");+ }+ const [bucket] = await Storage.getAccessForVideo(+ decodeStorageVideo(video),+ {+ resolvePublishedOutput: false,+ },+ ).pipe(runWorkflowPromise);+ if (bucket.provider !== "s3") return unchanged("unsupported-storage");+ const source = await bucket+ .headObject(request.sourceKey)+ .pipe(Effect.timeout("10 seconds"), runWorkflowPromise);+ if (+ source.ETag !== request.sourceIdentity ||+ source.ContentLength !== request.sourceSize+ )+ return unchanged("source-changed");+ const identity = createHash("sha256")+ .update(`${request.sourceKey}:${request.sourceIdentity}`)+ .digest("hex");+ const attempt = createHash("sha256")+ .update(`${identity}:${request.jobId}`)+ .digest("hex");+ const transferBudgetBytes = await reserveMediaProcessingBudget({+ videoId: video.id,+ generation: `audio-${identity}`,+ attemptId: attempt,+ sourceBytes: request.sourceSize,+ });+ const outputKey = `${video.ownerId}/${video.id}/.recording/outputs/audio-quality-v3/${attempt}.mp4`;+ const [outputUrl, verificationUrl] = await Promise.all([+ bucket+ .getInternalPresignedPutUrl(+ outputKey,+ { ContentType: "video/mp4", IfNoneMatch: "*" },+ { expiresIn: 600 },+ )+ .pipe(runWorkflowPromise),+ bucket+ .getInternalSignedObjectUrl(outputKey, { expiresIn: 600 })+ .pipe(runWorkflowPromise),+ ]);+ const context: z.infer<typeof tokenSchema> = {+ ...request,+ orgId: video.orgId,+ bucket: video.bucket,+ storageIntegrationId: video.storageIntegrationId,+ source: JSON.stringify(video.source),+ outputKey,+ transferBudgetBytes,+ expiresAt: Date.now() + 10 * 60_000,+ };+ const encoded = Buffer.from(JSON.stringify(context)).toString(+ "base64url",+ );+ return {+ status: "prepared" as const,+ outputUrl,+ verificationUrl,+ token: `${encoded}.${sign(encoded, secret)}`,+ transferBudgetBytes,+ };+ }+ const parsed = publishSchema.safeParse(payload);+ if (!parsed.success) return unchanged("invalid-request");+ const result = parsed.data;+ if (+ result.outputLufs < result.inputLufs + 0.5 ||+ result.outputLufs > result.inputLufs + 12.75+ )+ return unchanged("invalid-levels");+ const context = decodeToken(result.token, secret);+ if (result.outputSize * 2 > context.transferBudgetBytes)+ return unchanged("transfer-budget");+ const id = Video.VideoId.make(context.videoId);+ const published = await db().transaction(async (tx) => {+ const [video] = await tx+ .select()+ .from(videos)+ .where(eq(videos.id, id))+ .for("update");+ if (+ !video ||+ video.ownerId !== context.userId ||+ video.orgId !== context.orgId ||+ video.bucket !== context.bucket ||+ video.storageIntegrationId !== context.storageIntegrationId ||+ JSON.stringify(video.source) !== context.source ||+ originalKey(video) !== context.sourceKey+ )+ return false;+ const [upload] = await tx+ .select()+ .from(videoUploads)+ .where(eq(videoUploads.videoId, id));+ if (+ upload ||+ (video.source.type !== "desktopMP4" && video.source.type !== "webMP4")+ )+ return false;+ const [bucket] = await Storage.getAccessForVideo(+ decodeStorageVideo(video),+ {+ resolvePublishedOutput: false,+ },+ ).pipe(runWorkflowPromise);+ const [source, output] = await Promise.all([+ bucket+ .headObject(context.sourceKey)+ .pipe(Effect.timeout("10 seconds"), runWorkflowPromise),+ bucket+ .headObject(context.outputKey)+ .pipe(Effect.timeout("10 seconds"), runWorkflowPromise),+ ]);+ if (+ source.ETag !== context.sourceIdentity ||+ source.ContentLength !== context.sourceSize ||+ output.ETag !== result.outputIdentity ||+ output.ContentLength !== result.outputSize+ )+ return false;+ await tx+ .update(videos)+ .set({+ source: {+ ...video.source,+ audioLevelSourceKey: context.sourceKey,+ audioLevelOutputKey: context.outputKey,+ },+ })+ .where(eq(videos.id, id));+ return true;+ });+ console.info("[audio-levels] Publication", {+ videoId: context.videoId,+ published,+ inputLufs: result.inputLufs,+ outputLufs: result.outputLufs,+ truePeak: result.truePeak,+ });+ return {+ status: published ? ("published" as const) : ("unchanged" as const),+ };+ } catch {+ return unchanged("unavailable");+ }+}diff --git a/apps/web/workflows/enhance-recording-audio.ts b/apps/web/workflows/enhance-recording-audio.tsdeleted file mode 100644index 4538043ac..000000000--- a/apps/web/workflows/enhance-recording-audio.ts+++ /dev/null@@ -1,166 +0,0 @@-import { createHash } from "node:crypto";-import { db } from "@cap/database";-import {- videoProcessingJobs,- videos,- videoUploads,-} from "@cap/database/schema";-import { serverEnv } from "@cap/env";-import { Storage } from "@cap/web-backend/src/Storage/index";-import { Video } from "@cap/web-domain";-import { and, eq } from "drizzle-orm";-import { getStepMetadata } from "workflow";-import { z } from "zod";-import { decodeStorageVideo } from "@/lib/video-storage";-import { runWorkflowPromise } from "@/lib/workflow-runtime";--const responseSchema = z.object({- status: z.literal("verified"),- version: z.literal("audio-quality-v3"),- sourceSha256: z.string().regex(/^[a-f0-9]{64}$/),- outputSha256: z.string().regex(/^[a-f0-9]{64}$/),- outputIdentity: z.string().min(1),- outputSize: z.number().int().positive().safe(),- inputLufs: z.number().finite(),- outputLufs: z.number().finite().max(-14),- truePeak: z.number().finite().max(-1),-});--export async function enhanceRecordingAudio(videoId: string, userId: string) {- "use step";-- try {- const env = serverEnv();- if (!env.MEDIA_SERVER_URL || !env.MEDIA_SERVER_WEBHOOK_SECRET) return;- const id = Video.VideoId.make(videoId);- const [video] = await db().select().from(videos).where(eq(videos.id, id));- if (- !video ||- video.ownerId !== userId ||- video.source.type !== "desktopMP4" ||- video.source.audioLevelOutputKey ||- !video.duration ||- video.duration > 900- )- return;- const sourceKey = Video.getRetainedRecordingOutputKey(- userId,- videoId,- video.source.outputKey,- );- if (!sourceKey) return;- const source = video.source;- const [job] = await db()- .select()- .from(videoProcessingJobs)- .where(eq(videoProcessingJobs.videoId, id));- if (job?.state !== "verified") return;- const [bucket] = await Storage.getAccessForVideo(- decodeStorageVideo(video),- ).pipe(runWorkflowPromise);- if (bucket.provider !== "s3") return;- const sourceHead = await bucket- .headObject(sourceKey)- .pipe(runWorkflowPromise);- if (- !sourceHead.ETag ||- !sourceHead.ContentLength ||- sourceHead.ContentLength > 256 * 1024 * 1024- )- return;- const token = createHash("sha256")- .update(`${sourceKey}:${sourceHead.ETag}:${getStepMetadata().stepId}`)- .digest("hex");- const outputKey = `${userId}/${videoId}/.recording/outputs/audio-quality-v3/${token}.mp4`;- const [sourceUrl, outputUrl, verificationUrl] = await Promise.all([- bucket- .getInternalSignedObjectUrl(sourceKey, { expiresIn: 600 })- .pipe(runWorkflowPromise),- bucket- .getInternalPresignedPutUrl(- outputKey,- { ContentType: "video/mp4", IfNoneMatch: "*" },- { expiresIn: 600 },- )- .pipe(runWorkflowPromise),- bucket- .getInternalSignedObjectUrl(outputKey, { expiresIn: 600 })- .pipe(runWorkflowPromise),- ]);- const response = await fetch(`${env.MEDIA_SERVER_URL}/audio/levels`, {- method: "POST",- headers: {- "Content-Type": "application/json",- "x-media-server-secret": env.MEDIA_SERVER_WEBHOOK_SECRET,- },- body: JSON.stringify({- sourceUrl,- sourceIdentity: sourceHead.ETag,- sourceSize: sourceHead.ContentLength,- outputUrl,- verificationUrl,- }),- signal: AbortSignal.timeout(135_000),- });- if (!response.ok) return;- const payload: unknown = await response.json();- const parsed = responseSchema.safeParse(payload);- if (!parsed.success) {- const skipped = z- .object({ status: z.literal("unchanged"), reason: z.string().max(100) })- .safeParse(payload);- console.info("[audio-levels] Original retained", {- videoId,- reason: skipped.success ? skipped.data.reason : "invalid-response",- });- return;- }- const result = parsed.data;- const [currentSource, output] = await Promise.all([- bucket.headObject(sourceKey).pipe(runWorkflowPromise),- bucket.headObject(outputKey).pipe(runWorkflowPromise),- ]);- if (- currentSource.ETag !== sourceHead.ETag ||- currentSource.ContentLength !== sourceHead.ContentLength ||- output.ETag !== result.outputIdentity ||- output.ContentLength !== result.outputSize- )- return;- const published = await db().transaction(async (tx) => {- const [current] = await tx- .select()- .from(videos)- .where(eq(videos.id, id))- .for("update");- if (- !current ||- current.ownerId !== userId ||- current.orgId !== video.orgId ||- JSON.stringify(current.source) !== JSON.stringify(video.source) ||- current.bucket !== video.bucket ||- current.storageIntegrationId !== video.storageIntegrationId- )- return false;- const [upload] = await tx- .select()- .from(videoUploads)- .where(eq(videoUploads.videoId, id));- if (upload) return false;- await tx- .update(videos)- .set({- source: {- ...source,- audioLevelSourceKey: sourceKey,- audioLevelOutputKey: outputKey,- },- })- .where(and(eq(videos.id, id), eq(videos.ownerId, video.ownerId)));- return true;- });- console.info("[audio-levels] Result", { videoId, published, ...result });- } catch {- console.warn("[audio-levels] Original retained", { videoId });- }-}diff --git a/apps/web/workflows/finalize-desktop-recording.ts b/apps/web/workflows/finalize-desktop-recording.tsindex 2a4a02a31..cf1f5dfe4 100644--- a/apps/web/workflows/finalize-desktop-recording.ts+++ b/apps/web/workflows/finalize-desktop-recording.ts@@ -39,7 +39,6 @@ import { getMediaServerCapacityDelay } from "@/lib/media-server-backpressure";import { transcribeVideo } from "@/lib/transcribe";import { decodeStorageVideo } from "@/lib/video-storage";import { runWorkflowPromise } from "@/lib/workflow-runtime";-import { enhanceRecordingAudio } from "./enhance-recording-audio";interface FinalizeDesktopRecordingWorkflowPayload {videoId: string;@@ -196,8 +195,6 @@ export async function finalizeDesktopRecordingWorkflow(if (queued) break;await sleep(Math.min(15_000 * 2 ** Math.min(attempt, 5), 300_000));}- if (!mediaServerUnavailable)- await enhanceRecordingAudio(payload.videoId, payload.userId);return mediaServerUnavailable? { success: false, reason: "media-server-unconfigured" }: { success: true, ...(completedJobId ? { jobId: completedJobId } : {}) };@@ -541,6 +538,7 @@ export async function startDesktopRecordingJob(}path = "/video/mux-segments";body = {+ audioLevels: true,...context,...urls,...(await buildDesktopSegmentsOutput({ video, attempt })),diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.tsindex 6740ee24d..a1a95a3a3 100644--- a/apps/web/workflows/process-video.ts+++ b/apps/web/workflows/process-video.ts@@ -171,6 +171,7 @@ async function startMediaServerProcessJob(webhookUrl: string;webhookSecret?: string;inputExtension: string;+ audioLevels?: boolean;},): Promise<string> {for (let attempt = 0; attempt < MEDIA_SERVER_START_MAX_ATTEMPTS; attempt++) {@@ -334,6 +335,7 @@ async function processVideoOnMediaServer(.where(eq(videoUploads.videoId, videoId as Video.VideoId));await startMediaServerProcessJob(mediaServerUrl, {+ audioLevels: video.source.type === "webMP4",videoId,userId,videoUrl: rawVideoUrl,