Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: verify recordings with tied frame timestamps

Richie McIlroy02db577c2963
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.ts
index 74de1729c..be08d3232 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
@@ -36,6 +36,117 @@ let silentBytes: Uint8Array<ArrayBuffer>;
let corruptBytes: Uint8Array<ArrayBuffer>;
let fragmentInit: Buffer;
let videoFragments: Buffer[];
+let bFrameInit: Buffer;
+let bFrameSamples: VideoSample[];
+
+interface VideoSample {
+ pts: number;
+ dts: number;
+ duration: number;
+ flags: number;
+ data: Buffer;
+}
+
+function mp4Box(type: string, ...payload: Buffer[]): Buffer {
+ const header = Buffer.alloc(8);
+ header.writeUInt32BE(
+ 8 + payload.reduce((size, bytes) => size + bytes.length, 0),
+ );
+ header.write(type, 4, "ascii");
+ return Buffer.concat([header, ...payload]);
+}
+
+function sampleFragment(
+ samples: VideoSample[],
+ sequence: number,
+ durationSource: "trun" | "tfhd" | "trex" = "trun",
+): Buffer {
+ const first = samples[0];
+ if (!first) throw new Error("Fixture fragment is empty");
+ const mfhd = Buffer.alloc(8);
+ mfhd.writeUInt32BE(sequence, 4);
+ const tfhd = Buffer.alloc(durationSource === "tfhd" ? 12 : 8);
+ tfhd.writeUInt32BE(durationSource === "tfhd" ? 0x20008 : 0x20000);
+ tfhd.writeUInt32BE(1, 4);
+ if (durationSource === "tfhd") tfhd.writeUInt32BE(first.duration, 8);
+ const tfdt = Buffer.alloc(12);
+ tfdt.writeUInt32BE(0x1000000);
+ tfdt.writeBigUInt64BE(BigInt(first.dts), 4);
+ const stride = durationSource === "trun" ? 16 : 12;
+ const trun = Buffer.alloc(12 + stride * samples.length);
+ trun.writeUInt32BE(durationSource === "trun" ? 0x1000f01 : 0x1000e01);
+ trun.writeUInt32BE(samples.length, 4);
+ for (const [index, sample] of samples.entries()) {
+ let offset = 12 + index * stride;
+ if (durationSource === "trun") {
+ trun.writeUInt32BE(sample.duration, offset);
+ offset += 4;
+ }
+ trun.writeUInt32BE(sample.data.length, offset);
+ trun.writeUInt32BE(sample.flags, offset + 4);
+ trun.writeInt32BE(sample.pts - sample.dts, offset + 8);
+ }
+ const fragment = () =>
+ mp4Box(
+ "moof",
+ mp4Box("mfhd", mfhd),
+ mp4Box(
+ "traf",
+ mp4Box("tfhd", tfhd),
+ mp4Box("tfdt", tfdt),
+ mp4Box("trun", trun),
+ ),
+ );
+ trun.writeInt32BE(fragment().length + 8, 8);
+ return Buffer.concat([
+ fragment(),
+ mp4Box("mdat", ...samples.map((sample) => sample.data)),
+ ]);
+}
+
+async function tiedTimestampSource(
+ name: string,
+ terminalTies: number,
+ tailChange = 0,
+ swapTailDurations = false,
+): Promise<string> {
+ const samples = bFrameSamples.map((sample) => ({ ...sample }));
+ const interior = samples[13];
+ const next = samples[17];
+ const final = samples[37];
+ const beforeLast = samples[38];
+ const last = samples[39];
+ if (!interior || !next || !final || !beforeLast || !last) {
+ throw new Error("B-frame fixture is incomplete");
+ }
+ interior.pts = next.pts;
+ if (terminalTies > 1) {
+ final.duration = 6000 + tailChange;
+ beforeLast.dts += 3000;
+ beforeLast.pts += 3000;
+ last.dts += 3000;
+ last.pts += 3000;
+ last.duration = 1;
+ if (terminalTies === 3) beforeLast.pts = final.pts;
+ if (swapTailDurations) {
+ [final.duration, last.duration] = [last.duration, final.duration];
+ }
+ }
+ const output = join(directory, name);
+ await writeFile(
+ output,
+ Buffer.concat(
+ tailChange || swapTailDurations
+ ? [
+ bFrameInit,
+ sampleFragment(samples.slice(0, 38), 1),
+ sampleFragment(samples.slice(38), 2),
+ ]
+ : [bFrameInit, sampleFragment(samples, 1)],
+ ),
+ );
+ return output;
+}
async function run(command: string[]): Promise<string> {
const proc = Bun.spawn(command, { stdout: "pipe", stderr: "pipe" });
@@ -88,7 +199,11 @@ function visitFragmentBoxes(
if (size < 8 || offset + size > end) {
throw new Error("Invalid fragmented fixture box");
}
- if (type === "moof" || type === "traf") {
+ if (
+ ["moof", "traf", "moov", "mvex", "trak", "mdia", "minf", "stbl"].includes(
+ type,
+ )
+ ) {
visitFragmentBoxes(bytes, visit, offset + 8, offset + size);
} else {
visit(type, offset);
@@ -195,6 +310,76 @@ beforeAll(async () => {
variableFrameRate = join(directory, "variable-frame-rate.mp4");
corruptTail = join(directory, "corrupt-tail.mp4");
truncatedTail = join(directory, "truncated-tail.mp4");
+ const bFrameSource = join(directory, "b-frame-fragments.mp4");
+ await run([
+ "ffmpeg",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=160x90:rate=30",
+ "-frames:v",
+ "40",
+ "-an",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "fast",
+ "-bf",
+ "2",
+ "-x264-params",
+ "b-adapt=0:b-pyramid=none:scenecut=0:keyint=60:min-keyint=60",
+ "-video_track_timescale",
+ "90000",
+ "-movflags",
+ "empty_moov+frag_keyframe+default_base_moof+delay_moov",
+ bFrameSource,
+ ]);
+ const bFrameBytes = await readFile(bFrameSource);
+ const initBoxes: Buffer[] = [];
+ for (let offset = 0; offset < bFrameBytes.length; ) {
+ const size = bFrameBytes.readUInt32BE(offset);
+ const type = bFrameBytes.toString("ascii", offset + 4, offset + 8);
+ if (type === "ftyp" || type === "moov") {
+ initBoxes.push(bFrameBytes.subarray(offset, offset + size));
+ }
+ if (size < 8) throw new Error("B-frame fixture box is invalid");
+ offset += size;
+ }
+ bFrameInit = Buffer.concat(initBoxes);
+ const bFramePackets: {
+ packets: {
+ pts: number;
+ dts: number;
+ pos: string;
+ size: string;
+ flags: string;
+ }[];
+ } = JSON.parse(
+ await run([
+ "ffprobe",
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "packet=pts,dts,pos,size,flags",
+ "-of",
+ "json",
+ bFrameSource,
+ ]),
+ );
+ bFrameSamples = bFramePackets.packets.map((packet) => ({
+ pts: packet.pts + 3000,
+ dts: packet.dts + 3000,
+ duration: 3000,
+ flags: packet.flags.includes("K") ? 0x2000000 : 0x1010000,
+ data: bFrameBytes.subarray(
+ Number(packet.pos),
+ Number(packet.pos) + Number(packet.size),
+ ),
+ }));
await generate(silent, "anullsrc=r=48000:cl=mono:d=5");
await generate(
shortAudio,
@@ -415,6 +600,248 @@ describe("complete recording decode", () => {
});
describe("source-preserving recording mux", () => {
+ test.each([1, 2])(
+ "preserves interior tied timestamps and %d terminal packets with real B-frames",
+ async (terminalTies) => {
+ const input = await tiedTimestampSource(
+ `tied-${terminalTies}.mp4`,
+ terminalTies,
+ );
+ const sourceEvidence = await inspectRecordingSources(input, silent);
+ const output = join(directory, `tied-${terminalTies}-output.mp4`);
+ await muxMediaTracksToMp4(input, silent, output);
+ const verified = await verifyRecording(output, {
+ requireAudio: true,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.video.frameCount).toBe(40);
+ expect(verified.integrity).toEqual(sourceEvidence.integrity);
+ expect(verified.audio?.sampleCount).toBe(
+ sourceEvidence.audio?.sampleCount,
+ );
+ const sourceTiming = await readRecordingVideoTiming(input, {
+ timeoutMs: 5000,
+ });
+ const outputTiming = await readRecordingVideoTiming(output, {
+ timeoutMs: 5000,
+ });
+ expect(sourceTiming.terminalPacketCount).toBe(terminalTies);
+ expect(outputTiming.terminalPacketSha256).toBe(
+ sourceTiming.terminalPacketSha256,
+ );
+ },
+ );
+
+ test("refuses tied timestamps when the decoder changes their presentation times", async () => {
+ const input = await tiedTimestampSource("tied-three.mp4", 3);
+ const timing = await readRecordingVideoTiming(input, { timeoutMs: 5000 });
+ expect(timing.terminalPacketCount).toBe(3);
+ await expect(inspectRecordingSources(input, null)).rejects.toThrow(
+ "Recording container timing does not match decoded video",
+ );
+ });
+
+ test("keeps standalone verification strict without source-bound timing evidence", async () => {
+ const input = await tiedTimestampSource("standalone-tied.mp4", 1);
+ await expect(
+ verifyRecording(input, { requireAudio: false, expectedDuration: 4 / 3 }),
+ ).rejects.toThrow("Decoded recording timestamps are invalid");
+ });
+
+ test("binds interior container timestamps even when the decoded evidence is unchanged", async () => {
+ const input = await tiedTimestampSource("tied-container-clock.mp4", 1);
+ const sourceEvidence = await inspectRecordingSources(input, null);
+ const originalNext = EncodedPacketSink.prototype.getNextPacket;
+ let calls = 0;
+ const next = spyOn(
+ EncodedPacketSink.prototype,
+ "getNextPacket",
+ ).mockImplementation(async function (
+ this: EncodedPacketSink,
+ ...args: Parameters<typeof originalNext>
+ ) {
+ const packet = await originalNext.apply(this, args);
+ if (packet && ++calls === 17)
+ Object.defineProperty(packet, "timestamp", {
+ value: packet.timestamp + 1 / 90000,
+ });
+ return packet;
+ });
+ let alteredEvidence: Awaited<ReturnType<typeof inspectRecordingSources>>;
+ try {
+ alteredEvidence = await inspectRecordingSources(input, null);
+ } finally {
+ next.mockRestore();
+ }
+ expect(alteredEvidence.video).toEqual(sourceEvidence.video);
+ expect(alteredEvidence.integrity.video.contentSha256).toBe(
+ sourceEvidence.integrity.video.contentSha256,
+ );
+ await expect(
+ verifyRecording(input, {
+ requireAudio: false,
+ sourceEvidence: alteredEvidence,
+ }),
+ ).rejects.toThrow("does not preserve source video: presentation timeline");
+ });
+
+ test.each(["tfhd", "trex"] as const)(
+ "binds tied final packets with %s default durations",
+ async (durationSource) => {
+ const samples = bFrameSamples.map((sample) => ({ ...sample }));
+ samples[39].pts = samples[37].pts;
+ const init = Buffer.from(bFrameInit);
+ visitFragmentBoxes(init, (type, offset) => {
+ if (type === "trex") init.writeUInt32BE(3000, offset + 20);
+ });
+ const input = join(directory, `tied-default-${durationSource}.mp4`);
+ await writeFile(
+ input,
+ Buffer.concat([
+ init,
+ ...samples.map((sample, index) =>
+ sampleFragment([sample], index + 1, durationSource),
+ ),
+ ]),
+ );
+ const sourceEvidence = await inspectRecordingSources(input, null);
+ const output = join(
+ directory,
+ `tied-default-${durationSource}-output.mp4`,
+ );
+ await muxMediaTracksToMp4(input, null, output);
+ const verified = await verifyRecording(output, {
+ requireAudio: false,
+ sourceEvidence,
+ });
+ expect(verified.sourcePreserved).toBe(true);
+ expect(verified.video.frameCount).toBe(40);
+ expect(verified.integrity).toEqual(sourceEvidence.integrity);
+ const invalid = await readFile(input);
+ visitFragmentBoxes(invalid, (type, offset) => {
+ if (durationSource === "trex" && type === "trex")
+ invalid.writeUInt32BE(0, offset + 20);
+ if (durationSource === "tfhd" && type === "tfhd")
+ invalid.writeUInt32BE(0, offset + 16);
+ });
+ await writeFile(input, invalid);
+ await expect(
+ readRecordingVideoTiming(input, { timeoutMs: 5000 }),
+ ).rejects.toThrow();
+ },
+ );
+
+ test("refuses a truncated sample-time table on a remuxed tied-tail recording", async () => {
+ const input = await tiedTimestampSource("tied-stts-input.mp4", 2);
+ const sourceEvidence = await inspectRecordingSources(input, null);
+ const output = join(directory, "tied-stts-output.mp4");
+ await muxMediaTracksToMp4(input, null, output);
+ const bytes = await readFile(output);
+ visitFragmentBoxes(bytes, (type, offset) => {
+ if (type === "stts")
+ bytes.writeUInt32BE(bytes.readUInt32BE(offset + 12) + 1, offset + 12);
+ });
+ await writeFile(output, bytes);
+ await expect(
+ verifyRecording(output, { requireAudio: false, sourceEvidence }),
+ ).rejects.toThrow();
+ });
+
+ test("handles a zero-sized trailing box without reading beyond the recording", async () => {
+ const input = await tiedTimestampSource("tied-zero-box.mp4", 2);
+ const expected = await readRecordingVideoTiming(input, { timeoutMs: 5000 });
+ const trailing = Buffer.alloc(8);
+ trailing.write("free", 4, "ascii");
+ await writeFile(input, Buffer.concat([await readFile(input), trailing]));
+ expect(await readRecordingVideoTiming(input, { timeoutMs: 5000 })).toEqual(
+ expected,
+ );
+ });
+
+ test("refuses an unsafe extended box size without allocating its claimed payload", async () => {
+ const input = await tiedTimestampSource("tied-large-box.mp4", 2);
+ const trailing = Buffer.alloc(16);
+ trailing.writeUInt32BE(1);
+ trailing.write("moof", 4, "ascii");
+ trailing.writeBigUInt64BE(1n << 63n, 8);
+ await writeFile(input, Buffer.concat([await readFile(input), trailing]));
+ await expect(
+ readRecordingVideoTiming(input, { timeoutMs: 5000 }),
+ ).rejects.toThrow();
+ });
+
+ test.each([
+ "unknown-trun-flags",
+ "trun-count-overflow",
+ "zero-terminal-duration",
+ ])("refuses ambiguous tied-tail metadata: %s", async (damage) => {
+ const input = await tiedTimestampSource(`tied-malformed-${damage}.mp4`, 2);
+ const bytes = await readFile(input);
+ visitFragmentBoxes(bytes, (type, offset) => {
+ if (type !== "trun") return;
+ if (damage === "unknown-trun-flags")
+ bytes.writeUIntBE(bytes.readUIntBE(offset + 9, 3) | 2, offset + 9, 3);
+ else if (damage === "trun-count-overflow")
+ bytes.writeUInt32BE(0xffffffff, offset + 12);
+ else bytes.writeUInt32BE(0, offset + 20 + 39 * 16);
+ });
+ await writeFile(input, bytes);
+ await expect(inspectRecordingSources(input, null)).rejects.toThrow();
+ });
+
+ test.each([-1, 1])(
+ "rejects a %d tick change hidden by another packet at the same final timestamp",
+ async (tailChange) => {
+ const input = await tiedTimestampSource(
+ `tied-tail-source-${tailChange}.mp4`,
+ 2,
+ );
+ const changed = await tiedTimestampSource(
+ `tied-tail-change-${tailChange}.mp4`,
+ 2,
+ tailChange,
+ );
+ const sourceEvidence = await inspectRecordingSources(input, null);
+ const alteredEvidence = await inspectRecordingSources(changed, null);
+ expect(alteredEvidence.video.frameCount).toBe(40);
+ expect(alteredEvidence.integrity.video.contentSha256).toBe(
+ sourceEvidence.integrity.video.contentSha256,
+ );
+ expect((await videoPackets(changed)).map((packet) => packet.pts)).toEqual(
+ (await videoPackets(input)).map((packet) => packet.pts),
+ );
+ await expect(
+ verifyRecording(changed, { requireAudio: false, sourceEvidence }),
+ ).rejects.toThrow(
+ "does not preserve source video: presentation timeline",
+ );
+ },
+ );
+
+ test("rejects exchanging durations between packets with tied final timestamps", async () => {
+ const input = await tiedTimestampSource("tied-duration-source.mp4", 2);
+ const changed = await tiedTimestampSource(
+ "tied-duration-swapped.mp4",
+ 2,
+ 0,
+ true,
+ );
+ const sourceEvidence = await inspectRecordingSources(input, null);
+ await expect(
+ verifyRecording(changed, { requireAudio: false, sourceEvidence }),
+ ).rejects.toThrow("does not preserve source video: presentation timeline");
+ });
+
+ test("continues rejecting backwards presentation timestamps without B-frames", async () => {
+ const input = await fragmentedSource(-33_334);
+ const timing = await readRecordingVideoTiming(input, { timeoutMs: 5000 });
+ expect(timing.videoPacketCount).toBe(31);
+ await expect(inspectRecordingSources(input, null)).rejects.toThrow(
+ "Recording container timing does not match decoded video",
+ );
+ });
+
test.each([-1, 1, 100_000])(
"preserves fragment boundary clock offsets of %d microseconds",
async (offsetTicks) => {
@@ -993,6 +1420,98 @@ function expectExited(pid: number) {
}
describe("recording timing metadata lifetime", () => {
+ test.each(["cancel", "timeout"])(
+ "joins a stalled raw terminal-duration read after %s",
+ async (cause) => {
+ const input = await tiedTimestampSource(`tied-raw-${cause}.mp4`, 2);
+ const bytes = await readFile(input);
+ const identity = '"tied-terminal-read"';
+ let walked = false;
+ const originalNext = EncodedPacketSink.prototype.getNextPacket;
+ const next = spyOn(
+ EncodedPacketSink.prototype,
+ "getNextPacket",
+ ).mockImplementation(async function (
+ this: EncodedPacketSink,
+ ...args: Parameters<typeof originalNext>
+ ) {
+ const packet = await originalNext.apply(this, args);
+ if (!packet) walked = true;
+ return packet;
+ });
+ let began: (() => void) | undefined;
+ const requested = new Promise<void>((resolve) => {
+ began = resolve;
+ });
+ let ended: (() => void) | undefined;
+ const closed = new Promise<void>((resolve) => {
+ ended = resolve;
+ });
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ expect(request.headers.get("if-match")).toBe(identity);
+ const range = request.headers
+ .get("range")
+ ?.match(/^bytes=(\d+)-(\d+)$/);
+ if (!range) throw new Error("Fixture request has no range");
+ const start = Number(range[1]);
+ const end = Number(range[2]) + 1;
+ const body = bytes.subarray(start, end);
+ return new Response(
+ walked
+ ? new ReadableStream({
+ start(controller) {
+ controller.enqueue(body.subarray(0, 1));
+ began?.();
+ },
+ cancel() {
+ ended?.();
+ },
+ })
+ : body,
+ {
+ status: 206,
+ headers: {
+ ETag: identity,
+ "Content-Length": String(end - start),
+ "Content-Range": `bytes ${start}-${end - 1}/${bytes.length}`,
+ },
+ },
+ );
+ },
+ });
+ const controller = new AbortController();
+ try {
+ const outcome = readRecordingVideoTiming(
+ `http://127.0.0.1:${server.port}/tied.mp4`,
+ {
+ timeoutMs: cause === "timeout" ? 1000 : 5000,
+ abortSignal: controller.signal,
+ remoteObject: { objectIdentity: identity, fileSize: bytes.length },
+ },
+ ).catch((error: unknown) => error);
+ await requested;
+ if (cause === "cancel") controller.abort();
+ const error = await outcome;
+ expect(error).toBeInstanceOf(RecordingTimingError);
+ if (!(error instanceof RecordingTimingError))
+ throw new Error("Stalled raw read unexpectedly succeeded");
+ expect(error.message).toContain(
+ cause === "cancel" ? "cancelled" : "timed out",
+ );
+ expect(error.retryable).toBe(cause === "timeout");
+ await closed;
+ } finally {
+ controller.abort();
+ await server.stop(true);
+ next.mockRestore();
+ }
+ },
+ 10_000,
+ );
+
test.each(["pre-format", "post-format"])(
"joins a cancelled %s metadata read without leaking a rejected read",
async (stage) => {
diff --git a/apps/media-server/src/lib/recording-timing.ts b/apps/media-server/src/lib/recording-timing.ts
index d9be31eb4..c6b740121 100644
--- a/apps/media-server/src/lib/recording-timing.ts
+++ b/apps/media-server/src/lib/recording-timing.ts
@@ -1,7 +1,9 @@
+import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { type FileHandle, open } from "node:fs/promises";
import { isAbsolute } from "node:path";
import {
+ type EncodedPacket,
EncodedPacketSink,
Input,
MP4,
@@ -13,6 +15,8 @@ import {
const MAX_METADATA_BYTES = 64 * 1024 * 1024;
const MAX_RANGE_BYTES = 1024 * 1024;
const MAX_CACHE_BYTES = 8 * 1024 * 1024;
+const MAX_TERMINAL_PACKETS = 1024;
+const MAX_TIMING_CHILD_BOXES = 65_536;
export class RecordingTimingError extends Error {
constructor(
@@ -29,6 +33,10 @@ export interface RecordingVideoTiming {
firstTimestampTicks: bigint;
lastTimestampTicks: bigint;
lastDurationTicks: bigint;
+ videoPacketCount: number;
+ packetTimelineSha256: string;
+ terminalPacketCount: number;
+ terminalPacketSha256?: string;
}
interface RecordingTimingOptions {
@@ -58,6 +66,15 @@ function integerTicks(seconds: number, timeScale: number): bigint {
return BigInt(rounded);
}
+function rationalTicks(ticks: bigint, timeScale: number): string {
+ let numerator = ticks < 0n ? -ticks : ticks;
+ let denominator = BigInt(timeScale);
+ while (denominator !== 0n) {
+ [numerator, denominator] = [denominator, numerator % denominator];
+ }
+ return `${ticks / numerator}/${BigInt(timeScale) / numerator}`;
+}
+
function localReadError(error: unknown): RecordingTimingError {
const code =
typeof error === "object" && error !== null && "code" in error
@@ -78,6 +95,215 @@ function localReadError(error: unknown): RecordingTimingError {
);
}
+interface TimingBox {
+ type: string;
+ body: Buffer;
+}
+
+function invalidTimingTable(): never {
+ throw new RecordingTimingError(
+ "Recording sample duration table is invalid",
+ false,
+ );
+}
+
+function* timingBoxes(bytes: Buffer): Generator<TimingBox> {
+ let boxes = 0;
+ for (let offset = 0; offset < bytes.length; ) {
+ if (++boxes > MAX_TIMING_CHILD_BOXES) invalidTimingTable();
+ if (offset + 8 > bytes.length) invalidTimingTable();
+ let size = bytes.readUInt32BE(offset);
+ let header = 8;
+ if (size === 1) {
+ if (offset + 16 > bytes.length) invalidTimingTable();
+ size = Number(bytes.readBigUInt64BE(offset + 8));
+ header = 16;
+ } else if (size === 0) size = bytes.length - offset;
+ if (
+ !Number.isSafeInteger(size) ||
+ size < header ||
+ offset + size > bytes.length
+ ) {
+ invalidTimingTable();
+ }
+ yield {
+ type: bytes.toString("ascii", offset + 4, offset + 8),
+ body: bytes.subarray(offset + header, offset + size),
+ };
+ offset += size;
+ }
+}
+
+function timingChild(bytes: Buffer, type: string): Buffer | undefined {
+ let result: Buffer | undefined;
+ for (const box of timingBoxes(bytes)) {
+ if (box.type !== type) continue;
+ if (result) invalidTimingTable();
+ result = box.body;
+ }
+ return result;
+}
+
+async function readTerminalDurations(
+ readBytes: (start: number, end: number) => Promise<Uint8Array>,
+ fileSize: number,
+ trackId: number,
+ packetCount: number,
+ ordinals: Set<number>,
+ checkActive: () => void,
+): Promise<Map<number, bigint>> {
+ const durations = new Map<number, bigint>();
+ const wanted = [...ordinals].sort((left, right) => left - right);
+ let nextWanted = 0;
+ let samples = 0;
+ let defaultDuration = 0;
+ let foundDefaults = false;
+ let foundTrack = false;
+ const record = (count: number, duration: number) => {
+ if (
+ !Number.isSafeInteger(count) ||
+ count < 0 ||
+ samples + count > packetCount
+ ) {
+ invalidTimingTable();
+ }
+ while (nextWanted < wanted.length) {
+ const ordinal = wanted[nextWanted];
+ if (ordinal >= samples + count) break;
+ if (ordinal < samples) invalidTimingTable();
+ if (duration <= 0) invalidTimingTable();
+ durations.set(ordinal, BigInt(duration));
+ nextWanted++;
+ }
+ samples += count;
+ };
+ for (let offset = 0; offset < fileSize; ) {
+ checkActive();
+ if (offset + 8 > fileSize) invalidTimingTable();
+ const header = Buffer.from(await readBytes(offset, offset + 8));
+ const type = header.toString("ascii", 4, 8);
+ let size = header.readUInt32BE(0);
+ let headerSize = 8;
+ if (size === 1) {
+ if (offset + 16 > fileSize) invalidTimingTable();
+ size = Number(
+ Buffer.from(await readBytes(offset + 8, offset + 16)).readBigUInt64BE(),
+ );
+ headerSize = 16;
+ } else if (size === 0) size = fileSize - offset;
+ if (
+ !Number.isSafeInteger(size) ||
+ size < headerSize ||
+ offset + size > fileSize
+ ) {
+ invalidTimingTable();
+ }
+ if (type !== "moov" && type !== "moof") {
+ offset += size;
+ continue;
+ }
+ if (size === headerSize) invalidTimingTable();
+ const data = await readBytes(offset + headerSize, offset + size);
+ const body = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
+ if (type === "moov") {
+ for (const box of timingBoxes(body)) {
+ if (box.type === "mvex") {
+ for (const child of timingBoxes(box.body)) {
+ if (child.type !== "trex") continue;
+ if (child.body.length !== 24 || child.body.readUInt32BE() !== 0)
+ invalidTimingTable();
+ if (child.body.readUInt32BE(4) === trackId) {
+ if (foundDefaults) invalidTimingTable();
+ foundDefaults = true;
+ defaultDuration = child.body.readUInt32BE(12);
+ }
+ }
+ }
+ if (box.type !== "trak") continue;
+ const tkhd = timingChild(box.body, "tkhd");
+ if (!tkhd || (tkhd[0] !== 0 && tkhd[0] !== 1)) invalidTimingTable();
+ const idOffset = tkhd[0] === 1 ? 20 : 12;
+ if (tkhd.length < idOffset + 4) invalidTimingTable();
+ if (tkhd.readUInt32BE(idOffset) !== trackId) continue;
+ if (foundTrack) invalidTimingTable();
+ foundTrack = true;
+ let table: Buffer | undefined = box.body;
+ for (const name of ["mdia", "minf", "stbl", "stts"]) {
+ table = table && timingChild(table, name);
+ }
+ if (!table || table.length < 8 || table.readUInt32BE() !== 0)
+ invalidTimingTable();
+ const entries = table.readUInt32BE(4);
+ if (table.length !== 8 + entries * 8) invalidTimingTable();
+ for (let index = 0; index < entries; index++) {
+ record(
+ table.readUInt32BE(8 + index * 8),
+ table.readUInt32BE(12 + index * 8),
+ );
+ if (index % 1024 === 0) {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ checkActive();
+ }
+ }
+ }
+ } else {
+ if (!foundTrack) invalidTimingTable();
+ for (const box of timingBoxes(body)) {
+ if (box.type !== "traf") continue;
+ const tfhd = timingChild(box.body, "tfhd");
+ if (!tfhd || tfhd.length < 8 || tfhd[0] !== 0) invalidTimingTable();
+ if (tfhd.readUInt32BE(4) !== trackId) continue;
+ const flags = tfhd.readUIntBE(1, 3);
+ if (flags & ~0x03003b) invalidTimingTable();
+ const durationOffset = 8 + (flags & 1 ? 8 : 0) + (flags & 2 ? 4 : 0);
+ const expectedSize =
+ durationOffset +
+ (flags & 8 ? 4 : 0) +
+ (flags & 16 ? 4 : 0) +
+ (flags & 32 ? 4 : 0);
+ if (tfhd.length !== expectedSize) invalidTimingTable();
+ const fragmentDuration =
+ flags & 8 ? tfhd.readUInt32BE(durationOffset) : defaultDuration;
+ for (const child of timingBoxes(box.body)) {
+ if (child.type !== "trun") continue;
+ const run = child.body;
+ if (run.length < 8 || (run[0] !== 0 && run[0] !== 1))
+ invalidTimingTable();
+ const runFlags = run.readUIntBE(1, 3);
+ if (runFlags & ~0xf05) invalidTimingTable();
+ const count = run.readUInt32BE(4);
+ if (flags & 0x10000 && count > 0) invalidTimingTable();
+ const start = 8 + (runFlags & 1 ? 4 : 0) + (runFlags & 4 ? 4 : 0);
+ const stride =
+ [0x100, 0x200, 0x400, 0x800].filter((flag) => runFlags & flag)
+ .length * 4;
+ if (
+ run.length !== start + count * stride ||
+ samples + count > packetCount
+ )
+ invalidTimingTable();
+ for (let index = 0; index < count; index++) {
+ record(
+ 1,
+ runFlags & 0x100
+ ? run.readUInt32BE(start + index * stride)
+ : fragmentDuration,
+ );
+ if (index % 1024 === 0) {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ checkActive();
+ }
+ }
+ }
+ }
+ }
+ offset += size;
+ }
+ if (samples !== packetCount || durations.size !== ordinals.size)
+ invalidTimingTable();
+ return durations;
+}
+
export async function readRecordingVideoTiming(
path: string,
options: RecordingTimingOptions,
@@ -392,26 +618,114 @@ export async function readRecordingVideoTiming(
metadataOnly: true,
skipLiveWait: true,
});
- const last = await sink.getPacket(Infinity, {
- metadataOnly: true,
- skipLiveWait: true,
- });
checkActive();
- if (!first || !last) {
+ if (!first) {
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) {
+ let lastTimestampTicks = firstTimestampTicks;
+ let lastDurationTicks = integerTicks(first.duration, timeScale);
+ const terminalPackets: {
+ metadata: EncodedPacket;
+ previous: EncodedPacket | undefined;
+ ordinal: number;
+ }[] = [];
+ let previousPacket: EncodedPacket | undefined;
+ let packet: EncodedPacket | null = first;
+ let packetCount = 0;
+ const packetTimeline = createHash("sha256");
+ while (packet) {
+ checkActive();
+ if (
+ !Number.isSafeInteger(packet.sequenceNumber) ||
+ packet.sequenceNumber < 0 ||
+ (previousPacket &&
+ packet.sequenceNumber <= previousPacket.sequenceNumber)
+ ) {
+ throw new RecordingTimingError(
+ "Recording packet order is invalid",
+ false,
+ );
+ }
+ const timestamp = integerTicks(packet.timestamp, timeScale);
+ packetTimeline.update(
+ `${rationalTicks(timestamp - firstTimestampTicks, timeScale)}\n`,
+ );
+ if (timestamp > lastTimestampTicks) {
+ lastTimestampTicks = timestamp;
+ terminalPackets.length = 0;
+ }
+ if (timestamp === lastTimestampTicks) {
+ if (terminalPackets.length === MAX_TERMINAL_PACKETS) {
+ throw new RecordingTimingError(
+ "Recording terminal packets exceed their bound",
+ false,
+ );
+ }
+ terminalPackets.push({
+ metadata: packet,
+ previous: previousPacket,
+ ordinal: packetCount,
+ });
+ lastDurationTicks = integerTicks(packet.duration, timeScale);
+ }
+ previousPacket = packet;
+ packet = await sink.getNextPacket(packet, {
+ metadataOnly: true,
+ skipLiveWait: true,
+ });
+ if (++packetCount % 1024 === 0) {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ }
+ }
+ checkActive();
+ if (!terminalPackets.length || lastDurationTicks <= 0n) {
throw new RecordingTimingError(
"Recording video endpoint is invalid",
false,
);
}
+ let terminalPacketSha256: string | undefined;
+ if (terminalPackets.length > 1) {
+ // Demuxers can replace tied samples' stored durations with zero-length PTS gaps.
+ const durations = await readTerminalDurations(
+ readRange,
+ fileSize,
+ track.id,
+ packetCount,
+ new Set(terminalPackets.map(({ ordinal }) => ordinal)),
+ checkActive,
+ );
+ const hash = createHash("sha256");
+ for (const { metadata, previous, ordinal } of terminalPackets) {
+ const packet = previous
+ ? await sink.getNextPacket(previous, { skipLiveWait: true })
+ : await sink.getFirstPacket({ skipLiveWait: true });
+ checkActive();
+ if (
+ !packet ||
+ packet.sequenceNumber !== metadata.sequenceNumber ||
+ packet.timestamp !== metadata.timestamp ||
+ packet.duration !== metadata.duration ||
+ packet.byteLength !== metadata.byteLength ||
+ packet.data.byteLength !== packet.byteLength
+ ) {
+ throw new RecordingTimingError(
+ "Recording terminal packet changed",
+ false,
+ );
+ }
+ const duration = durations.get(ordinal);
+ if (duration === undefined) invalidTimingTable();
+ const digest = createHash("sha256").update(packet.data).digest("hex");
+ hash.update(`${rationalTicks(duration, timeScale)},${digest}\n`);
+ }
+ terminalPacketSha256 = hash.digest("hex");
+ }
+
if (file) {
const stat = await file.stat();
checkActive();
@@ -431,6 +745,10 @@ export async function readRecordingVideoTiming(
firstTimestampTicks,
lastTimestampTicks,
lastDurationTicks,
+ videoPacketCount: packetCount,
+ packetTimelineSha256: packetTimeline.digest("hex"),
+ terminalPacketCount: terminalPackets.length,
+ ...(terminalPacketSha256 ? { terminalPacketSha256 } : {}),
};
} catch (error) {
const reason = controller.signal.aborted ? controller.signal.reason : error;
diff --git a/apps/media-server/src/lib/recording-verification.ts b/apps/media-server/src/lib/recording-verification.ts
index 057b7f292..6849bc5af 100644
--- a/apps/media-server/src/lib/recording-verification.ts
+++ b/apps/media-server/src/lib/recording-verification.ts
@@ -115,6 +115,7 @@ interface DecodedStream {
firstVideoPts?: bigint;
lastVideoPts?: bigint;
lastVideoEndPts?: bigint;
+ terminalVideoFrameCount?: number;
sampleRate?: number;
frameCount: number;
sampleCount: number;
@@ -185,24 +186,44 @@ function videoTailIntegrity(
if (
(timing.lastTimestampTicks - timing.firstTimestampTicks) *
timeBaseDenominator !==
- (lastVideoPts - firstVideoPts) * timeBaseNumerator * timeScale
+ (lastVideoPts - firstVideoPts) * timeBaseNumerator * timeScale ||
+ timing.videoPacketCount !== stream.frameCount ||
+ timing.terminalPacketCount !== stream.terminalVideoFrameCount
) {
throw new Error("Recording container timing does not match decoded video");
}
+ if (!/^[a-f0-9]{64}$/.test(timing.packetTimelineSha256)) {
+ throw new Error("Recording container packet timing is missing");
+ }
+ const packets = `packets:${timing.packetTimelineSha256}\n`;
+ if (timing.terminalPacketCount > 1) {
+ if (!timing.terminalPacketSha256) {
+ throw new Error("Recording terminal packets have no content binding");
+ }
+ return `${packets}tails:${timing.terminalPacketCount},${timing.terminalPacketSha256}\n`;
+ }
let numerator = timing.lastDurationTicks;
let denominator = timeScale;
while (denominator !== 0n) {
[numerator, denominator] = [denominator, numerator % denominator];
}
- return `tail:${timing.lastDurationTicks / numerator}/${timeScale / numerator}\n`;
+ return `${packets}tail:${timing.lastDurationTicks / numerator}/${timeScale / numerator}\n`;
}
-function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
+function decodeLine(
+ line: string,
+ streams: Map<number, DecodedStream>,
+ allowVideoTies = false,
+): void {
if (!line) return;
const digest = line.match(/^(\d+),(v|a),SHA256=([a-f0-9]{64})$/);
if (digest) {
const stream = streams.get(Number(digest[1]));
- if (!stream || stream.contentSha256) {
+ if (
+ !stream ||
+ stream.contentSha256 ||
+ stream.kind !== (digest[2] === "v" ? "video" : "audio")
+ ) {
throw new Error("Invalid decoded recording content digest");
}
stream.contentSha256 = digest[3];
@@ -271,7 +292,12 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
const startTime = pts * stream.timeBase;
const duration = ticks * stream.timeBase;
const endTime = startTime + duration;
- if (!Number.isFinite(endTime) || startTime <= stream.previousTime) {
+ if (
+ !Number.isFinite(endTime) ||
+ startTime < stream.previousTime ||
+ ((stream.kind === "audio" || !allowVideoTies) &&
+ startTime === stream.previousTime)
+ ) {
throw new Error("Decoded recording timestamps are invalid");
}
stream.maximumGap = Math.max(
@@ -284,7 +310,14 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
stream.frameCount++;
if (stream.kind === "video") {
const timestamp = BigInt(pts);
+ if (stream.lastVideoPts !== undefined && timestamp < stream.lastVideoPts) {
+ throw new Error("Decoded recording timestamps are invalid");
+ }
stream.firstVideoPts ??= timestamp;
+ stream.terminalVideoFrameCount =
+ stream.lastVideoPts === timestamp
+ ? (stream.terminalVideoFrameCount ?? 0) + 1
+ : 1;
stream.lastVideoPts = timestamp;
stream.lastVideoEndPts = timestamp + BigInt(ticks);
stream.timeline.update(
@@ -316,6 +349,7 @@ function decodeLine(line: string, streams: Map<number, DecodedStream>): void {
async function readFrameEvidence(
stream: ReadableStream<Uint8Array>,
streams: Map<number, DecodedStream>,
+ allowVideoTies: boolean,
): Promise<void> {
const decoder = new TextDecoder();
let pending = "";
@@ -326,7 +360,7 @@ async function readFrameEvidence(
if (newline > MAX_OUTPUT_LINE_LENGTH) {
throw new Error("Recording decoder output exceeded its limit");
}
- decodeLine(pending.slice(0, newline).trim(), streams);
+ decodeLine(pending.slice(0, newline).trim(), streams, allowVideoTies);
pending = pending.slice(newline + 1);
newline = pending.indexOf("\n");
}
@@ -335,13 +369,13 @@ async function readFrameEvidence(
}
}
pending += decoder.decode();
- decodeLine(pending.trim(), streams);
+ decodeLine(pending.trim(), streams, allowVideoTies);
}
async function readDecoderErrors(
stream: ReadableStream<Uint8Array>,
input: string,
-): Promise<string> {
+): Promise<{ error: string; digests: string[] }> {
const decoder = new TextDecoder();
let output = "";
let truncated = false;
@@ -352,14 +386,25 @@ async function readDecoderErrors(
}
output += decoder.decode();
if (truncated) output = output.slice(0, output.lastIndexOf("\n") + 1);
- return (
- output
- .replaceAll(input, "<recording input>")
- .replace(/https?:\/\/\S+/g, "<redacted URL>")
- .trim()
- .slice(-MAX_ERROR_LENGTH) ||
- (truncated ? "Decoder error output exceeded its limit" : "")
- );
+ const digests: string[] = [];
+ output = output
+ .split("\n")
+ .filter((line) => {
+ if (!/^\d+,(v|a),SHA256=[a-f0-9]{64}$/.test(line.trim())) return true;
+ digests.push(line.trim());
+ return false;
+ })
+ .join("\n");
+ return {
+ digests,
+ error:
+ output
+ .replaceAll(input, "<recording input>")
+ .replace(/https?:\/\/\S+/g, "<redacted URL>")
+ .trim()
+ .slice(-MAX_ERROR_LENGTH) ||
+ (truncated ? "Decoder error output exceeded its limit" : ""),
+ };
}
function validateEvidence(
@@ -624,6 +669,23 @@ async function decodeRecording(
true,
);
}
+ const outputOptions = [
+ "-map",
+ "0:v:0",
+ ...(sourceAudioInput === null
+ ? []
+ : ["-map", sourceAudioInput ? "1:a:0" : "0:a:0?"]),
+ "-fps_mode",
+ "passthrough",
+ "-enc_time_base:v",
+ "-1",
+ "-c:v",
+ "rawvideo",
+ "-c:a",
+ "pcm_f64le",
+ "-threads",
+ "1",
+ ];
const proc = registerSubprocess(
spawn({
cmd: [
@@ -668,24 +730,16 @@ async function decodeRecording(
sourceAudioInput,
]
: []),
- "-map",
- "0:v:0",
- ...(sourceAudioInput === null
- ? []
- : ["-map", sourceAudioInput ? "1:a:0" : "0:a:0?"]),
- "-fps_mode",
- "passthrough",
- "-enc_time_base:v",
- "-1",
- "-c:v",
- "rawvideo",
- "-c:a",
- "pcm_f64le",
- "-threads",
- "1",
+ ...outputOptions,
"-f",
- "tee",
- "[f=framecrc]pipe:1|[f=streamhash:hash=sha256]pipe:1",
+ "framecrc",
+ "pipe:1",
+ ...outputOptions,
+ "-f",
+ "streamhash",
+ "-hash",
+ "sha256",
+ "pipe:2",
],
stdin: "ignore",
stdout: "pipe",
@@ -715,16 +769,21 @@ async function decodeRecording(
stop();
}, decodeBudgetMs);
const streams = new Map<number, DecodedStream>();
- const frames = readFrameEvidence(proc.stdout, streams);
+ const frames = readFrameEvidence(
+ proc.stdout,
+ streams,
+ videoTiming !== undefined,
+ );
const errors = readDecoderErrors(proc.stderr, input);
let result: RecordingSourceEvidence;
try {
if (options.abortSignal?.aborted) cancel();
- const [, stderr, exitCode] = await Promise.all([
+ const [, diagnostics, exitCode] = await Promise.all([
frames,
errors,
proc.exited,
]);
+ const stderr = diagnostics.error;
if (failure) throw failure;
if (exitCode !== 0 || stderr || proc.signalCode) {
throw new RecordingVerificationError(
@@ -735,6 +794,7 @@ async function decodeRecording(
),
);
}
+ for (const digest of diagnostics.digests) decodeLine(digest, streams);
result = validateEvidence(
streams,
options,