Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: correct quiet recording levels after publication
Richie McIlroycb20fc73d600
diff --git a/.github/workflows/docker-build-media-server.yml b/.github/workflows/docker-build-media-server.ymlindex 6521617de..82378eb1e 100644--- a/.github/workflows/docker-build-media-server.yml+++ b/.github/workflows/docker-build-media-server.yml@@ -108,6 +108,8 @@ jobs:src/__tests__/lib/audio-quality.integration.test.ts \src/__tests__/lib/audio-quality-formats.integration.test.ts \src/__tests__/lib/audio-quality-benchmark.test.ts+ docker run --rm --network none --entrypoint bun "$MEDIA_IMAGE" test \+ src/__tests__/lib/audio-levels-route.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/.github/workflows/recording-reliability.yml b/.github/workflows/recording-reliability.ymlindex 9196e58fb..38a814aaf 100644--- a/.github/workflows/recording-reliability.yml+++ b/.github/workflows/recording-reliability.yml@@ -41,6 +41,9 @@ jobs:working-directory: apps/webrun: |pnpm exec vitest run \+ __tests__/unit/audio-level-publication.test.ts \+ __tests__/unit/recording-output.test.ts \+ __tests__/unit/recording-storage-lifecycle.test.ts \__tests__/unit/desktop-recording-*.test.ts \__tests__/unit/desktop-segments-*.test.ts \__tests__/unit/finalize-desktop-recording.test.ts \diff --git a/apps/media-server/audio-quality-benchmarks.md b/apps/media-server/audio-quality-benchmarks.mdindex 36f7ae241..50983e17d 100644--- a/apps/media-server/audio-quality-benchmarks.md+++ b/apps/media-server/audio-quality-benchmarks.md@@ -1,12 +1,26 @@# Instant audio quality experiment-This is an offline, shadow-only experiment. No route, recording finalizer, player,-export, upload, desktop capture path, or production flag imports the worker.-`mode: "off"` returns before filesystem access. There is no publishing mode.--The proposed first rollout is bounded, constant level correction, after production-validation. EQ and denoising remain experimental because consistent perceptual-improvement has not been established. This PR does not enable either profile.+The level-correction worker is connected to the desktop recording finalizer after+the original recording is verified and published. The original output key and+verification receipt remain intact. A separate, versioned MP4 becomes the playback+and download source only after local and remote-byte validation and an atomic check+that ownership, storage, source, and upload state have not changed.++The serving integration uses bounded, constant level correction. EQ and denoising+remain experimental because consistent perceptual improvement has not been+established. No desktop capture change is required.++Eligibility is limited to newly finalized, durably verified desktop MP4 recordings+on S3-compatible storage, at most 15 minutes and 256 MiB. All existing audio-policy+gates still apply. Google Drive, legacy recordings without an immutable output,+unsupported audio, and larger recordings retain their original audio. There is no+historical backfill. Only one enhancement runs per media-server replica, it requires+spare processing capacity, and the entire request has a two-minute deadline.+Capacity, timeout, transfer, or validation failures retain the original. The step+does not retry capacity failures or delay original publication.++Rollback to the previous web deployment selects the retained original output;+the original recording verification target is never redirected to a derivative.## Evidence and limits@@ -135,7 +149,7 @@ browser captures and recordings without completed transcripts, were left unchangby stream, level, headroom, or timestamp gates. All original hashes were preserved.These are bounded compatibility checks, not proof of safety for every possible file.-## Before serving any enhanced audio+## Before enabling voice processingHuman review of the 12 volume-matched A/B excerpts is still required. Speech-onlyeligibility, noisy and mixed-system-audio cases, and recordings excluded by the@@ -147,9 +161,10 @@ Run the exact policy in the production Linux image, then verify actual share-pagembed, seeking, downloads, edits, transcript alignment, and fallback behavior.Measure worker memory, throughput, storage, and tail latency before rollout.-Future integration should create a separately versioned derivative after the-original is available, using a durable idempotent job bound to the source hash.-Publish atomically only after validation and only if the source still matches.-Keep the original available throughout processing, on failure, and for rollback.-Existing desktop installs could then benefit server-side without a capture update;-this experiment does not yet implement that serving integration.+The level-correction integration runs as a durable Workflow step. Its immutable+derivative key is bound to the original key, object identity, and step identity.+The worker hashes the source and output, verifies video packets and audio timing,+and verifies the uploaded bytes before returning. Publication rechecks source and+output identities and locks the video row while selecting the derivative. A+response lost after upload can leave an unpublished derivative; it is never served+and remains under the recording's prefix for normal recording deletion.diff --git a/apps/web/__tests__/unit/audio-level-publication.test.ts b/apps/web/__tests__/unit/audio-level-publication.test.tsnew file mode 100644index 000000000..c618354ba--- /dev/null+++ b/apps/web/__tests__/unit/audio-level-publication.test.ts@@ -0,0 +1,211 @@+import { Effect } from "effect";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ db: vi.fn(),+ access: vi.fn(),+ fetch: vi.fn(),+}));+vi.mock("@cap/database", () => ({ db: mocks.db }));+vi.mock("@cap/env", () => ({+ serverEnv: () => ({+ MEDIA_SERVER_URL: "https://media.test",+ MEDIA_SERVER_WEBHOOK_SECRET: "secret",+ }),+}));+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,+}));+vi.mock("@/lib/workflow-runtime", async () => ({+ runWorkflowPromise: (await import("effect")).Effect.runPromise,+}));++import {+ videoProcessingJobs,+ videos,+ videoUploads,+} from "@cap/database/schema";+import {+ getPublishedRecordingOutputKey,+ resolveRecordingObjectKey,+} from "@cap/web-backend/src/Storage/recording-output";+import { Video } from "@cap/web-domain";+import { enhanceRecordingAudio } from "@/workflows/enhance-recording-audio";++const sourceKey = "owner/video/.recording/outputs/generation/attempt.mp4";+let current: {+ id: string;+ ownerId: string;+ source: {+ type: "desktopMP4";+ outputKey?: string;+ audioLevelSourceKey?: string;+ audioLevelOutputKey?: string;+ };+ duration: number;+ bucket: string | null;+ storageIntegrationId: string | null;+};+let sourceIdentity: string;+let jobState: string;+let uploading: boolean;+let writes: Record<string, unknown>[];+let onFetch: () => void;++beforeEach(() => {+ vi.clearAllMocks();+ current = {+ id: "video",+ ownerId: "owner",+ source: { type: "desktopMP4", outputKey: sourceKey },+ duration: 120,+ bucket: null,+ storageIntegrationId: null,+ };+ sourceIdentity = '"source"';+ jobState = "verified";+ uploading = false;+ writes = [];+ onFetch = () => {};+ const connection = {+ select: () => ({+ from: (table: unknown) => ({+ where: () => {+ const rows =+ table === videos+ ? [structuredClone(current)]+ : table === videoProcessingJobs+ ? [{ state: jobState }]+ : table === videoUploads && uploading+ ? [{ phase: "processing" }]+ : [];+ return Object.assign(Promise.resolve(rows), {+ for: () => Promise.resolve(rows),+ });+ },+ }),+ }),+ update: () => ({+ set: (value: Record<string, unknown>) => ({+ where: async () => {+ writes.push(value);+ },+ }),+ }),+ };+ mocks.db.mockReturnValue({+ ...connection,+ transaction: async (fn: (tx: typeof connection) => Promise<unknown>) =>+ fn(connection),+ });+ mocks.access.mockImplementation(() =>+ Effect.succeed([+ {+ provider: "s3",+ headObject: (key: string) =>+ Effect.succeed(+ key === sourceKey+ ? { ETag: sourceIdentity, ContentLength: 100 }+ : { ETag: '"output"', ContentLength: 150 },+ ),+ getInternalSignedObjectUrl: () =>+ Effect.succeed("https://storage.test/read"),+ getInternalPresignedPutUrl: () =>+ Effect.succeed("https://storage.test/write"),+ },+ ]),+ );+ 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,+ });+ });+ vi.stubGlobal("fetch", mocks.fetch);+});++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(["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");+ 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 },+ ]) {+ mocks.fetch.mockResolvedValueOnce(Response.json(result));+ await enhanceRecordingAudio("video", "owner");+ }+ mocks.fetch.mockRejectedValueOnce(new Error("timeout"));+ await expect(+ enhanceRecordingAudio("video", "owner"),+ ).resolves.toBeUndefined();+ expect(writes).toHaveLength(0);+ });+ it("does not enhance unverified, legacy or already enhanced recordings", async () => {+ jobState = "processing";+ await enhanceRecordingAudio("video", "owner");+ 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();+ });+ 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;+ 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/workflows/enhance-recording-audio.ts b/apps/web/workflows/enhance-recording-audio.tsnew file mode 100644index 000000000..4538043ac--- /dev/null+++ b/apps/web/workflows/enhance-recording-audio.ts@@ -0,0 +1,166 @@+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 c211271de..2a4a02a31 100644--- a/apps/web/workflows/finalize-desktop-recording.ts+++ b/apps/web/workflows/finalize-desktop-recording.ts@@ -39,6 +39,7 @@ 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;@@ -195,6 +196,8 @@ 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 } : {}) };