Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: reconcile audio levels with current main
Richie McIlroyb536c8505f90
diff --cc .github/workflows/recording-reliability.ymlindex 38a814aaf,d278b1a00..937c814c4--- a/.github/workflows/recording-reliability.yml+++ b/.github/workflows/recording-reliability.yml@@@ -50,4 -47,9 +50,10 @@@ jobs__tests__/unit/media-server-progress.test.ts \__tests__/unit/media-processing-budget.test.ts \__tests__/unit/playback-source.test.ts \- __tests__/unit/upload-progress-playback.test.ts+ __tests__/unit/share-page-loading.test.ts \+ __tests__/unit/media-player-store-refs.test.ts \+ __tests__/unit/video-edit-processing.test.ts \++ __tests__/unit/video-edit-published-output.test.ts \+ __tests__/unit/upload-progress-playback.test.ts \+ __tests__/unit/recording-prepare.test.ts \+ __tests__/unit/s3-bucket-connections.test.tsdiff --cc apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.tsindex d1e427d61,51979172e..1c7a4cc54--- a/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts+++ b/apps/media-server/src/__tests__/lib/media-routes-real-world.integration.test.ts@@@ -217,38 -216,25 +217,42 @@@ beforeAll(async () =>getJob = jobManager.getJob;deleteJob = jobManager.deleteJob;tempDir = mkdtempSync(join(tmpdir(), "cap-real-world-routes-"));+ execFileSync("ffmpeg", [+ "-v",+ "error",+ "-i",+ TEST_VIDEO_WITH_AUDIO,+ "-c:v",+ "libvpx-vp9",+ "-deadline",+ "realtime",+ "-cpu-used",+ "8",+ "-c:a",+ "libopus",+ "-threads",+ "1",+ join(tempDir, "chrome.webm"),+ ]);for (const kind of ["video", "audio"] as const) {const path = join(tempDir, `${kind}-fragmented.mp4`);- execFileSync("ffmpeg", [- "-v",- "error",- "-i",- TEST_VIDEO_WITH_AUDIO,- "-map",- kind === "video" ? "0:v:0" : "0:a:0",- "-c",- "copy",- "-movflags",- "+empty_moov+frag_keyframe+default_base_moof",- path,- ]);+ execFileSync(+ "ffmpeg",+ [+ "-v",+ "error",+ "-i",+ TEST_VIDEO_WITH_AUDIO,+ "-map",+ kind === "video" ? "0:v:0" : "0:a:0",+ "-c",+ "copy",+ "-movflags",+ "+empty_moov+frag_keyframe+default_base_moof",+ path,+ ],+ { stdio: "inherit" },+ );const bytes = new Uint8Array(await Bun.file(path).arrayBuffer());const view = new DataView(bytes.buffer);let split = 0;diff --cc apps/web/__tests__/unit/audio-level-publication.test.tsindex a7de7c099,000000000..932dae9b0mode 100644,000000..100644--- a/apps/web/__tests__/unit/audio-level-publication.test.ts+++ b/apps/web/__tests__/unit/audio-level-publication.test.ts@@@ -1,335 -1,0 +1,350 @@@+import { Effect } from "effect";+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",+ MEDIA_SERVER_WEBHOOK_SECRET: "secret",+ }),+}));+vi.mock("@cap/web-backend/src/Storage/index", () => ({+ Storage: { getAccessForVideo: mocks.access },+}));+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 { handleAudioLevelPublication } from "@/lib/audio-level-publication";++const sourceKey = "owner/video/.recording/outputs/generation/attempt.mp4";+let current: {+ id: string;+ ownerId: string;+ source: {+ type: "desktopMP4" | "webMP4";+ outputKey?: string;+ audioLevelSourceKey?: string;+ audioLevelOutputKey?: string;+ };+ duration: number;+ orgId: string;+ bucket: string | null;+ storageIntegrationId: string | null;+};+let sourceIdentity: string;+let jobState: string;+let uploading: boolean;+let writes: Record<string, unknown>[];++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,+ };+ sourceIdentity = '"source"';+ jobState = "verified";+ uploading = false;+ writes = [];+ const connection = {+ select: () => ({+ from: (table: unknown) => ({+ where: () => {+ const rows =+ table === videos+ ? [structuredClone(current)]+ : table === videoProcessingJobs+ ? [{ state: jobState, generation: "generation" }]+ : 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);+ Object.assign(current, 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 || key === "owner/video/result.mp4"+ ? { ETag: sourceIdentity, ContentLength: 100 }+ : { ETag: '"output"', ContentLength: 150 },+ ),+ getInternalSignedObjectUrl: () =>+ Effect.succeed("https://storage.test/read"),+ getInternalPresignedPutUrl: () =>+ Effect.succeed("https://storage.test/write"),+ },+ ]),+ );+ 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("rejects a late browser correction for a source replaced by an edit", async () => {++ current.source = {++ type: "webMP4",++ outputKey:++ "owner/video/.recording/outputs/edit-11111111-1111-4111-8111-111111111111/result.mp4",++ };++ expect(++ await handleAudioLevelPublication({++ ...request,++ sourceKey: "owner/video/result.mp4",++ }),++ ).toEqual({ status: "unchanged", reason: "ineligible" });++ expect(mocks.access).not.toHaveBeenCalled();++ expect(writes).toHaveLength(0);++ });+ it.each([+ { inputLufs: -50.48, outputLufs: -22.49, truePeak: -3.04 },+ { inputLufs: -55, outputLufs: -27, truePeak: -10 },+ { inputLufs: -35, outputLufs: -22, truePeak: -3 },+ ])(+ "selects a validated quiet correction for playback: %j",+ async (levels) => {+ const prepared = await prepare();+ expect(+ await handleAudioLevelPublication({+ ...result,+ ...levels,+ token: prepared.token,+ }),+ ).toEqual({ status: "published" });+ expect(writes).toHaveLength(1);+ expect(resolveRecordingObjectKey(current, "owner/video/result.mp4")).toBe(+ current.source.audioLevelOutputKey,+ );+ expect(getPublishedRecordingOutputKey(current)).toBe(sourceKey);+ },+ );+ 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([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.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 },+ { inputLufs: -55.01, outputLufs: -27.01 },+ { inputLufs: -50.48, outputLufs: -21.48 },+ { inputLufs: -35, outputLufs: -21 },+ { inputLufs: -30, outputLufs: -17 },+ { outputSize: 1024 * 1024 },+ ]) {+ expect(+ (+ await handleAudioLevelPublication({+ ...result,+ token: prepared.token,+ ...overrides,+ })+ ).status,+ ).toBe("unchanged");+ }+ expect(writes).toHaveLength(0);+ });+ 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);+ } 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";+ expect((await handleAudioLevelPublication(request)).status).toBe(+ "unchanged",+ );+ jobState = "verified";+ uploading = true;+ expect((await handleAudioLevelPublication(request)).status).toBe(+ "unchanged",+ );+ expect(mocks.access).not.toHaveBeenCalled();+ });+ 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();+ },+ );+});diff --cc apps/web/__tests__/unit/desktop-recording-output-replacement.test.tsindex 6af2ded70,ee20daa6d..caa36c364--- a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts+++ b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts@@@ -221,29 -244,6 +246,64 @@@ beforeEach(() =>afterEach(() => vi.unstubAllGlobals());describe("edited recording publication", () => {- it.each(["edit", "reprocess", "replace"])(++ it.each(["reprocess", "replace"])(+ "clears a browser audio derivative after %s",+ async (operation) => {+ video.source = {+ type: "webMP4",+ audioLevelSourceKey: "user/video/result.mp4",+ audioLevelOutputKey:+ "user/video/.recording/outputs/audio-quality-v3/test.mp4",+ };- if (operation === "edit")- await saveEditResultAndComplete(- "video",- "user/video/edit-original.mp4",- editSpec,- editSpec,- metadata,- );- else if (operation === "reprocess")++ if (operation === "reprocess")+ await saveMetadataAndComplete("video", metadata);+ else await invalidateVideoCache("video");+ expect(video.source).toEqual({ type: "webMP4" });+ },+ );++ it.each(["desktopMP4", "webMP4"])(++ "clears the previous audio derivative when publishing a %s edit",++ async (type) => {++ video.source = {++ type,++ ...(type === "desktopMP4"++ ? {++ outputKey: "user/video/.recording/outputs/generation/attempt.mp4",++ }++ : {}),++ audioLevelSourceKey:++ type === "desktopMP4"++ ? "user/video/.recording/outputs/generation/attempt.mp4"++ : "user/video/result.mp4",++ audioLevelOutputKey:++ "user/video/.recording/outputs/audio-quality-v3/test.mp4",++ };++ video.metadata.editProcessing = {++ ...operation,++ ownerId: video.ownerId,++ bucket: video.bucket,++ storageIntegrationId: video.storageIntegrationId,++ sourceKey,++ source: JSON.stringify(video.source),++ dispatch: "accepted",++ };++ await saveEditResultAndComplete(++ "video",++ sourceKey,++ editSpec,++ editSpec,++ metadata,++ operation,++ );++ expect(video.source).toEqual({++ type,++ outputKey: `user/video/.recording/outputs/edit-${operation.token}/result.mp4`,++ thumbnailKey: `user/video/.recording/outputs/edit-${operation.token}/thumbnail.jpg`,++ previewKey: `user/video/.recording/outputs/edit-${operation.token}/preview.gif`,++ });++ expect(video.metadata.completedVideoEdit).toMatchObject(operation);++ },++ );it("verifies the newly rendered canonical output instead of the old published immutable recording", async () => {await verifyRenderedEditOutput("video", "user", editSpec, metadata);expect(mocks.access).toHaveBeenCalledWith(video, {diff --cc apps/web/__tests__/unit/media-server-progress.test.tsindex 02928f4d2,c55705cc9..f4e817178--- a/apps/web/__tests__/unit/media-server-progress.test.ts+++ b/apps/web/__tests__/unit/media-server-progress.test.ts@@@ -291,14 -286,6 +291,35 @@@ describe("media-server recording progrevi.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("keeps stale edit callbacks out of recording and audio publication", async () => {++ const database = databaseFixture();++ const response = await POST(++ new NextRequest(++ "https://cap.so/api/webhooks/media-server/progress?editOperation=old-edit&editStartedAt=2026-09-08T12%3A00%3A00.000Z",++ {++ method: "POST",++ headers: {++ "Content-Type": "application/json",++ "x-media-server-secret": "media-secret",++ },++ body: JSON.stringify(fixture().payload),++ },++ ),++ );++ expect(response.status).toBe(200);++ expect(await response.json()).toEqual({ success: true });++ expect(database.mutations).toEqual([]);++ expect(mocks.audio).not.toHaveBeenCalled();++ expect(mocks.transcribe).not.toHaveBeenCalled();++ });+it.each([null, "wrong-secret", "éééééééééééé"])("rejects unauthenticated callbacks before publication %s",async (secret) => {diff --cc apps/web/__tests__/unit/video-edit-published-output.test.tsindex 000000000,39099e4ea..7a58870b2mode 000000,100644..100644--- a/apps/web/__tests__/unit/video-edit-published-output.test.ts+++ b/apps/web/__tests__/unit/video-edit-published-output.test.ts@@@ -1,0 -1,67 +1,83 @@@+ import {+ getPublishedRecordingCopyKeys,+ getPublishedRecordingOutputKey,+ resolveRecordingObjectKey,+ } from "@cap/web-backend/src/Storage/recording-output";+ import { describe, expect, it } from "vitest";++ const prefix = "owner/video/";+ const editPrefix = `${prefix}.recording/outputs/edit-11111111-1111-4111-8111-111111111111/`;++ describe.each(["desktopMP4", "webMP4"])("published %s edit output", (type) => {+ const video = {+ id: "video",+ ownerId: "owner",+ source: {+ type,+ outputKey: `${editPrefix}result.mp4`,+ thumbnailKey: `${editPrefix}thumbnail.jpg`,+ previewKey: `${editPrefix}preview.gif`,+ },+ };+ it("resolves playback, thumbnails, previews and duplication to the current edit", () => {+ expect(getPublishedRecordingOutputKey(video)).toBe(+ `${editPrefix}result.mp4`,+ );+ expect(resolveRecordingObjectKey(video, `${prefix}result.mp4`)).toBe(+ `${editPrefix}result.mp4`,+ );+ expect(+ resolveRecordingObjectKey(+ video,+ `${prefix}screenshot/screen-capture.jpg`,+ ),+ ).toBe(`${editPrefix}thumbnail.jpg`);+ expect(+ resolveRecordingObjectKey(video, `${prefix}preview/animated-preview.gif`),+ ).toBe(`${editPrefix}preview.gif`);+ expect(getPublishedRecordingCopyKeys(video)).toEqual([+ `${prefix}result.mp4`,+ `${prefix}screenshot/screen-capture.jpg`,+ `${prefix}preview/animated-preview.gif`,+ ]);+ });++ it("ignores an audio derivative from before the current edit", () => {++ const stale = {++ ...video,++ source: {++ ...video.source,++ audioLevelSourceKey:++ type === "webMP4"++ ? `${prefix}result.mp4`++ : `${prefix}.recording/outputs/generation/attempt.mp4`,++ audioLevelOutputKey: `${prefix}.recording/outputs/audio-quality-v3/old.mp4`,++ },++ };++ expect(resolveRecordingObjectKey(stale, `${prefix}result.mp4`)).toBe(++ `${editPrefix}result.mp4`,++ );++ });+ it("preserves original source reads", () => {+ const original = `${prefix}source/original.mp4`;+ expect(resolveRecordingObjectKey(video, original)).toBe(original);+ });+ it("rejects another recording's output and asset pointers", () => {+ const foreign = {+ ...video,+ source: {+ type,+ outputKey: "other/video/.recording/outputs/x/result.mp4",+ thumbnailKey: "other/video/.recording/outputs/x/thumbnail.jpg",+ },+ };+ expect(resolveRecordingObjectKey(foreign, `${prefix}result.mp4`)).toBe(+ `${prefix}result.mp4`,+ );+ expect(+ resolveRecordingObjectKey(+ foreign,+ `${prefix}screenshot/screen-capture.jpg`,+ ),+ ).toBe(`${prefix}screenshot/screen-capture.jpg`);+ });+ });diff --cc apps/web/app/api/storage/object/route.tsindex 8572f092a,d20d974c6..b529129d8--- a/apps/web/app/api/storage/object/route.ts+++ b/apps/web/app/api/storage/object/route.ts@@@ -165,13 -165,13 +165,14 @@@ export async function GET(request: NextisInternalRecordingKey(key) &&!(tokenPayload?.videoId === videoIdParam && tokenPayload.key === key) &&!(- (video.source.type === "desktopMP4" ||+ key === Video.getAudioLevelOutputKey(video) ||- (video.source.type === "desktopMP4" &&++ ((video.source.type === "desktopMP4" ||+ video.source.type === "webMP4") &&- [- key === video.source.outputKey,- key === video.source.thumbnailKey,- key === video.source.previewKey,- ].some(Boolean)+ [+ key === video.source.outputKey,+ key === video.source.thumbnailKey,+ key === video.source.previewKey,+ ].some(Boolean)))) {return yield* Effect.fail("not-found" as const);diff --cc apps/web/app/api/webhooks/media-server/progress/route.tsindex cbf7a9510,8f4036bb6..9e4a7bf82--- a/apps/web/app/api/webhooks/media-server/progress/route.ts+++ b/apps/web/app/api/webhooks/media-server/progress/route.ts@@@ -101,15 -101,16 +102,24 @@@ export async function POST(request: Nexreturn 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;+ if (+ await applyEditProgress(+ payload,+ request.nextUrl.searchParams.get("editOperation"),+ request.nextUrl.searchParams.get("editStartedAt"),+ )+ ) {+ return NextResponse.json({ success: true });+ }const recordingProgress = await applyDesktopRecordingProgress(payload);if (recordingProgress.handled) {if (recordingProgress.published) {diff --cc apps/web/lib/audio-level-publication.tsindex 0cdce755e,000000000..c9240cc2fmode 100644,000000..100644--- a/apps/web/lib/audio-level-publication.ts+++ b/apps/web/lib/audio-level-publication.ts@@@ -1,282 -1,0 +1,285 @@@+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(-55).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,++ if (video.source.type === "desktopMP4" || video.source.type === "webMP4")++ return (++ Video.getRetainedRecordingOutputKey(++ video.ownerId,++ video.id,++ video.source.outputKey,++ ) ??++ (video.source.type === "webMP4"++ ? `${video.ownerId}/${video.id}/result.mp4`++ : undefined)+ );+}++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;+ const maximumGain = Math.min(+ 28,+ Math.max(12, -22 - result.inputLufs),+ -16 - result.inputLufs,+ );+ if (+ result.outputLufs < result.inputLufs + 0.5 ||+ result.outputLufs > result.inputLufs + maximumGain + 0.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),+ ]);+ // The authenticated worker hashes stored bytes with If-Match; retain that verified identity without another download.+ 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 --cc apps/web/workflows/edit-video.tsindex 6bc9e5241,b1e81d633..1f182eb50--- a/apps/web/workflows/edit-video.ts+++ b/apps/web/workflows/edit-video.ts@@@ -844,54 -815,50 +815,54 @@@ export async function saveEditResultAnd);}- await db().transaction(async (tx) => {- await retireDesktopRecordingJobForOutputReplacement(tx, {- videoId: video.id,- userId: video.ownerId,- });- const [lockedVideo] = await tx- .select()- .from(videos)- .where(eq(videos.id, video.id))- .for("update");- if (- !lockedVideo ||- lockedVideo.ownerId !== video.ownerId ||- lockedVideo.bucket !== video.bucket ||- lockedVideo.storageIntegrationId !== video.storageIntegrationId- ) {- throw new Error("Recording storage changed while the edit was rendering");- }- const nextMetadata = clearAiMetadata(lockedVideo.metadata);- delete nextMetadata.desktopRecordingUpload;- await tx- .update(videos)- .set({- width: metadata.width,- height: metadata.height,- fps: metadata.fps,- metadata: nextMetadata,- ...(lockedVideo.source.type === "desktopMP4" ||- lockedVideo.source.type === "webMP4"- ? { source: { type: lockedVideo.source.type } }- : {}),- // Derivable captions keep the transcription COMPLETE; only legacy- // videos without a stored word transcript get re-transcribed.- ...(originalTranscript ? {} : { transcriptionStatus: null }),- ...(duration === undefined ? {} : { duration }),- })- .where(eq(videos.id, videoId as Video.VideoId));+ await withEditOperation(+ videoId,+ sourceKey,+ operation,+ async (tx, lockedVideo, upload, state) => {+ if (upload.phase !== "complete")+ throw new FatalError("Edit output is not complete");+ if (state.resultCommitted) return;+ await retireDesktopRecordingJobForOutputReplacement(tx, {+ videoId: video.id,+ userId: video.ownerId,+ });+ const source = {+ ...lockedVideo.source,+ ...getEditOutputKeys(lockedVideo.ownerId, videoId, operation),+ };++ if (source.type === "desktopMP4" || source.type === "webMP4") {++ delete source.audioLevelSourceKey;++ delete source.audioLevelOutputKey;++ }+ const nextMetadata = clearAiMetadata(lockedVideo.metadata);+ delete nextMetadata.desktopRecordingUpload;+ await tx+ .update(videos)+ .set({+ source,+ width: metadata.width,+ height: metadata.height,+ fps: metadata.fps,+ metadata: {+ ...nextMetadata,+ editProcessing: {+ ...state,+ source: JSON.stringify(source),+ resultCommitted: true,+ },+ },+ // Derivable captions keep the transcription COMPLETE; only legacy+ // videos without a stored word transcript get re-transcribed.+ ...(originalTranscript ? {} : { transcriptionStatus: null }),+ ...(duration === undefined ? {} : { duration }),+ })+ .where(eq(videos.id, videoId as Video.VideoId));- await tx- .insert(videoEdits)- .values({- videoId: videoId as Video.VideoId,- sourceKey,- editSpec,- updatedAt: new Date(),- })- .onDuplicateKeyUpdate({- set: {+ await tx+ .insert(videoEdits)+ .values({+ videoId: videoId as Video.VideoId,sourceKey,editSpec,updatedAt: new Date(),diff --cc packages/database/schema.tsindex 443f1149d,4d66fc0f5..0021f914d--- a/packages/database/schema.ts+++ b/packages/database/schema.ts@@@ -435,8 -433,9 +435,11 @@@ export const videos = mysqlTable| { type: "desktopSegments" }| {type: "webMP4";+ outputKey?: string;+ thumbnailKey?: string;+ previewKey?: string;+ audioLevelOutputKey?: string;+ audioLevelSourceKey?: string;}>().notNull()diff --cc packages/web-domain/src/Video.tsindex 0ddb4d568,e6f6e0fb8..c47acdeb0--- a/packages/web-domain/src/Video.ts+++ b/packages/web-domain/src/Video.ts@@@ -163,42 -161,6 +163,39 @@@ export function getRetainedRecordingOutreturn key;}+export function getAudioLevelOutputKey(video: {+ id: string;+ ownerId: string;+ source: {+ type: string;+ outputKey?: string;+ audioLevelSourceKey?: string;+ audioLevelOutputKey?: string;+ };+}) {+ const { source } = video;+ const originalKey =- source.type === "webMP4"++ getRetainedRecordingOutputKey(video.ownerId, video.id, source.outputKey) ??++ (source.type === "webMP4"+ ? `${video.ownerId}/${video.id}/result.mp4`- : getRetainedRecordingOutputKey(- video.ownerId,- video.id,- source.outputKey,- );++ : undefined);+ const key = getRetainedRecordingOutputKey(+ video.ownerId,+ video.id,+ source.audioLevelOutputKey,+ );+ if (+ !["desktopMP4", "webMP4"].includes(source.type) ||+ !originalKey ||+ source.audioLevelSourceKey !== originalKey ||+ !key?.startsWith(+ `${video.ownerId}/${video.id}/.recording/outputs/audio-quality-v3/`,+ )+ )+ return undefined;+ return key;+}+export class Mp4Source extends Schema.TaggedClass<Mp4Source>()("Mp4Source", {videoId: Schema.String,ownerId: Schema.String,