Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: preserve fragmented recording timing during processing
Richie McIlroy434bd5e1bcc7
diff --git a/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.tsindex b25e5b66a..74de1729c 100644--- a/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts+++ b/apps/media-server/src/__tests__/lib/recording-verification.integration.test.ts@@ -1,4 +1,4 @@-import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";import { createHash } from "node:crypto";import {mkdtemp,@@ -10,7 +10,12 @@ import {} from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";+import { EncodedPacketSink, FilePathSource, Input, MP4 } from "mediabunny";import { muxMediaTracksToMp4 } from "../../lib/media-video";+import {+ RecordingTimingError,+ readRecordingVideoTiming,+} from "../../lib/recording-timing";import {inspectRecordingSources,isRetryableRecordingVerificationError,@@ -29,6 +34,8 @@ let audioGap: string;let variableFrameRate: string;let silentBytes: Uint8Array<ArrayBuffer>;let corruptBytes: Uint8Array<ArrayBuffer>;+let fragmentInit: Buffer;+let videoFragments: Buffer[];async function run(command: string[]): Promise<string> {const proc = Bun.spawn(command, { stdout: "pipe", stderr: "pipe" });@@ -69,6 +76,117 @@ async function generate(path: string, audio: string, filters: string[] = []) {]);}+function visitFragmentBoxes(+ bytes: Buffer,+ visit: (type: string, offset: number) => void,+ start = 0,+ end = bytes.length,+): void {+ for (let offset = start; offset + 8 <= end; ) {+ const size = bytes.readUInt32BE(offset);+ const type = bytes.toString("ascii", offset + 4, offset + 8);+ if (size < 8 || offset + size > end) {+ throw new Error("Invalid fragmented fixture box");+ }+ if (type === "moof" || type === "traf") {+ visitFragmentBoxes(bytes, visit, offset + 8, offset + size);+ } else {+ visit(type, offset);+ }+ offset += size;+ }+}++function shiftFragmentClocks(bytes: Buffer, offsetTicks: number): void {+ visitFragmentBoxes(bytes, (type, offset) => {+ if (type !== "sidx" && type !== "tfdt") return;+ const version = bytes[offset + 8];+ const position = offset + (type === "tfdt" ? 12 : 20);+ if (version === 1) {+ bytes.writeBigUInt64BE(+ bytes.readBigUInt64BE(position) + BigInt(offsetTicks),+ position,+ );+ } else if (version === 0) {+ bytes.writeUInt32BE(bytes.readUInt32BE(position) + offsetTicks, position);+ } else {+ throw new Error("Unsupported fragmented fixture clock");+ }+ });+}++function changeLastFragmentSampleDuration(bytes: Buffer, offsetTicks: number) {+ let changed = false;+ visitFragmentBoxes(bytes, (type, offset) => {+ if (type !== "trun") return;+ const flags = bytes.readUIntBE(offset + 9, 3);+ const sampleCount = bytes.readUInt32BE(offset + 12);+ if (!(flags & 0x100) || sampleCount === 0) {+ throw new Error("Fragmented fixture has no per-sample durations");+ }+ const sampleSize =+ [0x100, 0x200, 0x400, 0x800].filter((flag) => flags & flag).length * 4;+ const position =+ offset ++ 16 ++ (flags & 1 ? 4 : 0) ++ (flags & 4 ? 4 : 0) ++ (sampleCount - 1) * sampleSize;+ bytes.writeUInt32BE(bytes.readUInt32BE(position) + offsetTicks, position);+ changed = true;+ });+ if (!changed) throw new Error("Fragmented fixture has no sample run");+}++async function fragmentedSource(+ offsetTicks: number,+ durationOffsets: { first?: number; last?: number } = {},+): Promise<string> {+ const input = join(+ directory,+ `fragmented-${offsetTicks}-${durationOffsets.first ?? 0}-${durationOffsets.last ?? 0}.mp4`,+ );+ const fragments = videoFragments.map((fragment, index) => {+ const bytes = Buffer.from(fragment);+ if (index > 0) shiftFragmentClocks(bytes, offsetTicks);+ if (index === 0 && durationOffsets.first) {+ changeLastFragmentSampleDuration(bytes, durationOffsets.first);+ }+ if (index === videoFragments.length - 1 && durationOffsets.last) {+ changeLastFragmentSampleDuration(bytes, durationOffsets.last);+ }+ return bytes;+ });+ await writeFile(input, Buffer.concat([fragmentInit, ...fragments]));+ return input;+}++async function videoPackets(input: string) {+ const source = new Input({+ formats: [MP4],+ source: new FilePathSource(input),+ });+ try {+ const [track] = await source.getVideoTracks();+ if (!track) throw new Error("Fixture has no video track");+ const resolution = await track.getTimeResolution();+ const sink = new EncodedPacketSink(track);+ const packets: { pts: number; duration: number }[] = [];+ for await (const packet of sink.packets(undefined, undefined, {+ metadataOnly: true,+ skipLiveWait: true,+ })) {+ packets.push({+ pts: Math.round(packet.timestamp * resolution),+ duration: Math.round(packet.duration * resolution),+ });+ }+ return packets;+ } finally {+ source.dispose();+ }+}+beforeAll(async () => {directory = await mkdtemp(join(tmpdir(), "cap-recording-verification-"));silent = join(directory, "silent.mp4");@@ -94,6 +212,57 @@ beforeAll(async () => {"-video_track_timescale","90000",]);+ const fragmentDirectory = await mkdtemp(join(directory, "dash-"));+ await run([+ "ffmpeg",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "testsrc2=size=160x90:rate=30",+ "-frames:v",+ "31",+ "-fps_mode",+ "passthrough",+ "-enc_time_base:v",+ "1:1000000",+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-bf",+ "0",+ "-g",+ "6",+ "-pix_fmt",+ "yuv420p",+ "-threads",+ "1",+ "-f",+ "dash",+ "-seg_duration",+ "0.4",+ "-use_template",+ "1",+ "-use_timeline",+ "1",+ "-init_seg_name",+ "init.mp4",+ "-media_seg_name",+ "fragment-$Number%05d$.m4s",+ join(fragmentDirectory, "manifest.mpd"),+ ]);+ fragmentInit = await readFile(join(fragmentDirectory, "init.mp4"));+ const fragmentNames = (await readdir(fragmentDirectory))+ .filter((name) => /^fragment-\d+\.m4s$/.test(name))+ .sort();+ if (fragmentNames.length !== 3) {+ throw new Error("Fragmented fixture must have three video segments");+ }+ videoFragments = await Promise.all(+ fragmentNames.map((name) => readFile(join(fragmentDirectory, name))),+ );silentBytes = new Uint8Array(await readFile(silent));const packets: {packets: { pos: string; size: string; pts_time: string }[];@@ -246,6 +415,308 @@ describe("complete recording decode", () => {});describe("source-preserving recording mux", () => {+ test.each([-1, 1, 100_000])(+ "preserves fragment boundary clock offsets of %d microseconds",+ async (offsetTicks) => {+ const input = await fragmentedSource(offsetTicks);+ const sourceEvidence = await inspectRecordingSources(input, null);+ const output = join(directory, `preserved-fragmented-${offsetTicks}.mp4`);+ await muxMediaTracksToMp4(input, null, output);+ const [sourcePackets, outputPackets] = await Promise.all([+ videoPackets(input),+ videoPackets(output),+ ]);+ const sourceBoundary = sourcePackets[11];+ const outputBoundary = outputPackets[11];+ if (!sourceBoundary || !outputBoundary) {+ throw new Error("Fragmented fixture has no boundary packet");+ }+ expect(outputPackets.map((packet) => packet.pts)).toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ expect(outputBoundary.duration).toBe(+ sourceBoundary.duration + offsetTicks,+ );+ const verified = await verifyRecording(output, {+ requireAudio: false,+ sourceEvidence,+ });+ expect(verified.sourcePreserved).toBe(true);+ expect(verified.video).toEqual(sourceEvidence.video);+ expect(verified.integrity).toEqual(sourceEvidence.integrity);+ },+ );++ test.each([-1, 1, -23_333])(+ "preserves a true partial final frame with duration offset %d ticks when muxing",+ async (offsetTicks) => {+ const input = await fragmentedSource(0, { last: offsetTicks });+ const sourceEvidence = await inspectRecordingSources(input, null);+ const output = join(+ directory,+ `preserved-partial-tail-${offsetTicks}.mp4`,+ );+ await muxMediaTracksToMp4(input, null, output);+ const [sourcePackets, outputPackets] = await Promise.all([+ videoPackets(input),+ videoPackets(output),+ ]);+ expect(outputPackets.map((packet) => packet.pts)).toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ const sourceTail = sourcePackets.at(-1);+ const outputTail = outputPackets.at(-1);+ if (!sourceTail || !outputTail)+ throw new Error("Fixture has no final packet");+ expect(sourceTail.duration).toBe(33_333 + offsetTicks);+ expect(outputTail.duration).toBe(sourceTail.duration);+ const verified = await verifyRecording(output, {+ requireAudio: false,+ sourceEvidence,+ });+ expect(verified.sourcePreserved).toBe(true);+ expect(verified.video.frameCount).toBe(31);+ expect(verified.integrity).toEqual(sourceEvidence.integrity);+ },+ );++ test.each(["dropped-frame", "retimed-frame", "shortened-tail"])(+ "rejects a real %s change in a fully decodable fragmented recording",+ async (damage) => {+ const input = await fragmentedSource(0);+ const sourceEvidence = await inspectRecordingSources(input, null);+ const output = join(directory, `fragmented-${damage}.mp4`);+ const modification =+ damage === "dropped-frame"+ ? ["-frames:v", "30"]+ : [+ "-bsf:v",+ damage === "retimed-frame"+ ? "setts=ts=TS+if(eq(N\\,15)\\,1000\\,0)"+ : "setts=duration=if(eq(N\\,30)\\,10000\\,DURATION)",+ ];+ await run([+ "ffmpeg",+ "-v",+ "error",+ "-copyts",+ "-i",+ input,+ "-map",+ "0:v:0",+ "-c:v",+ "copy",+ "-an",+ "-movie_timescale",+ "1000000",+ ...modification,+ output,+ ]);+ const outputEvidence = await inspectRecordingSources(output, null);+ if (damage === "dropped-frame") {+ expect(outputEvidence.video.frameCount).toBe(+ sourceEvidence.video.frameCount - 1,+ );+ } else {+ expect(outputEvidence.video.frameCount).toBe(+ sourceEvidence.video.frameCount,+ );+ expect(outputEvidence.integrity.video.contentSha256).toBe(+ sourceEvidence.integrity.video.contentSha256,+ );+ const [sourcePackets, outputPackets] = await Promise.all([+ videoPackets(input),+ videoPackets(output),+ ]);+ if (damage === "retimed-frame") {+ expect(outputEvidence.video.endTime).toBe(+ sourceEvidence.video.endTime,+ );+ expect(outputPackets.map((packet) => packet.pts)).not.toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ } else {+ expect(outputPackets.map((packet) => packet.pts)).toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ expect(outputEvidence.video.endTime).toBeLessThan(+ sourceEvidence.video.endTime,+ );+ }+ }+ await expect(+ verifyRecording(output, { requireAudio: false, sourceEvidence }),+ ).rejects.toThrow(+ damage === "dropped-frame"+ ? "does not preserve source video: frame count"+ : "does not preserve source video: presentation timeline",+ );+ },+ );++ test("preserves sub-frame timestamps after a two-hour absolute clock shift", async () => {+ const original = await fragmentedSource(0);+ const input = join(directory, "fractional-timestamps.mp4");+ await run([+ "ffmpeg",+ "-v",+ "error",+ "-copyts",+ "-i",+ original,+ "-map",+ "0:v:0",+ "-c:v",+ "copy",+ "-an",+ "-bsf:v",+ "setts=ts=if(eq(N\\,1)\\,586\\,TS)",+ "-video_track_timescale",+ "15360",+ "-movie_timescale",+ "1000000",+ input,+ ]);+ const output = join(directory, "shifted-fractional-timestamps.mp4");+ await run([+ "ffmpeg",+ "-v",+ "error",+ "-copyts",+ "-itsoffset",+ "7200",+ "-i",+ input,+ "-map",+ "0:v:0",+ "-c:v",+ "copy",+ "-an",+ "-video_track_timescale",+ "15360",+ "-movie_timescale",+ "1000000",+ "-avoid_negative_ts",+ "disabled",+ output,+ ]);+ const sourceEvidence = await inspectRecordingSources(input, null);+ const [sourcePackets, outputPackets] = await Promise.all([+ videoPackets(input),+ videoPackets(output),+ ]);+ expect(sourcePackets[1]?.pts).toBe(9);+ expect(outputPackets.map((packet) => packet.pts - 7_200 * 15_360)).toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ const verified = await verifyRecording(output, {+ requireAudio: false,+ sourceEvidence,+ });+ expect(verified.sourcePreserved).toBe(true);+ expect(verified.integrity).toEqual(sourceEvidence.integrity);+ expect(verified.video.duration).toBeCloseTo(+ sourceEvidence.video.duration,+ 6,+ );+ });++ test.each([-1, 1])(+ "rejects a %d tick final-duration change without changed frames or PTS",+ async (offsetTicks) => {+ const input = await fragmentedSource(0);+ const output = await fragmentedSource(0, { last: offsetTicks });+ const sourceEvidence = await inspectRecordingSources(input, null);+ const outputEvidence = await inspectRecordingSources(output, null);+ expect(outputEvidence.video.frameCount).toBe(+ sourceEvidence.video.frameCount,+ );+ expect(outputEvidence.integrity.video.contentSha256).toBe(+ sourceEvidence.integrity.video.contentSha256,+ );+ const [sourcePackets, outputPackets] = await Promise.all([+ videoPackets(input),+ videoPackets(output),+ ]);+ expect(outputPackets.map((packet) => packet.pts)).toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ const sourceTail = sourcePackets.at(-1);+ const outputTail = outputPackets.at(-1);+ if (!sourceTail || !outputTail)+ throw new Error("Fixture has no final packet");+ expect(outputTail.duration).toBe(sourceTail.duration + offsetTicks);+ await expect(+ verifyRecording(output, { requireAudio: false, sourceEvidence }),+ ).rejects.toThrow(+ "does not preserve source video: presentation timeline",+ );+ },+ );++ test("rejects a shortened final frame hidden by an earlier fragment's endpoint", async () => {+ const input = await fragmentedSource(0, { first: 2_000_000 });+ const output = await fragmentedSource(0, { first: 2_000_000, last: -1 });+ const sourceEvidence = await inspectRecordingSources(input, null);+ const outputEvidence = await inspectRecordingSources(output, null);+ expect(outputEvidence.video).toEqual(sourceEvidence.video);+ expect(outputEvidence.integrity.video.contentSha256).toBe(+ sourceEvidence.integrity.video.contentSha256,+ );+ const [sourcePackets, outputPackets] = await Promise.all([+ videoPackets(input),+ videoPackets(output),+ ]);+ expect(outputPackets.map((packet) => packet.pts)).toEqual(+ sourcePackets.map((packet) => packet.pts),+ );+ const sourceTail = sourcePackets.at(-1);+ const outputTail = outputPackets.at(-1);+ if (!sourceTail || !outputTail)+ throw new Error("Fixture has no final packet");+ expect(outputTail.duration).toBe(sourceTail.duration - 1);+ await expect(+ verifyRecording(output, { requireAudio: false, sourceEvidence }),+ ).rejects.toThrow("does not preserve source video: presentation timeline");+ });++ test("preserves presentation order and terminal duration for real B-frames", async () => {+ const input = join(directory, "b-frame-source.mp4");+ await generate(input, "anullsrc=r=48000:cl=mono:d=5", [+ "-bf",+ "2",+ "-g",+ "30",+ "-video_track_timescale",+ "90000",+ ]);+ const probe: { streams: { has_b_frames: number }[] } = JSON.parse(+ await run([+ "ffprobe",+ "-v",+ "error",+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=has_b_frames",+ "-of",+ "json",+ input,+ ]),+ );+ expect(probe.streams[0]?.has_b_frames).toBeGreaterThan(0);+ const sourceEvidence = await inspectRecordingSources(input, input);+ const output = join(directory, "b-frame-output.mp4");+ await muxMediaTracksToMp4(input, input, output);+ const verified = await verifyRecording(output, {+ requireAudio: true,+ sourceEvidence,+ });+ expect(verified.sourcePreserved).toBe(true);+ expect(verified.video.frameCount).toBe(150);+ expect(verified.integrity).toEqual(sourceEvidence.integrity);+ });+test("preserves sparse screenshot timestamps without inventing missing frames", async () => {const input = join(directory, "sparse-video.mp4");await generate(input, "anullsrc=r=48000:cl=mono:d=5", [@@ -442,7 +913,7 @@ describe("source-preserving recording mux", () => {]);await expect(verifyRecording(reversed, { requireAudio: true, sourceEvidence }),- ).rejects.toThrow("does not preserve source video");+ ).rejects.toThrow("does not preserve source video: decoded content");const changedAudio = join(directory, "changed-audio.mp4");await run(["ffmpeg",@@ -521,6 +992,141 @@ function expectExited(pid: number) {expect(() => process.kill(pid, 0)).toThrow();}+describe("recording timing metadata lifetime", () => {+ test.each(["pre-format", "post-format"])(+ "joins a cancelled %s metadata read without leaking a rejected read",+ async (stage) => {+ const identity = '"metadata-cancellation"';+ const getFormat = Input.prototype.getFormat;+ let formatReady = false;+ const format = spyOn(Input.prototype, "getFormat").mockImplementation(+ async function (this: Input) {+ const result = await getFormat.call(this);+ formatReady = true;+ return result;+ },+ );+ let started: (() => void) | undefined;+ const request = new Promise<void>((resolve) => {+ started = resolve;+ });+ let stopped: (() => void) | undefined;+ const closed = new Promise<void>((resolve) => {+ stopped = resolve;+ });+ const requests: Request[] = [];+ const server = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ fetch(request) {+ requests.push(request);+ const range = request.headers+ .get("range")+ ?.match(/^bytes=(\d+)-(\d+)$/);+ if (!range) throw new Error("Metadata request has no bounded range");+ const start = Number(range[1]);+ const end = Number(range[2]) + 1;+ const body = silentBytes.subarray(start, end);+ const stalled = stage === "pre-format" || formatReady;+ return new Response(+ stalled+ ? new ReadableStream({+ start(controller) {+ controller.enqueue(body.subarray(0, 1));+ started?.();+ },+ cancel() {+ stopped?.();+ },+ })+ : body,+ {+ status: 206,+ headers: {+ ETag: identity,+ "Content-Length": String(end - start),+ "Content-Range": `bytes ${start}-${end - 1}/${silentBytes.length}`,+ },+ },+ );+ },+ });+ const controller = new AbortController();+ try {+ const outcome = readRecordingVideoTiming(+ `http://127.0.0.1:${server.port}/recording.mp4?signature=private-value`,+ {+ timeoutMs: 5_000,+ abortSignal: controller.signal,+ remoteObject: {+ objectIdentity: identity,+ fileSize: silentBytes.length,+ },+ },+ ).catch((error: unknown) => error);+ await request;+ await new Promise<void>((resolve) => setImmediate(resolve));+ controller.abort();+ const error = await outcome;+ expect(error).toBeInstanceOf(RecordingTimingError);+ if (!(error instanceof RecordingTimingError)) {+ throw new Error("Cancelled metadata read unexpectedly succeeded");+ }+ expect(error.message).toContain("cancelled");+ expect(error.message).not.toContain("private-value");+ expect(error.retryable).toBe(false);+ expect(formatReady).toBe(stage === "post-format");+ await closed;+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(requests.length).toBeGreaterThan(0);+ for (const request of requests) {+ expect(request.headers.get("if-match")).toBe(identity);+ }+ } finally {+ controller.abort();+ await server.stop(true);+ format.mockRestore();+ }+ },+ 10_000,+ );++ test.each([412, 503])(+ "classifies metadata HTTP %d failures without exposing provider details",+ async (status) => {+ const server = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ fetch() {+ return new Response("Synthetic provider failure", { status });+ },+ });+ try {+ const error = await readRecordingVideoTiming(+ `http://127.0.0.1:${server.port}/recording.mp4?signature=private-value`,+ {+ timeoutMs: 1_000,+ remoteObject: {+ objectIdentity: '"metadata-failure"',+ fileSize: silentBytes.length,+ },+ },+ ).catch((error: unknown) => error);+ expect(error).toBeInstanceOf(RecordingTimingError);+ if (!(error instanceof RecordingTimingError)) {+ throw new Error("Failed metadata request unexpectedly succeeded");+ }+ expect(error.message).toContain(`HTTP ${status}`);+ expect(error.message).not.toContain("private-value");+ expect(error.retryable).toBe(status === 503);+ await new Promise<void>((resolve) => setImmediate(resolve));+ } finally {+ await server.stop(true);+ }+ },+ );+});+describe("recording verification lifetime", () => {test("does not start work for an already cancelled request", async () => {const controller = new AbortController();diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.tsindex ef4722439..0662e8c84 100644--- a/apps/media-server/src/lib/media-video.ts+++ b/apps/media-server/src/lib/media-video.ts@@ -11,6 +11,10 @@ import {withTimeout,} from "./media-common";import { probeVideoFile } from "./media-probe";+import {+ RecordingTimingError,+ readRecordingVideoTiming,+} from "./recording-timing";import { registerSubprocess, terminateProcess } from "./subprocess";import {createTempFile,@@ -989,6 +993,7 @@ async function runFfmpegCommand(timeoutMs: number,abortSignal?: AbortSignal,): Promise<void> {+ if (abortSignal?.aborted) throw new Error("Video processing was cancelled");const proc = registerSubprocess(spawn({cmd: args,@@ -1005,6 +1010,7 @@ async function runFfmpegCommand(}try {+ if (abortSignal?.aborted) throw new Error("Video processing was cancelled");await withTimeout((async () => {void drainStream(proc.stdout as ReadableStream<Uint8Array>);@@ -2402,6 +2408,15 @@ export async function muxMediaTracksToMp4(abortSignal?: AbortSignal,): Promise<void> {if (abortSignal?.aborted) throw new Error("Recording mux was cancelled");+ const startedAt = performance.now();+ const timing = await readRecordingVideoTiming(videoInputPath, {+ abortSignal,+ timeoutMs: PROCESS_TIMEOUT_MS,+ });+ if (abortSignal?.aborted) throw new Error("Recording mux was cancelled");+ const lastTimestamp = timing.lastTimestampTicks - timing.firstTimestampTicks;+ // FFmpeg 7 can discard a fragmented MP4's stored final sample duration.+ const videoTimingFilter = `setts=pts=PTS:dts=DTS:duration=if(eq(PTS-STARTPTS\\,${lastTimestamp})\\,${timing.lastDurationTicks}\\,DURATION)`;const args = audioInputPath? ["ffmpeg",@@ -2418,6 +2433,8 @@ export async function muxMediaTracksToMp4("1:a:0","-c","copy",+ "-bsf:v",+ videoTimingFilter,"-avoid_negative_ts","disabled","-movie_timescale",@@ -2437,6 +2454,8 @@ export async function muxMediaTracksToMp4("0:v:0","-c:v","copy",+ "-bsf:v",+ videoTimingFilter,"-an","-avoid_negative_ts","disabled",@@ -2447,5 +2466,9 @@ export async function muxMediaTracksToMp4(outputPath,];- await runFfmpegCommand(args, PROCESS_TIMEOUT_MS, abortSignal);+ const remainingMs = PROCESS_TIMEOUT_MS - (performance.now() - startedAt);+ if (remainingMs <= 0) {+ throw new RecordingTimingError("Recording mux timed out", true);+ }+ await runFfmpegCommand(args, remainingMs, abortSignal);}diff --git a/apps/media-server/src/lib/recording-timing.ts b/apps/media-server/src/lib/recording-timing.tsnew file mode 100644index 000000000..d9be31eb4--- /dev/null+++ b/apps/media-server/src/lib/recording-timing.ts@@ -0,0 +1,476 @@+import { constants } from "node:fs";+import { type FileHandle, open } from "node:fs/promises";+import { isAbsolute } from "node:path";+import {+ EncodedPacketSink,+ Input,+ MP4,+ QTFF,+ type SourceRef,+ StreamSource,+} from "mediabunny";++const MAX_METADATA_BYTES = 64 * 1024 * 1024;+const MAX_RANGE_BYTES = 1024 * 1024;+const MAX_CACHE_BYTES = 8 * 1024 * 1024;++export class RecordingTimingError extends Error {+ constructor(+ message: string,+ readonly retryable: boolean,+ ) {+ super(message);+ this.name = "RecordingTimingError";+ }+}++export interface RecordingVideoTiming {+ timeScale: number;+ firstTimestampTicks: bigint;+ lastTimestampTicks: bigint;+ lastDurationTicks: bigint;+}++interface RecordingTimingOptions {+ timeoutMs: number;+ abortSignal?: AbortSignal;+ remoteObject?: {+ objectIdentity: string;+ fileSize: number;+ };+}++function integerTicks(seconds: number, timeScale: number): bigint {+ const scaled = seconds * timeScale;+ const rounded = Math.round(scaled);+ const tolerance = Math.max(0.0000001, Math.abs(scaled) * Number.EPSILON * 4);+ if (+ !Number.isFinite(seconds) ||+ !Number.isSafeInteger(rounded) ||+ tolerance >= 0.25 ||+ Math.abs(scaled - rounded) > tolerance+ ) {+ throw new RecordingTimingError(+ "Recording video timing is not representable in its timebase",+ false,+ );+ }+ return BigInt(rounded);+}++function localReadError(error: unknown): RecordingTimingError {+ const code =+ typeof error === "object" && error !== null && "code" in error+ ? error.code+ : undefined;+ return new RecordingTimingError(+ "Recording timing file could not be read",+ typeof code === "string" &&+ [+ "EIO",+ "EBUSY",+ "EMFILE",+ "ENFILE",+ "ENOMEM",+ "EAGAIN",+ "ETIMEDOUT",+ ].includes(code),+ );+}++export async function readRecordingVideoTiming(+ path: string,+ options: RecordingTimingOptions,+): Promise<RecordingVideoTiming> {+ if (+ !Number.isSafeInteger(options.timeoutMs) ||+ options.timeoutMs <= 0 ||+ options.timeoutMs > 2_147_483_647+ ) {+ throw new RecordingTimingError("Invalid recording timing budget", false);+ }+ const remote = /^https?:\/\//i.test(path);+ const remoteObject = options.remoteObject;+ if (+ (remote &&+ (!remoteObject ||+ !Number.isSafeInteger(remoteObject.fileSize) ||+ remoteObject.fileSize <= 0 ||+ remoteObject.objectIdentity.length > 1024 ||+ !/^"[\x21\x23-\x7E\x80-\xFF]+"$/.test(remoteObject.objectIdentity))) ||+ (!remote && (!isAbsolute(path) || remoteObject !== undefined))+ ) {+ throw new RecordingTimingError("Invalid recording timing source", false);+ }++ const controller = new AbortController();+ const cancelled = () => {+ controller.abort(+ new RecordingTimingError("Recording timing read was cancelled", false),+ );+ };+ options.abortSignal?.addEventListener("abort", cancelled, { once: true });+ if (options.abortSignal?.aborted) cancelled();+ const timeout = setTimeout(() => {+ controller.abort(+ new RecordingTimingError("Recording timing read timed out", true),+ );+ }, options.timeoutMs);+ const checkActive = () => {+ if (controller.signal.aborted) throw controller.signal.reason;+ };+ let file: FileHandle | undefined;+ let input: Input | undefined;+ let sourceRef: SourceRef<InstanceType<typeof StreamSource>> | undefined;+ let formatReady = false;+ let fileSize = remoteObject?.fileSize ?? 0;+ let initialModification: number | undefined;+ let initialChange: number | undefined;+ let metadataBytes = 0;+ let entireRemoteFile: Uint8Array | undefined;+ let result: RecordingVideoTiming | undefined;+ let failure: RecordingTimingError | undefined;+ const reads = new Set<Promise<Uint8Array>>();+ const reserve = (bytes: number) => {+ metadataBytes += bytes;+ if (+ !Number.isSafeInteger(bytes) ||+ bytes < 0 ||+ metadataBytes > MAX_METADATA_BYTES+ ) {+ throw new RecordingTimingError(+ "Recording timing metadata exceeds its read budget",+ false,+ );+ }+ };++ const boundedBody = async (response: Response, length: number) => {+ const reader = response.body?.getReader();+ if (!reader) {+ throw new RecordingTimingError(+ "Recording timing response has no body",+ false,+ );+ }+ const stop = () => {+ void reader.cancel().catch(() => {});+ };+ controller.signal.addEventListener("abort", stop, { once: true });+ const bytes = new Uint8Array(length);+ let offset = 0;+ try {+ checkActive();+ while (true) {+ const result = await reader.read();+ checkActive();+ if (result.done) break;+ if (result.value.length > length - offset) {+ throw new RecordingTimingError(+ "Recording timing response exceeded its requested range",+ false,+ );+ }+ bytes.set(result.value, offset);+ offset += result.value.length;+ }+ if (offset !== length) {+ throw new RecordingTimingError(+ "Recording timing response was incomplete",+ false,+ );+ }+ return bytes;+ } finally {+ controller.signal.removeEventListener("abort", stop);+ await reader.cancel().catch(() => {});+ reader.releaseLock();+ }+ };++ const readRemoteRange = async (start: number, end: number) => {+ if (!remoteObject) {+ throw new RecordingTimingError(+ "Recording timing object is not pinned",+ false,+ );+ }+ checkActive();+ let response: Response;+ try {+ response = await fetch(path, {+ headers: {+ Range: `bytes=${start}-${end - 1}`,+ "If-Match": remoteObject.objectIdentity,+ "X-Cap-Recording-Verification": "1",+ "Accept-Encoding": "identity",+ },+ signal: controller.signal,+ redirect: "error",+ });+ } catch {+ checkActive();+ throw new RecordingTimingError("Recording timing request failed", true);+ }+ try {+ checkActive();+ if (response.status !== 200 && response.status !== 206) {+ throw new RecordingTimingError(+ `Recording timing request failed: HTTP ${response.status}`,+ response.status === 408 ||+ response.status === 429 ||+ response.status >= 500,+ );+ }+ if (response.headers.get("etag") !== remoteObject.objectIdentity) {+ throw new RecordingTimingError(+ "Recording timing object changed during verification",+ false,+ );+ }+ const encoding = response.headers.get("content-encoding");+ if (encoding && encoding.toLowerCase() !== "identity") {+ throw new RecordingTimingError(+ "Recording timing response changed its byte encoding",+ false,+ );+ }+ const expectedLength = response.status === 200 ? fileSize : end - start;+ const length = response.headers.get("content-length");+ if (+ (response.status === 206 &&+ response.headers.get("content-range") !==+ `bytes ${start}-${end - 1}/${fileSize}`) ||+ (response.status === 200 && fileSize > MAX_CACHE_BYTES) ||+ (length !== null && Number(length) !== expectedLength)+ ) {+ throw new RecordingTimingError(+ "Recording timing response does not match its requested range",+ false,+ );+ }+ if (response.status === 200) reserve(fileSize - (end - start));+ const bytes = await boundedBody(response, expectedLength);+ if (response.status === 200) {+ entireRemoteFile = bytes;+ return bytes.subarray(start, end);+ }+ return bytes;+ } catch (error) {+ checkActive();+ if (error instanceof RecordingTimingError) throw error;+ throw new RecordingTimingError(+ "Recording timing response could not be read",+ true,+ );+ } finally {+ await response.body?.cancel().catch(() => {});+ }+ };++ const readRange = async (start: number, end: number): Promise<Uint8Array> => {+ checkActive();+ if (+ !Number.isSafeInteger(start) ||+ !Number.isSafeInteger(end) ||+ start < 0 ||+ end <= start ||+ end > fileSize+ ) {+ throw new RecordingTimingError(+ "Invalid recording timing byte range",+ false,+ );+ }+ reserve(end - start);+ const result = new Uint8Array(end - start);+ for (let position = start; position < end; ) {+ checkActive();+ const length = Math.min(end - position, MAX_RANGE_BYTES);+ if (remote) {+ const bytes = entireRemoteFile+ ? entireRemoteFile.subarray(position, position + length)+ : await readRemoteRange(position, position + length);+ result.set(bytes, position - start);+ position += bytes.length;+ } else {+ if (!file) {+ throw new RecordingTimingError(+ "Recording timing file is closed",+ false,+ );+ }+ let bytesRead: number;+ try {+ ({ bytesRead } = await file.read(+ result,+ position - start,+ length,+ position,+ ));+ } catch (error) {+ throw localReadError(error);+ }+ if (bytesRead === 0) {+ throw new RecordingTimingError(+ "Recording timing file is incomplete",+ false,+ );+ }+ position += bytesRead;+ }+ }+ checkActive();+ return result;+ };++ try {+ checkActive();+ if (!remote) {+ try {+ file = await open(+ path,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,+ );+ const stat = await file.stat();+ if (+ !stat.isFile() ||+ !Number.isSafeInteger(stat.size) ||+ stat.size <= 0+ ) {+ throw new RecordingTimingError(+ "Recording timing source is not a file",+ false,+ );+ }+ fileSize = stat.size;+ initialModification = stat.mtimeMs;+ initialChange = stat.ctimeMs;+ } catch (error) {+ if (error instanceof RecordingTimingError) throw error;+ throw localReadError(error);+ }+ }+ checkActive();+ sourceRef = new StreamSource({+ getSize: () => {+ checkActive();+ return fileSize;+ },+ read: (start, end) => {+ const task = readRange(start, end);+ reads.add(task);+ void task.then(+ () => reads.delete(task),+ () => reads.delete(task),+ );+ return task;+ },+ maxCacheSize: MAX_CACHE_BYTES,+ prefetchProfile: "none",+ }).ref();+ input = new Input({ formats: [MP4, QTFF], source: sourceRef });+ await input.getFormat();+ formatReady = true;+ const track = (await input.getVideoTracks())[0];+ checkActive();+ if (!track) {+ throw new RecordingTimingError(+ "Recording timing has no video track",+ false,+ );+ }+ const timeScale = await track.getTimeResolution();+ if (!Number.isSafeInteger(timeScale) || timeScale <= 0) {+ throw new RecordingTimingError(+ "Recording video timebase is invalid",+ false,+ );+ }+ const sink = new EncodedPacketSink(track);+ const first = await sink.getFirstPacket({+ metadataOnly: true,+ skipLiveWait: true,+ });+ const last = await sink.getPacket(Infinity, {+ metadataOnly: true,+ skipLiveWait: true,+ });+ checkActive();+ if (!first || !last) {+ throw new RecordingTimingError(+ "Recording video packets are missing",+ false,+ );+ }+ const firstTimestampTicks = integerTicks(first.timestamp, timeScale);+ const lastTimestampTicks = integerTicks(last.timestamp, timeScale);+ const lastDurationTicks = integerTicks(last.duration, timeScale);+ if (lastTimestampTicks < firstTimestampTicks || lastDurationTicks <= 0n) {+ throw new RecordingTimingError(+ "Recording video endpoint is invalid",+ false,+ );+ }+ if (file) {+ const stat = await file.stat();+ checkActive();+ if (+ stat.size !== fileSize ||+ stat.mtimeMs !== initialModification ||+ stat.ctimeMs !== initialChange+ ) {+ throw new RecordingTimingError(+ "Recording timing file changed during verification",+ false,+ );+ }+ }+ result = {+ timeScale,+ firstTimestampTicks,+ lastTimestampTicks,+ lastDurationTicks,+ };+ } catch (error) {+ const reason = controller.signal.aborted ? controller.signal.reason : error;+ failure =+ reason instanceof RecordingTimingError+ ? reason+ : new RecordingTimingError(+ "Recording video timing could not be read",+ false,+ );+ } finally {+ clearTimeout(timeout);+ options.abortSignal?.removeEventListener("abort", cancelled);+ controller.abort(+ new RecordingTimingError("Recording timing read is finished", false),+ );+ // Mediabunny 1.45 leaves pending reads unresolved if disposal precedes their rejection.+ await Promise.allSettled([...reads]);+ try {+ // Its Input.dispose also leaves an unhandled rejection when format detection failed.+ if (formatReady) input?.dispose();+ else sourceRef?.free();+ } catch {+ failure ??= new RecordingTimingError(+ "Recording timing reader could not be closed",+ false,+ );+ }+ try {+ await file?.close();+ } catch {+ failure ??= new RecordingTimingError(+ "Recording timing file could not be closed",+ true,+ );+ }+ }+ if (failure) throw failure;+ if (!result) {+ throw new RecordingTimingError("Recording video timing is missing", false);+ }+ return result;+}diff --git a/apps/media-server/src/lib/recording-verification.ts b/apps/media-server/src/lib/recording-verification.tsindex 7665f3a8b..057b7f292 100644--- a/apps/media-server/src/lib/recording-verification.ts+++ b/apps/media-server/src/lib/recording-verification.ts@@ -4,6 +4,11 @@ import { lstat } from "node:fs/promises";import { isAbsolute } from "node:path";import { spawn } from "bun";import { PROCESS_TIMEOUT_MS } from "./media-common";+import {+ RecordingTimingError,+ type RecordingVideoTiming,+ readRecordingVideoTiming,+} from "./recording-timing";import { registerSubprocess, unregisterSubprocess } from "./subprocess";const MAX_OUTPUT_LINE_LENGTH = 16_384;@@ -21,7 +26,11 @@ class RecordingVerificationError extends Error {}export function isRetryableRecordingVerificationError(error: unknown): boolean {- return error instanceof RecordingVerificationError && error.retryable;+ return (+ (error instanceof RecordingVerificationError ||+ error instanceof RecordingTimingError) &&+ error.retryable+ );}export interface RecordingVerificationOptions {@@ -101,6 +110,11 @@ export interface RemoteRecordingBytesResult {interface DecodedStream {kind?: "video" | "audio";timeBase?: number;+ timeBaseNumerator?: bigint;+ timeBaseDenominator?: bigint;+ firstVideoPts?: bigint;+ lastVideoPts?: bigint;+ lastVideoEndPts?: bigint;sampleRate?: number;frameCount: number;sampleCount: number;@@ -127,6 +141,62 @@ function streamEvidence(stream: DecodedStream): DecodedVideoEvidence {};}+function relativeVideoNanoseconds(+ stream: DecodedStream,+ timestamp: bigint,+): bigint {+ const { firstVideoPts, timeBaseNumerator, timeBaseDenominator } = stream;+ if (+ firstVideoPts === undefined ||+ !timeBaseNumerator ||+ !timeBaseDenominator+ ) {+ throw new Error("Decoded recording frame has no stream metadata");+ }+ const scaled =+ (timestamp - firstVideoPts) * timeBaseNumerator * 1_000_000_000n;+ return (scaled + timeBaseDenominator / 2n) / timeBaseDenominator;+}++function videoTailIntegrity(+ stream: DecodedStream,+ timing: RecordingVideoTiming | undefined,+): string {+ const {+ firstVideoPts,+ lastVideoPts,+ lastVideoEndPts,+ timeBaseNumerator,+ timeBaseDenominator,+ } = stream;+ if (+ firstVideoPts === undefined ||+ lastVideoPts === undefined ||+ lastVideoEndPts === undefined ||+ !timeBaseNumerator ||+ !timeBaseDenominator+ ) {+ throw new Error("Decoded recording video endpoint is missing");+ }+ if (!timing) {+ return `end:${relativeVideoNanoseconds(stream, lastVideoEndPts)}\n`;+ }+ const timeScale = BigInt(timing.timeScale);+ if (+ (timing.lastTimestampTicks - timing.firstTimestampTicks) *+ timeBaseDenominator !==+ (lastVideoPts - firstVideoPts) * timeBaseNumerator * timeScale+ ) {+ throw new Error("Recording container timing does not match decoded video");+ }+ let numerator = timing.lastDurationTicks;+ let denominator = timeScale;+ while (denominator !== 0n) {+ [numerator, denominator] = [denominator, numerator % denominator];+ }+ return `tail:${timing.lastDurationTicks / numerator}/${timeScale / numerator}\n`;+}+function decodeLine(line: string, streams: Map<number, DecodedStream>): void {if (!line) return;const digest = line.match(/^(\d+),(v|a),SHA256=([a-f0-9]{64})$/);@@ -165,6 +235,8 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {throw new Error("Invalid decoded recording timebase");}stream.timeBase = ratio[0] / ratio[1];+ stream.timeBaseNumerator = BigInt(ratio[0]);+ stream.timeBaseDenominator = BigInt(ratio[1]);} else if (metadata[1] === "media_type") {if (metadata[3] !== "video" && metadata[3] !== "audio") {throw new Error("Invalid decoded recording stream type");@@ -211,8 +283,12 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {stream.previousTime = startTime;stream.frameCount++;if (stream.kind === "video") {+ const timestamp = BigInt(pts);+ stream.firstVideoPts ??= timestamp;+ stream.lastVideoPts = timestamp;+ stream.lastVideoEndPts = timestamp + BigInt(ticks);stream.timeline.update(- `${Math.round((startTime - stream.startTime) * 1e9)},${Math.round(duration * 1e9)},${bytes}\n`,+ `${relativeVideoNanoseconds(stream, timestamp)},${bytes}\n`,);}if (stream.kind === "audio") {@@ -290,6 +366,7 @@ function validateEvidence(streams: Map<number, DecodedStream>,options: RecordingVerificationOptions,inspectingSource: boolean,+ videoTiming: RecordingVideoTiming | undefined,): RecordingSourceEvidence {const video = streams.get(0);const audio = streams.get(1);@@ -335,6 +412,11 @@ function validateEvidence(if (!stream.contentSha256) {throw new Error("Decoded recording content digest is missing");}+ if (stream.kind === "video") {+ // Remuxing can change a fragment's nominal packet duration without changing+ // presentation timestamps. FFmpeg 7 can also omit the true final duration.+ stream.timeline.update(videoTailIntegrity(stream, videoTiming));+ }return {contentSha256: stream.contentSha256,timelineSha256: stream.timeline.digest("hex"),@@ -365,11 +447,35 @@ function assertSourcePreserved(a.contentSha256 === b.contentSha256 &&a.timelineSha256 === b.timelineSha256 &&a.format === b.format;- if (- source.video.frameCount !== output.video.frameCount ||- !sameIntegrity(source.integrity.video, output.integrity.video)- ) {- throw new Error("Recording output does not preserve source video");+ const videoMismatches = [+ {+ preserved: source.video.frameCount === output.video.frameCount,+ name: "frame count",+ },+ {+ preserved:+ source.integrity.video.contentSha256 ===+ output.integrity.video.contentSha256,+ name: "decoded content",+ },+ {+ preserved:+ source.integrity.video.timelineSha256 ===+ output.integrity.video.timelineSha256,+ name: "presentation timeline",+ },+ {+ preserved:+ source.integrity.video.format === output.integrity.video.format,+ name: "display format",+ },+ ]+ .filter(({ preserved }) => !preserved)+ .map(({ name }) => name);+ if (videoMismatches.length > 0) {+ throw new Error(+ `Recording output does not preserve source video: ${videoMismatches.join(", ")}`,+ );}if (Boolean(source.audio) !== Boolean(output.audio)) {throw new Error("Recording output does not preserve source audio");@@ -424,6 +530,7 @@ async function decodeRecording(objectIdentity?: string,sourceAudioInput?: string | null,): Promise<RecordingSourceEvidence> {+ const startedAt = performance.now();const timeoutMs = options.timeoutMs ?? PROCESS_TIMEOUT_MS;if ((options.expectedDuration !== undefined &&@@ -463,6 +570,60 @@ async function decodeRecording(if (options.abortSignal?.aborted) {throw new Error("Recording verification was cancelled");}+ let videoTiming: RecordingVideoTiming | undefined;+ if (sourceAudioInput !== undefined || options.sourceEvidence) {+ const deadline = new AbortController();+ const remainingMs = timeoutMs - (performance.now() - startedAt);+ if (remainingMs <= 0) {+ throw new RecordingVerificationError(+ "Recording verification timed out",+ true,+ );+ }+ const timeout = setTimeout(() => deadline.abort(), remainingMs);+ const signal = options.abortSignal+ ? AbortSignal.any([deadline.signal, options.abortSignal])+ : deadline.signal;+ try {+ const remoteObject = remote+ ? await readRemoteIdentity(input, signal, objectIdentity)+ : undefined;+ objectIdentity = remoteObject?.objectIdentity ?? objectIdentity;+ const timingBudgetMs = timeoutMs - (performance.now() - startedAt);+ if (timingBudgetMs <= 0) {+ throw new RecordingVerificationError(+ "Recording verification timed out",+ true,+ );+ }+ videoTiming = await readRecordingVideoTiming(input, {+ remoteObject,+ abortSignal: signal,+ timeoutMs: Math.ceil(timingBudgetMs),+ });+ } catch (error) {+ if (options.abortSignal?.aborted) {+ throw new Error("Recording verification was cancelled");+ }+ if (deadline.signal.aborted) {+ throw new RecordingVerificationError(+ "Recording verification timed out",+ true,+ );+ }+ throw error;+ } finally {+ clearTimeout(timeout);+ deadline.abort();+ }+ }+ const decodeBudgetMs = timeoutMs - (performance.now() - startedAt);+ if (decodeBudgetMs <= 0) {+ throw new RecordingVerificationError(+ "Recording verification timed out",+ true,+ );+ }const proc = registerSubprocess(spawn({cmd: [@@ -552,7 +713,7 @@ async function decodeRecording(true,);stop();- }, timeoutMs);+ }, decodeBudgetMs);const streams = new Map<number, DecodedStream>();const frames = readFrameEvidence(proc.stdout, streams);const errors = readDecoderErrors(proc.stderr, input);@@ -574,7 +735,12 @@ async function decodeRecording(),);}- result = validateEvidence(streams, options, sourceAudioInput !== undefined);+ result = validateEvidence(+ streams,+ options,+ sourceAudioInput !== undefined,+ videoTiming,+ );} finally {clearTimeout(timeout);options.abortSignal?.removeEventListener("abort", cancel);diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.tsindex fa6b05b1d..a5417e08d 100644--- a/apps/media-server/src/routes/video.ts+++ b/apps/media-server/src/routes/video.ts@@ -1677,7 +1677,7 @@ function classifySourceError(error: unknown): RecordingErrorCode {if (/HTTP error 404|Server returned 404/.test(error.message))return "source-missing";if (- /Decoded recording|Invalid decoded recording|Recording has no decoded|does not match the completed local file|Verified recording size/.test(+ /Decoded recording|Invalid decoded recording|Recording has no decoded|Recording video packets are missing|Recording timing has no video track|does not match the completed local file|Verified recording size/.test(error.message,))