Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add timeline layout and waveform utilities

Richie McIlroye77ef0334f46
diff --git a/apps/web/__tests__/unit/filmstrip-pool.test.ts b/apps/web/__tests__/unit/filmstrip-pool.test.ts
new file mode 100644
index 000000000..ebed61a24
--- /dev/null
+++ b/apps/web/__tests__/unit/filmstrip-pool.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from "vitest";
+import {
+ FILMSTRIP_MAX_TILES,
+ filmstripPoolQuantum,
+ filmstripWindowTimes,
+ nearestPooledTime,
+ POOL_QUANTUM_MAX,
+ POOL_QUANTUM_MIN,
+ poolBorrowTolerance,
+ quantizePoolTime,
+ rememberFrame,
+} from "@/app/s/[videoId]/_components/timeline/filmstrip-math";
+
+describe("filmstripPoolQuantum", () => {
+ it("scales with the duration between its bounds", () => {
+ expect(filmstripPoolQuantum(1120)).toBeCloseTo(10);
+ expect(filmstripPoolQuantum(10)).toBe(POOL_QUANTUM_MIN);
+ expect(filmstripPoolQuantum(12 * 3600)).toBe(POOL_QUANTUM_MAX);
+ });
+
+ it("is safe before the duration is known", () => {
+ expect(filmstripPoolQuantum(0)).toBe(POOL_QUANTUM_MIN);
+ expect(filmstripPoolQuantum(Number.NaN)).toBe(POOL_QUANTUM_MIN);
+ });
+});
+
+describe("quantizePoolTime", () => {
+ it("snaps a moment onto the grid", () => {
+ expect(quantizePoolTime(7.4, 2)).toBe(8);
+ expect(quantizePoolTime(6.9, 2)).toBe(6);
+ expect(quantizePoolTime(-5, 2)).toBe(0);
+ });
+
+ it("collapses nearby requests onto one slot", () => {
+ expect(quantizePoolTime(10.1, 5)).toBe(quantizePoolTime(11.9, 5));
+ });
+});
+
+describe("filmstripWindowTimes", () => {
+ it("puts one time at the centre of every tile in the window", () => {
+ expect(filmstripWindowTimes(4, 0, 100, 100)).toEqual([
+ 12.5, 37.5, 62.5, 87.5,
+ ]);
+ });
+
+ it("follows the window rather than the video", () => {
+ expect(filmstripWindowTimes(2, 40, 60, 100)).toEqual([45, 55]);
+ });
+
+ it("keeps clear of the very last frames", () => {
+ const times = filmstripWindowTimes(2, 0, 10, 10);
+ expect(times[1]).toBeCloseTo(7.5);
+ expect(filmstripWindowTimes(1, 9.9, 10, 10)[0]).toBeCloseTo(9.9);
+ });
+
+ it("returns nothing without a window, tiles or a duration", () => {
+ expect(filmstripWindowTimes(0, 0, 100, 100)).toEqual([]);
+ expect(filmstripWindowTimes(4, 50, 50, 100)).toEqual([]);
+ expect(filmstripWindowTimes(4, 0, 100, 0)).toEqual([]);
+ });
+});
+
+describe("nearestPooledTime", () => {
+ it("borrows the closest frame inside the tolerance", () => {
+ expect(nearestPooledTime([0, 5, 10], 6, 2)).toBe(5);
+ expect(nearestPooledTime([0, 5, 10], 9, 2)).toBe(10);
+ });
+
+ it("refuses anything further away than the tolerance", () => {
+ // Dead centre between two frames, both of them out of reach.
+ expect(nearestPooledTime([0, 5, 10], 7.5, 2)).toBeNull();
+ expect(nearestPooledTime([0, 20], 10, 2)).toBeNull();
+ expect(nearestPooledTime([], 10, 100)).toBeNull();
+ });
+});
+
+describe("poolBorrowTolerance", () => {
+ it("never reaches closer than the grid it captures onto", () => {
+ expect(poolBorrowTolerance(2, 10, 28)).toBe(2);
+ });
+
+ it("widens to a tile when zoomed out past the grid", () => {
+ expect(poolBorrowTolerance(0.5, 280, 28)).toBe(10);
+ });
+});
+
+describe("rememberFrame", () => {
+ it("drops the oldest capture once the pool is full", () => {
+ const frames = new Map<number, string>();
+ for (let index = 0; index < 5; index += 1) {
+ rememberFrame(frames, index, `frame-${index}`, 3);
+ }
+
+ expect(frames.size).toBe(3);
+ expect(Array.from(frames.keys())).toEqual([2, 3, 4]);
+ });
+
+ it("overwrites a slot in place rather than growing", () => {
+ const frames = new Map<number, string>();
+ rememberFrame(frames, 1, "a", 2);
+ rememberFrame(frames, 1, "b", 2);
+
+ expect(frames.size).toBe(1);
+ expect(frames.get(1)).toBe("b");
+ });
+
+ it("keeps enough frames for a full strip at any zoom", () => {
+ const frames = new Map<number, string>();
+ for (let index = 0; index < FILMSTRIP_MAX_TILES; index += 1) {
+ rememberFrame(frames, index, `frame-${index}`);
+ }
+ expect(frames.size).toBe(FILMSTRIP_MAX_TILES);
+ });
+});
diff --git a/apps/web/__tests__/unit/timeline-layout.test.ts b/apps/web/__tests__/unit/timeline-layout.test.ts
new file mode 100644
index 000000000..0158c457f
--- /dev/null
+++ b/apps/web/__tests__/unit/timeline-layout.test.ts
@@ -0,0 +1,222 @@
+import { describe, expect, it } from "vitest";
+import {
+ CLUSTER_MAX,
+ MIN_NODE_GAP,
+ RAIL_PAD_X,
+} from "@/app/s/[videoId]/_components/timeline/timeline-constants";
+import {
+ type BranchNode,
+ branchComments,
+ type LayoutComment,
+ layoutBranches,
+} from "@/app/s/[videoId]/_components/timeline/timeline-layout";
+
+/**
+ * 1000px of usable rail over a 100s video: one second of video is ten pixels,
+ * so the 26px minimum gap works out to a tidy 2.6s.
+ */
+const TRACK_WIDTH = 1000 + RAIL_PAD_X * 2;
+const DURATION = 100;
+const WINDOW = { start: 0, end: DURATION };
+const GAP_SECONDS = (MIN_NODE_GAP / 1000) * DURATION;
+
+let sequence = 0;
+const comment = (
+ timestamp: number | null,
+ overrides: Partial<LayoutComment> = {},
+): LayoutComment => {
+ sequence += 1;
+ return {
+ id: `c${sequence}`,
+ timestamp,
+ createdAt: new Date(1_700_000_000_000 + sequence * 1000),
+ ...overrides,
+ };
+};
+
+const at = (nodes: BranchNode[], index: number) => {
+ const node = nodes[index];
+ if (!node) throw new Error(`no node at ${index}`);
+ return node;
+};
+
+describe("layoutBranches", () => {
+ it("returns nothing for empty input, or when the window has no span", () => {
+ expect(layoutBranches([], WINDOW, TRACK_WIDTH)).toEqual([]);
+ expect(
+ layoutBranches([comment(5)], { start: 0, end: 0 }, TRACK_WIDTH),
+ ).toEqual([]);
+ expect(
+ layoutBranches([comment(5)], { start: 0, end: Number.NaN }, TRACK_WIDTH),
+ ).toEqual([]);
+ });
+
+ it("drops comments that are not pinned to a moment", () => {
+ const nodes = layoutBranches(
+ [comment(null), comment(null)],
+ WINDOW,
+ TRACK_WIDTH,
+ );
+ expect(nodes).toEqual([]);
+ });
+
+ it("places a single comment on lane 0", () => {
+ const only = comment(12.5);
+ const nodes = layoutBranches([only], WINDOW, TRACK_WIDTH);
+
+ expect(nodes).toHaveLength(1);
+ const node = at(nodes, 0);
+ expect(node.kind).toBe("single");
+ expect(node.lane).toBe(0);
+ expect(node.t).toBe(12.5);
+ expect(node.id).toBe(only.id);
+ });
+
+ it("keeps well-spaced comments on lane 0 in time order", () => {
+ const nodes = layoutBranches(
+ [comment(60), comment(10), comment(35)],
+ WINDOW,
+ TRACK_WIDTH,
+ );
+
+ expect(nodes.map((node) => node.t)).toEqual([10, 35, 60]);
+ expect(nodes.every((node) => node.lane === 0)).toBe(true);
+ expect(nodes.every((node) => node.kind === "single")).toBe(true);
+ });
+
+ it("breaks timestamp ties by creation time", () => {
+ const later = comment(20, {
+ id: "later",
+ createdAt: new Date("2026-01-02T00:00:00Z"),
+ });
+ const earlier = comment(20, {
+ id: "earlier",
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ });
+
+ // Same instant, so they land on separate lanes rather than one stack; the
+ // older of the two is still laid out first.
+ const nodes = layoutBranches([later, earlier], WINDOW, TRACK_WIDTH);
+ expect(
+ nodes.flatMap((node) => branchComments(node)).map((c) => c.id),
+ ).toEqual(["earlier", "later"]);
+ expect(nodes.map((node) => node.lane)).toEqual([0, 1]);
+ });
+
+ it("pushes a colliding comment to lane 1", () => {
+ const nodes = layoutBranches(
+ [comment(10), comment(10 + GAP_SECONDS / 2)],
+ WINDOW,
+ TRACK_WIDTH,
+ );
+
+ expect(nodes).toHaveLength(2);
+ expect(at(nodes, 0).lane).toBe(0);
+ expect(at(nodes, 1).lane).toBe(1);
+ expect(nodes.every((node) => node.kind === "single")).toBe(true);
+ });
+
+ it("folds a third collision into a cluster on the most recent node", () => {
+ const first = comment(10);
+ const second = comment(10.2);
+ const third = comment(10.4);
+ const nodes = layoutBranches([first, second, third], WINDOW, TRACK_WIDTH);
+
+ expect(nodes).toHaveLength(2);
+ const overflow = at(nodes, 1);
+ expect(overflow.kind).toBe("cluster");
+ expect(overflow.lane).toBe(1);
+ // The cluster keeps its first member's position, not the newcomer's.
+ expect(overflow.t).toBe(10.2);
+ expect(branchComments(overflow).map((c) => c.id)).toEqual([
+ second.id,
+ third.id,
+ ]);
+ });
+
+ it("caps a cluster and starts a new one once it is full", () => {
+ // Two singles (one per lane) plus enough collisions to fill a cluster and
+ // spill into the next.
+ const crowd = Array.from({ length: CLUSTER_MAX + 4 }, (_, index) =>
+ comment(10 + index * 0.01),
+ );
+ const nodes = layoutBranches(crowd, WINDOW, TRACK_WIDTH);
+
+ const clusters = nodes.filter((node) => node.kind === "cluster");
+ expect(clusters.length).toBeGreaterThanOrEqual(2);
+ for (const cluster of clusters) {
+ expect(branchComments(cluster).length).toBeLessThanOrEqual(CLUSTER_MAX);
+ }
+ expect(branchComments(clusters[0] as BranchNode)).toHaveLength(CLUSTER_MAX);
+
+ // Nothing is lost on the way through.
+ const total = nodes.reduce(
+ (sum, node) => sum + branchComments(node).length,
+ 0,
+ );
+ expect(total).toBe(crowd.length);
+ });
+
+ it("falls back to lane 0 for everything before the band is measured", () => {
+ const nodes = layoutBranches(
+ [comment(10), comment(10.1), comment(10.2)],
+ WINDOW,
+ 0,
+ );
+
+ expect(nodes).toHaveLength(3);
+ expect(nodes.every((node) => node.lane === 0)).toBe(true);
+ });
+
+ it("honours a wider minimum gap", () => {
+ const spaced = [comment(10), comment(10 + GAP_SECONDS * 1.2)];
+
+ expect(layoutBranches(spaced, WINDOW, TRACK_WIDTH)).toHaveLength(2);
+ expect(
+ layoutBranches(spaced, WINDOW, TRACK_WIDTH).every(
+ (node) => node.lane === 0,
+ ),
+ ).toBe(true);
+
+ // Same comments, a gap they no longer clear.
+ const tighter = layoutBranches(
+ spaced,
+ WINDOW,
+ TRACK_WIDTH,
+ MIN_NODE_GAP * 2,
+ );
+ expect(at(tighter, 1).lane).toBe(1);
+ });
+
+ it("culls comments outside the window, keeping a small margin", () => {
+ const window = { start: 40, end: 60 };
+ const inside = comment(50);
+ const nodes = layoutBranches(
+ [comment(10), inside, comment(90)],
+ window,
+ TRACK_WIDTH,
+ );
+
+ expect(nodes.map((node) => node.id)).toEqual([inside.id]);
+
+ // Just outside the edges, but within the 2% margin, so still drawn.
+ const edge = layoutBranches(
+ [comment(39.8), comment(60.2)],
+ window,
+ TRACK_WIDTH,
+ );
+ expect(edge).toHaveLength(2);
+ });
+
+ it("separates comments that collide zoomed out once the window narrows", () => {
+ const pair = [comment(50), comment(51)];
+
+ const wide = layoutBranches(pair, WINDOW, TRACK_WIDTH);
+ expect(wide.map((node) => node.lane)).toEqual([0, 1]);
+
+ // 10s of video across the same rail: a second is now 100px apart, well
+ // clear of the minimum gap.
+ const zoomed = layoutBranches(pair, { start: 45, end: 55 }, TRACK_WIDTH);
+ expect(zoomed.map((node) => node.lane)).toEqual([0, 0]);
+ });
+});
diff --git a/apps/web/__tests__/unit/timeline-window.test.ts b/apps/web/__tests__/unit/timeline-window.test.ts
new file mode 100644
index 000000000..c813a5b8d
--- /dev/null
+++ b/apps/web/__tests__/unit/timeline-window.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it } from "vitest";
+import {
+ fractionInWindow,
+ RAIL_PAD_X,
+ timeFromClientX,
+} from "@/app/s/[videoId]/_components/timeline/timeline-constants";
+import {
+ clampWindow,
+ followWindow,
+ fullWindow,
+ isFullWindow,
+ MIN_WINDOW_S,
+ panWindowBy,
+ zoomWindowAt,
+} from "@/app/s/[videoId]/_components/timeline/timeline-window";
+
+const DURATION = 100;
+/** 1000px of usable rail, so one second of a full window is ten pixels. */
+const RECT = { left: 0, width: 1000 + RAIL_PAD_X * 2 };
+
+describe("fractionInWindow", () => {
+ it("maps a moment onto its place in the window", () => {
+ expect(fractionInWindow(50, 0, 100)).toBeCloseTo(0.5);
+ expect(fractionInWindow(45, 40, 60)).toBeCloseTo(0.25);
+ });
+
+ it("runs outside 0-1 off-window, so callers can cull", () => {
+ expect(fractionInWindow(30, 40, 60)).toBeLessThan(0);
+ expect(fractionInWindow(70, 40, 60)).toBeGreaterThan(1);
+ });
+
+ it("is zero for a window with no span", () => {
+ expect(fractionInWindow(10, 5, 5)).toBe(0);
+ expect(fractionInWindow(10, 0, Number.NaN)).toBe(0);
+ });
+});
+
+describe("timeFromClientX", () => {
+ it("reads a time out of the padded rail", () => {
+ expect(timeFromClientX(RAIL_PAD_X, RECT, 0, DURATION)).toBeCloseTo(0);
+ expect(timeFromClientX(RAIL_PAD_X + 500, RECT, 0, DURATION)).toBeCloseTo(
+ 50,
+ );
+ });
+
+ it("reads it out of the window, not the video", () => {
+ expect(timeFromClientX(RAIL_PAD_X + 500, RECT, 40, 60)).toBeCloseTo(50);
+ expect(timeFromClientX(RAIL_PAD_X, RECT, 40, 60)).toBeCloseTo(40);
+ expect(timeFromClientX(RAIL_PAD_X + 1000, RECT, 40, 60)).toBeCloseTo(60);
+ });
+
+ it("clamps to the rail and gives up on an unmeasured band", () => {
+ expect(timeFromClientX(-500, RECT, 40, 60)).toBeCloseTo(40);
+ expect(timeFromClientX(9999, RECT, 40, 60)).toBeCloseTo(60);
+ expect(timeFromClientX(100, { left: 0, width: 0 }, 0, DURATION)).toBe(0);
+ });
+});
+
+describe("clampWindow", () => {
+ it("keeps the window inside the video", () => {
+ expect(clampWindow({ start: -20, end: 30 }, DURATION)).toEqual({
+ start: 0,
+ end: 50,
+ });
+ expect(clampWindow({ start: 80, end: 130 }, DURATION)).toEqual({
+ start: 50,
+ end: 100,
+ });
+ });
+
+ it("refuses to collapse below the minimum span", () => {
+ const tight = clampWindow({ start: 50, end: 51 }, DURATION);
+ expect(tight.end - tight.start).toBeCloseTo(MIN_WINDOW_S);
+ });
+
+ it("falls back to the whole video when it is shorter than the minimum", () => {
+ const short = clampWindow({ start: 1, end: 2 }, 4);
+ expect(short).toEqual({ start: 0, end: 4 });
+ });
+
+ it("has nothing to clamp before the duration is known", () => {
+ expect(clampWindow({ start: 0, end: 10 }, 0)).toEqual({ start: 0, end: 0 });
+ });
+});
+
+describe("zoomWindowAt", () => {
+ it("keeps the focus time under the cursor", () => {
+ const focus = 30;
+ let window = fullWindow(DURATION);
+ const anchor = fractionInWindow(focus, window.start, window.end);
+
+ for (const factor of [1.5, 1.5, 2, 1.25]) {
+ window = zoomWindowAt(window, factor, focus, DURATION);
+ expect(fractionInWindow(focus, window.start, window.end)).toBeCloseTo(
+ anchor,
+ 5,
+ );
+ }
+ });
+
+ it("shrinks the span on the way in and grows it on the way out", () => {
+ const zoomed = zoomWindowAt(fullWindow(DURATION), 2, 50, DURATION);
+ expect(zoomed.end - zoomed.start).toBeCloseTo(50);
+
+ const back = zoomWindowAt(zoomed, 0.5, 50, DURATION);
+ expect(back.end - back.start).toBeCloseTo(100);
+ expect(isFullWindow(back, DURATION)).toBe(true);
+ });
+
+ it("stops at the minimum span and at the video edges", () => {
+ const tiny = zoomWindowAt(fullWindow(DURATION), 1000, 0, DURATION);
+ expect(tiny.end - tiny.start).toBeCloseTo(MIN_WINDOW_S);
+ expect(tiny.start).toBeCloseTo(0);
+
+ const atEnd = zoomWindowAt(fullWindow(DURATION), 1000, DURATION, DURATION);
+ expect(atEnd.end).toBeCloseTo(DURATION);
+ });
+
+ it("ignores a nonsense factor", () => {
+ const window = { start: 20, end: 40 };
+ expect(zoomWindowAt(window, 0, 30, DURATION)).toEqual(window);
+ expect(zoomWindowAt(window, Number.NaN, 30, DURATION)).toEqual(window);
+ });
+});
+
+describe("panWindowBy", () => {
+ it("slides the window without changing its span", () => {
+ const panned = panWindowBy({ start: 20, end: 40 }, 15, DURATION);
+ expect(panned).toEqual({ start: 35, end: 55 });
+ });
+
+ it("stops at the ends", () => {
+ expect(panWindowBy({ start: 20, end: 40 }, -100, DURATION)).toEqual({
+ start: 0,
+ end: 20,
+ });
+ expect(panWindowBy({ start: 20, end: 40 }, 100, DURATION)).toEqual({
+ start: 80,
+ end: 100,
+ });
+ });
+});
+
+describe("followWindow", () => {
+ it("does nothing while the playhead is on screen", () => {
+ expect(followWindow({ start: 20, end: 40 }, 30, DURATION)).toBeNull();
+ });
+
+ it("does nothing when the whole video is on screen", () => {
+ expect(followWindow(fullWindow(DURATION), 30, DURATION)).toBeNull();
+ });
+
+ it("puts the playhead a fifth of the way in once it has left", () => {
+ const next = followWindow({ start: 20, end: 40 }, 41, DURATION);
+ expect(next).not.toBeNull();
+ if (!next) return;
+ expect(next.end - next.start).toBeCloseTo(20);
+ expect(fractionInWindow(41, next.start, next.end)).toBeCloseTo(0.2);
+ });
+
+ it("gives up rather than jitter when the window is already at the end", () => {
+ expect(followWindow({ start: 80, end: 100 }, 101, DURATION)).toBeNull();
+ });
+});
diff --git a/apps/web/__tests__/unit/waveform-envelope.test.ts b/apps/web/__tests__/unit/waveform-envelope.test.ts
new file mode 100644
index 000000000..68bc24ba7
--- /dev/null
+++ b/apps/web/__tests__/unit/waveform-envelope.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vitest";
+import {
+ envelopeFromVtt,
+ parseVttCues,
+ pseudoEnvelope,
+ WAVEFORM_BUCKETS,
+ WAVEFORM_FLOOR,
+} from "@/app/s/[videoId]/_components/timeline/waveform-envelope";
+
+const VTT = `WEBVTT
+
+1
+00:00:00.000 --> 00:00:10.000
+Talking at the start.
+
+2
+00:01:30.000 --> 00:01:40.000
+And again near the end.
+`;
+
+const DURATION = 100;
+const BUCKETS = 100;
+
+const bucketAt = (envelope: Float32Array, seconds: number) =>
+ envelope[Math.floor((seconds / DURATION) * envelope.length)] ?? 0;
+
+describe("parseVttCues", () => {
+ it("reads start and end times, milliseconds included", () => {
+ expect(parseVttCues(VTT)).toEqual([
+ { start: 0, end: 10 },
+ { start: 90, end: 100 },
+ ]);
+ });
+
+ it("accepts MM:SS.mmm cues", () => {
+ expect(parseVttCues("WEBVTT\n\n00:01.500 --> 00:02.250\nhi\n")).toEqual([
+ { start: 1.5, end: 2.25 },
+ ]);
+ });
+
+ it("returns nothing for empty or garbage input", () => {
+ expect(parseVttCues("")).toEqual([]);
+ expect(parseVttCues("WEBVTT\n\nnot a cue at all\n")).toEqual([]);
+ expect(parseVttCues("00:00:05.000 --> 00:00:01.000\nbackwards\n")).toEqual(
+ [],
+ );
+ });
+});
+
+describe("envelopeFromVtt", () => {
+ it("lands speech in the buckets the cues cover", () => {
+ const envelope = envelopeFromVtt(VTT, DURATION, BUCKETS);
+
+ expect(bucketAt(envelope, 5)).toBeGreaterThan(0.5);
+ expect(bucketAt(envelope, 95)).toBeGreaterThan(0.5);
+ // The silent middle stays near the floor.
+ expect(bucketAt(envelope, 50)).toBeLessThan(0.2);
+ });
+
+ it("normalises to 0-1 and never drops below the floor", () => {
+ const envelope = envelopeFromVtt(VTT, DURATION, BUCKETS);
+
+ expect(envelope).toHaveLength(BUCKETS);
+ for (const value of envelope) {
+ expect(value).toBeGreaterThanOrEqual(WAVEFORM_FLOOR - 1e-6);
+ expect(value).toBeLessThanOrEqual(1 + 1e-6);
+ }
+ expect(Math.max(...envelope)).toBeCloseTo(1, 5);
+ });
+
+ it("is deterministic", () => {
+ expect(Array.from(envelopeFromVtt(VTT, DURATION, BUCKETS))).toEqual(
+ Array.from(envelopeFromVtt(VTT, DURATION, BUCKETS)),
+ );
+ });
+
+ it("draws a flat floor when there is nothing to read", () => {
+ for (const input of ["", "WEBVTT\n\n", "}{ nonsense"]) {
+ const envelope = envelopeFromVtt(input, DURATION, BUCKETS);
+ expect(envelope).toHaveLength(BUCKETS);
+ for (const value of envelope)
+ expect(value).toBeCloseTo(WAVEFORM_FLOOR, 5);
+ }
+ });
+
+ it("gives up gracefully on a nonsense duration or bucket count", () => {
+ expect(envelopeFromVtt(VTT, 0, BUCKETS)).toHaveLength(BUCKETS);
+ expect(envelopeFromVtt(VTT, DURATION, 0)).toHaveLength(0);
+ expect(envelopeFromVtt(VTT, DURATION, Number.NaN)).toHaveLength(0);
+ });
+});
+
+describe("pseudoEnvelope", () => {
+ it("is deterministic per seed", () => {
+ expect(Array.from(pseudoEnvelope("video-a", DURATION, BUCKETS))).toEqual(
+ Array.from(pseudoEnvelope("video-a", DURATION, BUCKETS)),
+ );
+ expect(
+ Array.from(pseudoEnvelope("video-a", DURATION, BUCKETS)),
+ ).not.toEqual(Array.from(pseudoEnvelope("video-b", DURATION, BUCKETS)));
+ });
+
+ it("stays inside the floor and the ceiling", () => {
+ const envelope = pseudoEnvelope("video-a", DURATION, BUCKETS);
+ expect(envelope).toHaveLength(BUCKETS);
+ for (const value of envelope) {
+ expect(value).toBeGreaterThanOrEqual(WAVEFORM_FLOOR - 1e-6);
+ expect(value).toBeLessThanOrEqual(1 + 1e-6);
+ }
+ expect(Math.max(...envelope)).toBeCloseTo(1, 5);
+ });
+
+ it("varies across the strip rather than drawing a bar", () => {
+ const envelope = pseudoEnvelope("video-a", DURATION, BUCKETS);
+ const unique = new Set(Array.from(envelope));
+ expect(unique.size).toBeGreaterThan(BUCKETS / 2);
+ });
+
+ it("costs the same at any duration", () => {
+ expect(pseudoEnvelope("video-a", 30)).toHaveLength(WAVEFORM_BUCKETS);
+ expect(pseudoEnvelope("video-a", 3 * 3600)).toHaveLength(WAVEFORM_BUCKETS);
+ });
+});
diff --git a/apps/web/app/s/[videoId]/_components/timeline/filmstrip-math.ts b/apps/web/app/s/[videoId]/_components/timeline/filmstrip-math.ts
new file mode 100644
index 000000000..9e64a3118
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/filmstrip-math.ts
@@ -0,0 +1,145 @@
+/**
+ * Pure geometry/sampling math for the timeline filmstrip. Kept
+ * framework-free so the capture hook stays thin and this part stays unit-testable.
+ */
+
+/** Bounds on how many tiles the strip renders, regardless of width. */
+export const FILMSTRIP_MIN_TILES = 6;
+export const FILMSTRIP_MAX_TILES = 28;
+
+/** Ideal tile width in px; the count is derived from it, then clamped. */
+export const FILMSTRIP_TARGET_TILE_W = 104;
+
+/**
+ * HLS sources pay for every sample with a segment fetch, so they get fewer
+ * capture points than tiles; tiles in between borrow the nearest frame.
+ */
+export const FILMSTRIP_MAX_HLS_SAMPLES = 10;
+
+/** Frames one video keeps around before the oldest capture is dropped. */
+export const FRAME_POOL_MAX = 240;
+
+/** Bounds on the pool's time grid, in seconds. */
+export const POOL_QUANTUM_MIN = 0.5;
+export const POOL_QUANTUM_MAX = 30;
+
+/** How many tiles fit a strip of the given usable width. */
+export const filmstripTileCount = (usableWidth: number): number => {
+ if (!Number.isFinite(usableWidth) || usableWidth <= 0) return 0;
+ return Math.max(
+ FILMSTRIP_MIN_TILES,
+ Math.min(
+ FILMSTRIP_MAX_TILES,
+ Math.round(usableWidth / FILMSTRIP_TARGET_TILE_W),
+ ),
+ );
+};
+
+/**
+ * Spacing of the pool's time grid. Frames are captured onto it and shared by
+ * every zoom level, so zooming borrows what is already there instead of
+ * throwing the strip away and recapturing it.
+ */
+export const filmstripPoolQuantum = (duration: number): number => {
+ if (!Number.isFinite(duration) || duration <= 0) return POOL_QUANTUM_MIN;
+ return Math.min(
+ POOL_QUANTUM_MAX,
+ Math.max(POOL_QUANTUM_MIN, duration / (FILMSTRIP_MAX_TILES * 4)),
+ );
+};
+
+/** Grid slot a moment belongs to. Rounded, so nearby requests collapse. */
+export const quantizePoolTime = (time: number, quantum: number): number => {
+ if (!Number.isFinite(time) || !Number.isFinite(quantum) || quantum <= 0)
+ return 0;
+ return Math.round(Math.max(0, time) / quantum) * quantum;
+};
+
+/** One capture point per tile centre inside the window, clamped to the video. */
+export const filmstripWindowTimes = (
+ count: number,
+ start: number,
+ end: number,
+ duration: number,
+): number[] => {
+ const span = end - start;
+ if (count <= 0 || !Number.isFinite(span) || span <= 0) return [];
+ if (!Number.isFinite(duration) || duration <= 0) return [];
+
+ const times: number[] = [];
+ for (let index = 0; index < count; index++) {
+ const t = start + ((index + 0.5) / count) * span;
+ // Stay clear of the very end: the last frames of a stream often seek
+ // slowly or land on black.
+ times.push(Math.min(Math.max(t, 0), Math.max(0, duration - 0.1)));
+ }
+ return times;
+};
+
+/**
+ * Order in which samples are captured: a coarse pass (every 4th), then the
+ * halfway points, then the rest, so the strip sketches itself in and sharpens
+ * rather than filling left to right.
+ */
+export const filmstripCaptureOrder = (count: number): number[] => {
+ const order: number[] = [];
+ const seen = new Set<number>();
+ for (const stride of [4, 2, 1]) {
+ for (let index = 0; index < count; index += stride) {
+ if (seen.has(index)) continue;
+ seen.add(index);
+ order.push(index);
+ }
+ }
+ return order;
+};
+
+/**
+ * Nearest pooled moment within `tolerance`, or null. Lets a tile show a
+ * stale-but-near frame the instant the window moves, while the exact one is
+ * still being captured.
+ */
+export const nearestPooledTime = (
+ pooled: Iterable<number>,
+ time: number,
+ tolerance: number,
+): number | null => {
+ let best: number | null = null;
+ let bestDistance = Number.POSITIVE_INFINITY;
+ for (const candidate of pooled) {
+ const distance = Math.abs(candidate - time);
+ if (distance > tolerance || distance >= bestDistance) continue;
+ best = candidate;
+ bestDistance = distance;
+ }
+ return best;
+};
+
+/** How far a tile may reach into the pool before it gives up and shows nothing. */
+export const poolBorrowTolerance = (
+ quantum: number,
+ windowSpan: number,
+ tileCount: number,
+): number => {
+ const perTile = tileCount > 0 ? windowSpan / tileCount : quantum;
+ return Math.max(quantum, Number.isFinite(perTile) ? perTile : quantum);
+};
+
+/**
+ * Insert a frame, dropping the oldest capture once the pool is full. Eviction
+ * is insertion-order rather than access-order: borrowing happens inside a
+ * render memo, where touching the map would be a side effect.
+ */
+export const rememberFrame = (
+ frames: Map<number, string>,
+ time: number,
+ dataUrl: string,
+ max: number = FRAME_POOL_MAX,
+): void => {
+ frames.set(time, dataUrl);
+ while (frames.size > max) {
+ const oldest = frames.keys().next();
+ if (oldest.done) break;
+ frames.delete(oldest.value);
+ }
+};
diff --git a/apps/web/app/s/[videoId]/_components/timeline/timeline-constants.ts b/apps/web/app/s/[videoId]/_components/timeline/timeline-constants.ts
new file mode 100644
index 000000000..3cb760a47
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/timeline-constants.ts
@@ -0,0 +1,154 @@
+/**
+ * Geometry for the share-page timeline band.
+ *
+ * Everything horizontal is expressed against a rail that is inset by
+ * `RAIL_PAD_X` on both sides, so branches, ruler ticks, chapter ticks and the
+ * playhead all share one coordinate system (the same padded-calc trick the
+ * player uses for its comment stamps).
+ */
+
+/**
+ * Horizontal inset of the rail inside the band, in px. Zero: the strip runs
+ * edge to edge under the full-bleed video so the two read as one widescreen
+ * surface. Nodes near t=0 clamp themselves inward instead (`clampedRailLeft`).
+ */
+export const RAIL_PAD_X = 0;
+
+/**
+ * Height of the filmstrip scrubber, in px. The strip is the top band, fixed to
+ * the bottom edge of the video, so the film reads as a continuation of the
+ * frame above it.
+ */
+export const STRIP_H = 64;
+export const STRIP_H_MOBILE = 44;
+
+export const stripHeight = (compact: boolean): number =>
+ compact ? STRIP_H_MOBILE : STRIP_H;
+
+/**
+ * Height of the docked controls row under the strip, in px (`h-14`). Sized to
+ * the player's own control bar (size-8 buttons plus its py-3), which renders
+ * here through a portal while the timeline owns seeking.
+ */
+export const CONTROLS_H = 56;
+export const CONTROLS_H_MOBILE = 56;
+
+/**
+ * Height of the comments surface at the bottom of the band, in px. Branches
+ * hang *down* from its top edge (the anchor line the ruler draws), so it has to
+ * clear a lane-1 node: `LANE_STEM` plus half a node, plus a little air.
+ */
+export const COMMENTS_H = 88;
+export const COMMENTS_H_MOBILE = 80;
+
+export const commentsHeight = (compact: boolean): number =>
+ compact ? COMMENTS_H_MOBILE : COMMENTS_H;
+
+/**
+ * Deck height with the comments shelf open, in px. The band itself is
+ * content-sized (the shelf collapses to zero when nothing is on it); this is
+ * the ceiling, kept for anything budgeting viewport space.
+ */
+export const BAND_H = STRIP_H + CONTROLS_H + COMMENTS_H;
+export const BAND_H_MOBILE =
+ STRIP_H_MOBILE + CONTROLS_H_MOBILE + COMMENTS_H_MOBILE;
+
+/** Diameter of a branch node, in px. */
+export const NODE_SIZE = 30;
+
+/**
+ * Minimum horizontal distance between two branch nodes in the same lane before
+ * the later one is pushed to lane 1 (and eventually folded into a cluster).
+ */
+export const MIN_NODE_GAP = 34;
+export const MIN_NODE_GAP_MOBILE = 40;
+
+/** Distance from the anchor line down to the node centre, per lane, in px. */
+export const LANE_STEM: readonly [number, number] = [26, 62];
+export const LANE_STEM_MOBILE: readonly [number, number] = [22, 56];
+
+/** Hard cap on how many comments one cluster node represents. */
+export const CLUSTER_MAX = 9;
+
+/**
+ * Track width is quantised before it reaches the layout memo: resizing by a
+ * pixel must not rebuild every branch, and 24px is well under the gap that
+ * decides lane assignment.
+ */
+export const WIDTH_QUANTUM = 24;
+
+export const quantizeWidth = (width: number): number =>
+ Number.isFinite(width) && width > 0
+ ? Math.round(width / WIDTH_QUANTUM) * WIDTH_QUANTUM
+ : 0;
+
+/** Usable rail width for a given band width. */
+export const usableWidth = (trackWidth: number): number =>
+ Math.max(0, trackWidth - RAIL_PAD_X * 2);
+
+/**
+ * `left` value that places a 0-100 percentage inside the padded rail.
+ * Mirrors `CapVideoPlayer`'s comment-stamp positioning so both views agree.
+ */
+export const railLeft = (percent: number): string =>
+ `calc(${RAIL_PAD_X}px + (${percent}% * (100% - ${RAIL_PAD_X * 2}px) / 100%))`;
+
+/**
+ * `railLeft`, kept far enough inside the surface that a centred element of the
+ * given width survives the edge-to-edge rail without being clipped at 0% or
+ * 100%. Stems lean off-time by a few px at the extremes, which reads better
+ * than half a node.
+ */
+export const clampedRailLeft = (percent: number, width: number): string =>
+ `clamp(${width / 2}px, ${railLeft(percent)}, calc(100% - ${width / 2}px))`;
+
+/**
+ * Where a moment sits inside the current zoom window, as 0-1. Unclamped on
+ * purpose: callers cull or clamp depending on what they do off-window (the
+ * playhead hides, the ghost clamps).
+ */
+export const fractionInWindow = (
+ t: number,
+ start: number,
+ end: number,
+): number => {
+ const span = end - start;
+ if (!Number.isFinite(span) || span <= 0) return 0;
+ return (t - start) / span;
+};
+
+/**
+ * Time under a pointer, given the rect of an element that spans the whole band
+ * and the window that element is currently showing.
+ */
+export const timeFromClientX = (
+ clientX: number,
+ rect: { left: number; width: number },
+ start: number,
+ end: number,
+): number => {
+ const usable = usableWidth(rect.width);
+ const span = end - start;
+ if (usable <= 0 || !Number.isFinite(span) || span <= 0) return 0;
+ const x = Math.min(Math.max(clientX - rect.left - RAIL_PAD_X, 0), usable);
+ return start + (x / usable) * span;
+};
+
+/** Seek step for the rail's arrow keys, in seconds. */
+export const KEYBOARD_SEEK_STEP = 5;
+
+/** Span multiplier for the deck's zoom buttons. */
+export const ZOOM_STEP = 1.5;
+
+/** How close the playhead has to be for a branch to read as "now", in seconds. */
+export const ACTIVE_CUE_WINDOW = 2;
+
+/** Hover card timings, in ms. */
+export const CARD_OPEN_DELAY = 120;
+export const CARD_CLOSE_GRACE = 200;
+
+/** Hover card width, in px (`w-72`). */
+export const CARD_WIDTH = 288;
+
+/** Hover ghost preview card width, in px. */
+export const GHOST_CARD_WIDTH = 148;
diff --git a/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts b/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts
new file mode 100644
index 000000000..fb9fe9e3a
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts
@@ -0,0 +1,12 @@
+/** `M:SS`, or `H:MM:SS` once the video is an hour or longer. */
+export const formatClock = (seconds: number): string => {
+ const total =
+ Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
+ const secs = total % 60;
+ const mins = Math.floor(total / 60) % 60;
+ const hours = Math.floor(total / 3600);
+ const pad = (value: number) => String(value).padStart(2, "0");
+ return hours > 0
+ ? `${hours}:${pad(mins)}:${pad(secs)}`
+ : `${mins}:${pad(secs)}`;
+};
diff --git a/apps/web/app/s/[videoId]/_components/timeline/timeline-layout.ts b/apps/web/app/s/[videoId]/_components/timeline/timeline-layout.ts
new file mode 100644
index 000000000..11dd5403a
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/timeline-layout.ts
@@ -0,0 +1,148 @@
+/**
+ * Branch layout for the timeline band. Pure on purpose: no React, no DOM, no
+ * imports beyond the geometry constants, so the collision rules can be unit
+ * tested without a renderer.
+ */
+
+import { CLUSTER_MAX, MIN_NODE_GAP, usableWidth } from "./timeline-constants";
+import type { TimelineWindow } from "./timeline-window";
+
+/** Slack outside the window, as a share of its span, before a branch is culled. */
+const CULL_MARGIN = 0.02;
+
+/** The only fields the layout cares about. */
+export interface LayoutComment {
+ id: string;
+ timestamp: number | null;
+ createdAt: Date | string | number;
+}
+
+export type BranchLane = 0 | 1;
+
+export type BranchNode<C extends LayoutComment = LayoutComment> =
+ | { kind: "single"; id: string; t: number; lane: BranchLane; comment: C }
+ | { kind: "cluster"; id: string; t: number; lane: BranchLane; comments: C[] };
+
+const toMillis = (value: Date | string | number): number => {
+ if (value instanceof Date) return value.getTime();
+ const parsed = new Date(value).getTime();
+ return Number.isFinite(parsed) ? parsed : 0;
+};
+
+const hasTime = <C extends LayoutComment>(
+ comment: C,
+): comment is C & { timestamp: number } =>
+ typeof comment.timestamp === "number" && Number.isFinite(comment.timestamp);
+
+/**
+ * Place every timestamped comment visible in `window` on one of two lanes,
+ * folding anything that still collides into the node before it.
+ *
+ * Greedy and single-pass: lane 0 if it clears the last lane-0 node, else lane 1
+ * if it clears the last lane-1 node, else it joins the most recent node (which
+ * becomes a cluster). Clusters stop growing at `CLUSTER_MAX` and a fresh one
+ * takes over, so a hundred comments on the same second render as a handful of
+ * stacks rather than one unbounded pile.
+ *
+ * Collision distances are measured against the window, not the video, so
+ * zooming in genuinely separates comments that were stacked when zoomed out.
+ */
+export function layoutBranches<C extends LayoutComment>(
+ comments: readonly C[],
+ window: TimelineWindow,
+ trackWidth: number,
+ minNodeGap: number = MIN_NODE_GAP,
+): BranchNode<C>[] {
+ if (!comments.length) return [];
+ const span = window.end - window.start;
+ if (!Number.isFinite(span) || span <= 0) return [];
+
+ const margin = span * CULL_MARGIN;
+ const from = window.start - margin;
+ const to = window.end + margin;
+
+ const placed = comments
+ .filter(hasTime)
+ .filter((comment) => comment.timestamp >= from && comment.timestamp <= to)
+ .sort((a, b) => {
+ if (a.timestamp !== b.timestamp) return a.timestamp - b.timestamp;
+ return toMillis(a.createdAt) - toMillis(b.createdAt);
+ });
+ if (!placed.length) return [];
+
+ const usable = usableWidth(trackWidth);
+ // Before the band has been measured there is no collision to resolve, so
+ // everything lands on lane 0 and re-lays out once the observer fires.
+ const minGapT = usable > 0 ? (minNodeGap / usable) * span : 0;
+
+ const nodes: BranchNode<C>[] = [];
+ const lastInLane: [number, number] = [
+ Number.NEGATIVE_INFINITY,
+ Number.NEGATIVE_INFINITY,
+ ];
+
+ const push = (comment: C & { timestamp: number }, lane: BranchLane) => {
+ nodes.push({
+ kind: "single",
+ id: comment.id,
+ t: comment.timestamp,
+ lane,
+ comment,
+ });
+ lastInLane[lane] = comment.timestamp;
+ };
+
+ for (const comment of placed) {
+ const t = comment.timestamp;
+
+ if (t - lastInLane[0] >= minGapT) {
+ push(comment, 0);
+ continue;
+ }
+ if (t - lastInLane[1] >= minGapT) {
+ push(comment, 1);
+ continue;
+ }
+
+ // Comments are sorted ascending and every node keeps its first comment's
+ // time, so the last node pushed is always the nearest one to fold into.
+ const last = nodes[nodes.length - 1];
+ if (!last) {
+ push(comment, 0);
+ continue;
+ }
+
+ if (last.kind === "single") {
+ nodes[nodes.length - 1] = {
+ kind: "cluster",
+ id: last.id,
+ t: last.t,
+ lane: last.lane,
+ comments: [last.comment, comment],
+ };
+ continue;
+ }
+
+ if (last.comments.length < CLUSTER_MAX) {
+ last.comments.push(comment);
+ continue;
+ }
+
+ // Full: start a new stack in the same lane and measure future gaps from it.
+ nodes.push({
+ kind: "cluster",
+ id: comment.id,
+ t,
+ lane: last.lane,
+ comments: [comment],
+ });
+ lastInLane[last.lane] = t;
+ }
+
+ return nodes;
+}
+
+/** Every comment a node stands for, single or cluster. */
+export const branchComments = <C extends LayoutComment>(
+ node: BranchNode<C>,
+): C[] => (node.kind === "single" ? [node.comment] : node.comments);
diff --git a/apps/web/app/s/[videoId]/_components/timeline/timeline-window.ts b/apps/web/app/s/[videoId]/_components/timeline/timeline-window.ts
new file mode 100644
index 000000000..48d55e73a
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/timeline-window.ts
@@ -0,0 +1,119 @@
+/**
+ * The zoom window: the slice of the video the band is currently drawing.
+ *
+ * Pure on purpose — no React, no DOM — so the "time under the cursor stays
+ * under the cursor" invariant can be unit tested without a renderer.
+ */
+
+/** Narrowest the window can get, in seconds (or the whole video if shorter). */
+export const MIN_WINDOW_S = 10;
+
+export interface TimelineWindow {
+ start: number;
+ end: number;
+}
+
+const isDuration = (value: number): boolean =>
+ Number.isFinite(value) && value > 0;
+
+export const fullWindow = (duration: number): TimelineWindow => ({
+ start: 0,
+ end: isDuration(duration) ? duration : 0,
+});
+
+export const minWindowSpan = (duration: number): number =>
+ isDuration(duration) ? Math.min(MIN_WINDOW_S, duration) : 0;
+
+/** Force a window inside `[0, duration]` without letting it collapse. */
+export const clampWindow = (
+ window: TimelineWindow,
+ duration: number,
+): TimelineWindow => {
+ if (!isDuration(duration)) return { start: 0, end: 0 };
+
+ const requested = window.end - window.start;
+ const span = Number.isFinite(requested)
+ ? Math.min(duration, Math.max(minWindowSpan(duration), requested))
+ : duration;
+
+ const start = Number.isFinite(window.start)
+ ? Math.min(Math.max(window.start, 0), duration - span)
+ : 0;
+
+ return { start, end: start + span };
+};
+
+export const isFullWindow = (
+ window: TimelineWindow,
+ duration: number,
+): boolean => {
+ if (!isDuration(duration)) return true;
+ return window.end - window.start >= duration - 0.001;
+};
+
+/**
+ * Zoom around a point in time. `factor` above 1 zooms in (the span shrinks);
+ * `focusT` keeps its position within the window, so the frame under the
+ * pointer does not slide away while the wheel turns.
+ */
+export const zoomWindowAt = (
+ window: TimelineWindow,
+ factor: number,
+ focusT: number,
+ duration: number,
+): TimelineWindow => {
+ if (!isDuration(duration)) return { start: 0, end: 0 };
+ if (!Number.isFinite(factor) || factor <= 0)
+ return clampWindow(window, duration);
+
+ const current = clampWindow(window, duration);
+ const span = current.end - current.start;
+ if (span <= 0) return current;
+
+ const focus = Math.min(Math.max(focusT, 0), duration);
+ const anchor = Math.min(Math.max((focus - current.start) / span, 0), 1);
+ const nextSpan = Math.min(
+ duration,
+ Math.max(minWindowSpan(duration), span / factor),
+ );
+ const start = focus - anchor * nextSpan;
+
+ return clampWindow({ start, end: start + nextSpan }, duration);
+};
+
+export const panWindowBy = (
+ window: TimelineWindow,
+ deltaSeconds: number,
+ duration: number,
+): TimelineWindow => {
+ if (!Number.isFinite(deltaSeconds)) return clampWindow(window, duration);
+ const current = clampWindow(window, duration);
+ return clampWindow(
+ { start: current.start + deltaSeconds, end: current.end + deltaSeconds },
+ duration,
+ );
+};
+
+/** Where the playhead sits inside the window once it has been followed. */
+export const FOLLOW_ANCHOR = 0.2;
+
+/**
+ * Window that puts `time` at `FOLLOW_ANCHOR` of the span, or null when the
+ * playhead is already inside the window (or the whole video is on screen).
+ */
+export const followWindow = (
+ window: TimelineWindow,
+ time: number,
+ duration: number,
+): TimelineWindow | null => {
+ if (!isDuration(duration)) return null;
+ const current = clampWindow(window, duration);
+ if (isFullWindow(current, duration)) return null;
+ if (time >= current.start && time <= current.end) return null;
+
+ const span = current.end - current.start;
+ const start = time - span * FOLLOW_ANCHOR;
+ const next = clampWindow({ start, end: start + span }, duration);
+ if (Math.abs(next.start - current.start) < 0.001) return null;
+ return next;
+};
diff --git a/apps/web/app/s/[videoId]/_components/timeline/useFilmstripFrames.ts b/apps/web/app/s/[videoId]/_components/timeline/useFilmstripFrames.ts
new file mode 100644
index 000000000..93c91e238
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/useFilmstripFrames.ts
@@ -0,0 +1,358 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { captureVideoFrameDataUrl } from "../video-frame-thumbnail";
+import {
+ FILMSTRIP_MAX_HLS_SAMPLES,
+ filmstripCaptureOrder,
+ filmstripPoolQuantum,
+ filmstripWindowTimes,
+ nearestPooledTime,
+ poolBorrowTolerance,
+ quantizePoolTime,
+ rememberFrame,
+} from "./filmstrip-math";
+
+/**
+ * Where the filmstrip's frames come from. `native` is anything a bare
+ * `<video>` can decode (the result.mp4 of instant recordings); `hls` playlists
+ * go through hls.js, which the share page already ships for those videos.
+ */
+export interface FilmstripSource {
+ src: string;
+ kind: "native" | "hls";
+}
+
+interface FramePool {
+ /** Quantised time -> data URL. */
+ frames: Map<number, string>;
+ /** Quantised times already attempted, captured or not. */
+ settled: Set<number>;
+}
+
+/**
+ * One pool per source, kept at module level. Frames survive unmounts, view
+ * toggles, resizes and zooms: the strip is only ever recomposed from what is
+ * already here, so it never visibly regenerates.
+ */
+const pools = new Map<string, FramePool>();
+const POOL_MAX_SOURCES = 6;
+
+const poolFor = (src: string): FramePool => {
+ const existing = pools.get(src);
+ if (existing) return existing;
+ if (pools.size >= POOL_MAX_SOURCES) {
+ const oldest = pools.keys().next();
+ if (!oldest.done) pools.delete(oldest.value);
+ }
+ const created: FramePool = { frames: new Map(), settled: new Set() };
+ pools.set(src, created);
+ return created;
+};
+
+/** Debounce before a window change turns into capture work. */
+const SETTLE_MS = 300;
+
+function scheduleIdle(callback: () => void, timeout = 800) {
+ const idleWindow = window as Window & {
+ requestIdleCallback?: (
+ callback: () => void,
+ options?: { timeout?: number },
+ ) => number;
+ cancelIdleCallback?: (id: number) => void;
+ };
+ if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {
+ const id = idleWindow.requestIdleCallback(callback, { timeout });
+ return () => idleWindow.cancelIdleCallback?.(id);
+ }
+ const id = window.setTimeout(callback, 250);
+ return () => window.clearTimeout(id);
+}
+
+const waitForNextFrame = () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+
+function waitForVideoMetadata(video: HTMLVideoElement) {
+ if (video.readyState >= 1) return Promise.resolve(true);
+ return new Promise<boolean>((resolve) => {
+ let timeoutId = 0;
+ const settle = (value: boolean) => {
+ window.clearTimeout(timeoutId);
+ video.removeEventListener("loadedmetadata", handleLoaded);
+ video.removeEventListener("error", handleError);
+ resolve(value);
+ };
+ const handleLoaded = () => settle(true);
+ const handleError = () => settle(false);
+ timeoutId = window.setTimeout(() => settle(false), 8000);
+ video.addEventListener("loadedmetadata", handleLoaded);
+ video.addEventListener("error", handleError);
+ });
+}
+
+function seekForCapture(video: HTMLVideoElement, time: number) {
+ return new Promise<boolean>((resolve) => {
+ let timeoutId = 0;
+ let frameId = 0;
+ const settle = (value: boolean) => {
+ window.clearTimeout(timeoutId);
+ cancelAnimationFrame(frameId);
+ video.removeEventListener("seeked", handleSeeked);
+ video.removeEventListener("error", handleError);
+ resolve(value);
+ };
+ const handleSeeked = () => settle(true);
+ const handleError = () => settle(false);
+
+ timeoutId = window.setTimeout(() => settle(false), 4000);
+ video.addEventListener("seeked", handleSeeked);
+ video.addEventListener("error", handleError);
+ try {
+ video.currentTime = time;
+ if (video.readyState >= 2 && Math.abs(video.currentTime - time) <= 0.08) {
+ frameId = requestAnimationFrame(() => settle(true));
+ }
+ } catch {
+ settle(false);
+ }
+ });
+}
+
+interface HlsLike {
+ loadSource(src: string): void;
+ attachMedia(video: HTMLVideoElement): void;
+ destroy(): void;
+}
+
+interface UseFilmstripFramesOptions {
+ source: FilmstripSource | null;
+ duration: number;
+ /** Tiles the strip will render; sampling may be sparser for HLS. */
+ tileCount: number;
+ /** Tile width / tile height, so captures are cropped once, correctly. */
+ tileAspect: number;
+ windowStart: number;
+ windowEnd: number;
+}
+
+export interface FilmstripFrames {
+ /** One entry per rendered tile; null while nothing near enough exists yet. */
+ tiles: readonly (string | null)[];
+}
+
+const EMPTY: FilmstripFrames = { tiles: [] };
+
+/**
+ * Lazily builds the strip's frames off a second, muted, invisible video
+ * element — never the one the viewer is watching.
+ *
+ * Captured frames land on a per-source time grid rather than in a per-layout
+ * array, so a resize, a zoom or a view toggle recomposes the strip out of the
+ * pool immediately and only captures what is genuinely missing. Nothing in
+ * here depends on the playback position.
+ */
+export function useFilmstripFrames({
+ source,
+ duration,
+ tileCount,
+ tileAspect,
+ windowStart,
+ windowEnd,
+}: UseFilmstripFramesOptions): FilmstripFrames {
+ // Bumped on every capture flush; the tiles memo below reads through it.
+ const [poolVersion, setPoolVersion] = useState(0);
+ // The capture loop is re-entrant per (src, window, count); everything else
+ // (aspect drift from tile rounding) must not restart it.
+ const aspectRef = useRef(tileAspect);
+ aspectRef.current = tileAspect;
+
+ const src = source?.src ?? null;
+ const kind = source?.kind ?? "native";
+
+ useEffect(() => {
+ if (!src || tileCount <= 0 || !Number.isFinite(duration) || duration <= 0)
+ return;
+
+ const pool = poolFor(src);
+ const quantum = filmstripPoolQuantum(duration);
+ const full = windowEnd - windowStart >= duration - 0.001;
+
+ let cancelled = false;
+ let video: HTMLVideoElement | null = null;
+ let hls: HlsLike | null = null;
+ let cancelIdle: (() => void) | null = null;
+
+ const cleanupMedia = () => {
+ hls?.destroy();
+ hls = null;
+ if (video) {
+ video.removeAttribute("src");
+ video.load();
+ video = null;
+ }
+ };
+
+ const missingTimes = (): number[] => {
+ const wanted = filmstripWindowTimes(
+ tileCount,
+ windowStart,
+ windowEnd,
+ duration,
+ );
+ const tolerance = poolBorrowTolerance(
+ quantum,
+ windowEnd - windowStart,
+ tileCount,
+ );
+ const order = full
+ ? filmstripCaptureOrder(wanted.length)
+ : wanted.map((_, index) => index);
+
+ const times: number[] = [];
+ const queued = new Set<number>();
+ for (const index of order) {
+ const time = wanted[index];
+ if (time === undefined) continue;
+ if (nearestPooledTime(pool.frames.keys(), time, tolerance) !== null)
+ continue;
+ const slot = quantizePoolTime(time, quantum);
+ if (queued.has(slot) || pool.settled.has(slot)) continue;
+ queued.add(slot);
+ times.push(time);
+ }
+ return kind === "hls" ? times.slice(0, FILMSTRIP_MAX_HLS_SAMPLES) : times;
+ };
+
+ const settleTimer = window.setTimeout(() => {
+ const pending = missingTimes();
+ if (!pending.length) return;
+
+ cancelIdle = scheduleIdle(() => {
+ void (async () => {
+ video = document.createElement("video");
+ video.crossOrigin = "anonymous";
+ video.muted = true;
+ video.playsInline = true;
+ video.preload = "metadata";
+
+ if (
+ kind === "hls" &&
+ !video.canPlayType("application/vnd.apple.mpegurl")
+ ) {
+ try {
+ const HlsModule = (await import("hls.js")).default;
+ if (cancelled || !HlsModule.isSupported()) {
+ cleanupMedia();
+ return;
+ }
+ const instance = new HlsModule({
+ // A thumbnail run wants one segment around each seek point,
+ // not a playback buffer.
+ startLevel: 0,
+ maxBufferLength: 4,
+ maxMaxBufferLength: 8,
+ backBufferLength: 0,
+ });
+ instance.loadSource(src);
+ instance.attachMedia(video);
+ hls = instance;
+ } catch {
+ cleanupMedia();
+ return;
+ }
+ } else {
+ video.src = src;
+ video.load();
+ }
+
+ const hasMetadata = await waitForVideoMetadata(video);
+ if (cancelled || !hasMetadata) {
+ cleanupMedia();
+ return;
+ }
+
+ const captureWidth = 168;
+ const captureHeight = Math.max(
+ 48,
+ Math.round(captureWidth / Math.max(0.5, aspectRef.current)),
+ );
+
+ let sinceFlush = 0;
+ for (const time of pending) {
+ if (cancelled) break;
+ const slot = quantizePoolTime(time, quantum);
+ if (pool.frames.has(slot)) continue;
+
+ const seeked = await seekForCapture(video, time);
+ if (cancelled) break;
+ pool.settled.add(slot);
+ if (seeked) {
+ const frame = captureVideoFrameDataUrl({
+ video,
+ width: captureWidth,
+ height: captureHeight,
+ quality: 0.6,
+ });
+ if (frame) {
+ rememberFrame(pool.frames, slot, frame);
+ sinceFlush += 1;
+ if (sinceFlush >= 3) {
+ sinceFlush = 0;
+ setPoolVersion((version) => version + 1);
+ }
+ }
+ }
+ await waitForNextFrame();
+ }
+
+ if (!cancelled && sinceFlush > 0) {
+ setPoolVersion((version) => version + 1);
+ }
+ cleanupMedia();
+ })();
+ });
+ }, SETTLE_MS);
+
+ return () => {
+ cancelled = true;
+ window.clearTimeout(settleTimer);
+ cancelIdle?.();
+ cleanupMedia();
+ };
+ }, [src, kind, tileCount, duration, windowStart, windowEnd]);
+
+ return useMemo<FilmstripFrames>(() => {
+ if (!src || tileCount <= 0 || !Number.isFinite(duration) || duration <= 0)
+ return EMPTY;
+
+ // poolVersion is the whole point of this dependency: the pool is mutable,
+ // so a capture flush is what tells the memo to recompose.
+ void poolVersion;
+
+ const pool = pools.get(src);
+ const wanted = filmstripWindowTimes(
+ tileCount,
+ windowStart,
+ windowEnd,
+ duration,
+ );
+ if (!pool || pool.frames.size === 0)
+ return { tiles: wanted.map(() => null) };
+
+ const tolerance = poolBorrowTolerance(
+ filmstripPoolQuantum(duration),
+ windowEnd - windowStart,
+ tileCount,
+ );
+ const keys = Array.from(pool.frames.keys());
+
+ return {
+ tiles: wanted.map((time) => {
+ const slot = nearestPooledTime(keys, time, tolerance);
+ return slot === null ? null : (pool.frames.get(slot) ?? null);
+ }),
+ };
+ }, [src, tileCount, duration, windowStart, windowEnd, poolVersion]);
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/useTimelineWaveform.ts b/apps/web/app/s/[videoId]/_components/timeline/useTimelineWaveform.ts
new file mode 100644
index 000000000..ae384e789
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/useTimelineWaveform.ts
@@ -0,0 +1,38 @@
+"use client";
+
+import type { Video } from "@cap/web-domain";
+import { useTranscript } from "hooks/use-transcript";
+import { useMemo } from "react";
+import {
+ envelopeFromVtt,
+ parseVttCues,
+ pseudoEnvelope,
+ WAVEFORM_BUCKETS,
+} from "./waveform-envelope";
+
+interface UseTimelineWaveformOptions {
+ videoId: Video.VideoId;
+ transcriptionStatus?: string | null;
+ duration: number;
+}
+
+/**
+ * The filmstrip's amplitude envelope. Rides the transcript query the captions
+ * path already runs (same react-query key, so this costs no extra request) and
+ * falls back to a seeded shape when there is no transcript to read.
+ */
+export function useTimelineWaveform({
+ videoId,
+ transcriptionStatus,
+ duration,
+}: UseTimelineWaveformOptions): Float32Array | null {
+ const { data } = useTranscript(videoId, transcriptionStatus);
+
+ return useMemo(() => {
+ if (!Number.isFinite(duration) || duration <= 0) return null;
+ if (typeof data === "string" && parseVttCues(data).length > 0) {
+ return envelopeFromVtt(data, duration, WAVEFORM_BUCKETS);
+ }
+ return pseudoEnvelope(videoId, duration, WAVEFORM_BUCKETS);
+ }, [data, duration, videoId]);
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/waveform-envelope.ts b/apps/web/app/s/[videoId]/_components/timeline/waveform-envelope.ts
new file mode 100644
index 000000000..a3589a122
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/waveform-envelope.ts
@@ -0,0 +1,185 @@
+/**
+ * Amplitude envelopes for the filmstrip's waveform overlay.
+ *
+ * Framework-free and deterministic: the same video always draws the same
+ * shape, in every tab, on every render. The master resolution is fixed rather
+ * than derived from the duration, so a three-hour recording costs exactly what
+ * a thirty-second one does.
+ */
+
+/** Master envelope resolution. Fixed regardless of duration. */
+export const WAVEFORM_BUCKETS = 2048;
+
+/** Floor applied after normalisation, so silence still draws a thin line. */
+export const WAVEFORM_FLOOR = 0.08;
+
+export interface VttCue {
+ start: number;
+ end: number;
+}
+
+const CUE_LINE =
+ /(\d{1,2}:)?(\d{1,2}):(\d{1,2})([.,]\d{1,3})?\s*-->\s*(\d{1,2}:)?(\d{1,2}):(\d{1,2})([.,]\d{1,3})?/;
+
+const toSeconds = (
+ hours: string | undefined,
+ minutes: string | undefined,
+ seconds: string | undefined,
+ fraction: string | undefined,
+): number | null => {
+ const h = hours ? Number.parseInt(hours, 10) : 0;
+ const m = minutes ? Number.parseInt(minutes, 10) : Number.NaN;
+ const s = seconds ? Number.parseInt(seconds, 10) : Number.NaN;
+ if (!Number.isFinite(h) || !Number.isFinite(m) || !Number.isFinite(s))
+ return null;
+ const ms = fraction ? Number.parseFloat(`0.${fraction.slice(1)}`) : 0;
+ return h * 3600 + m * 60 + s + (Number.isFinite(ms) ? ms : 0);
+};
+
+/**
+ * Cue time ranges only. `parseVTT` in `_components/utils/transcript-utils`
+ * drops end times and milliseconds, which are exactly what an envelope needs.
+ */
+export function parseVttCues(vtt: string): VttCue[] {
+ if (typeof vtt !== "string" || !vtt.includes("-->")) return [];
+
+ const cues: VttCue[] = [];
+ for (const line of vtt.split("\n")) {
+ if (!line.includes("-->")) continue;
+ const match = CUE_LINE.exec(line);
+ if (!match) continue;
+
+ const start = toSeconds(
+ match[1]?.slice(0, -1),
+ match[2],
+ match[3],
+ match[4],
+ );
+ const end = toSeconds(match[5]?.slice(0, -1), match[6], match[7], match[8]);
+ if (start === null || end === null) continue;
+ if (end <= start) continue;
+ cues.push({ start, end });
+ }
+ return cues;
+}
+
+/** FNV-1a, the same hash the voice-note waveform uses. */
+const hashString = (value: string): number => {
+ let hash = 0x811c9dc5;
+ for (let index = 0; index < value.length; index += 1) {
+ hash ^= value.charCodeAt(index);
+ hash = Math.imul(hash, 0x01000193) >>> 0;
+ }
+ return hash || 0x9e3779b9;
+};
+
+/** Stable 0-1 noise for one bucket, so covered spans look like audio. */
+const bucketNoise = (index: number, salt: number): number => {
+ let state = (Math.imul(index + 1, 0x9e3779b1) ^ salt) >>> 0;
+ state ^= state >>> 15;
+ state = Math.imul(state, 0x85ebca6b) >>> 0;
+ state ^= state >>> 13;
+ state = Math.imul(state, 0xc2b2ae35) >>> 0;
+ state ^= state >>> 16;
+ return state / 0xffffffff;
+};
+
+const smooth = (values: Float32Array, radius: number): Float32Array => {
+ if (radius <= 0) return values;
+ const length = values.length;
+ const prefix = new Float64Array(length + 1);
+ for (let index = 0; index < length; index += 1) {
+ prefix[index + 1] = (prefix[index] ?? 0) + (values[index] ?? 0);
+ }
+
+ const out = new Float32Array(length);
+ for (let index = 0; index < length; index += 1) {
+ const from = Math.max(0, index - radius);
+ const to = Math.min(length - 1, index + radius);
+ out[index] =
+ ((prefix[to + 1] ?? 0) - (prefix[from] ?? 0)) / (to - from + 1);
+ }
+ return out;
+};
+
+/** Scale into 0-1 and lift onto the floor. */
+const normalize = (values: Float32Array): Float32Array => {
+ let max = 0;
+ for (const value of values) if (value > max) max = value;
+ const out = new Float32Array(values.length);
+ for (let index = 0; index < values.length; index += 1) {
+ const scaled = max > 0 ? (values[index] ?? 0) / max : 0;
+ out[index] = WAVEFORM_FLOOR + (1 - WAVEFORM_FLOOR) * scaled;
+ }
+ return out;
+};
+
+/**
+ * Speech coverage from a transcript, roughened into something that reads as
+ * audio: cue ranges mark which buckets carry voice, per-bucket noise gives the
+ * covered spans texture instead of solid blocks, and a short moving average
+ * rounds the edges off.
+ */
+export function envelopeFromVtt(
+ vtt: string,
+ duration: number,
+ buckets: number = WAVEFORM_BUCKETS,
+): Float32Array {
+ const count =
+ Number.isFinite(buckets) && buckets > 0 ? Math.floor(buckets) : 0;
+ if (count <= 0) return new Float32Array(0);
+ if (!Number.isFinite(duration) || duration <= 0)
+ return normalize(new Float32Array(count));
+
+ const raw = new Float32Array(count);
+ const salt = hashString(`vtt:${count}`);
+
+ for (const cue of parseVttCues(vtt)) {
+ const from = Math.max(0, Math.floor((cue.start / duration) * count));
+ const to = Math.min(count - 1, Math.ceil((cue.end / duration) * count));
+ for (let index = from; index <= to; index += 1) {
+ const noise = bucketNoise(index, salt);
+ const detail = (Math.sin(index * 0.7) + 1) / 2;
+ raw[index] = Math.max(
+ raw[index] ?? 0,
+ 0.5 + 0.32 * noise + 0.18 * detail,
+ );
+ }
+ }
+
+ return normalize(smooth(raw, 2));
+}
+
+/**
+ * Seeded stand-in for videos with no transcript. Value noise smoothed into
+ * phrases, in the same visual family as the voice-note `pseudoWaveform`: two
+ * out-of-phase sines for the body, a noise stream for grain.
+ */
+export function pseudoEnvelope(
+ seed: string,
+ duration: number,
+ buckets: number = WAVEFORM_BUCKETS,
+): Float32Array {
+ const count =
+ Number.isFinite(buckets) && buckets > 0 ? Math.floor(buckets) : 0;
+ if (count <= 0) return new Float32Array(0);
+
+ const hash = hashString(seed);
+ const phase = ((hash % 1000) / 1000) * Math.PI * 2;
+ const phrases = Math.min(
+ 90,
+ Math.max(6, Math.round((Number.isFinite(duration) ? duration : 60) / 6)),
+ );
+
+ const raw = new Float32Array(count);
+ for (let index = 0; index < count; index += 1) {
+ const t = count === 1 ? 0.5 : index / (count - 1);
+ const body = (Math.sin(phase + t * Math.PI * 2 * phrases) + 1) / 2;
+ const swell = (Math.sin(phase * 0.7 + t * Math.PI * 2) + 1) / 2;
+ const noise = bucketNoise(index, hash);
+ const taper = 0.7 + 0.3 * Math.sin(Math.PI * t);
+ raw[index] = (0.42 * body + 0.3 * swell + 0.28 * noise) * taper;
+ }
+
+ return normalize(smooth(raw, 3));
+}