// THE PLAY VIEW'S CLOCK (umtool/docs/knobs.md, "Play the cut"): a whole cut -- or a take -- // played in the browser on ONE continuous cut clock, clip after clip, with the // live preview's chrome over it. Pure: no DOM, no React, so the arithmetic is // unit-tested (playCut.test.mjs) and the page only applies it. // // The clock is the estimate's (the same schedule the live preview composes // its pages from, deck.mjs estimateSchedule): segment i starts at // `segments[i].start` and lasts `duration` (its hold included); consecutive // segments overlap by the crossfade. The page plays them as HARD CUTS at the // middle of each overlap -- where the deck hands its title over -- so a clip // plays from its play window's first source second (its segment's start) to // the second at that midpoint, and the next clip enters that far into its // own. A clip's source second at cut second t is liveClock.mjs's rule // (`seg.start + (src − playWindow.from)`); past its footage (a carrying // clip's hold) its last frame holds. import { clockText, livePlayWindow } from "./liveClock.mjs"; import { gappedLength, gapsOf, gapsWithin, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps"; // GAPS INSIDE A CLIP (umtool-report-to-video gaps.mjs): a clip's `gaps` are // source seconds its segment leaves out, so it plays as one item of jump cuts. // An item's `clip.gaps` (only when it has any) are those inside its play // window -- the render's (the cut-points route's `gaps`, on the frame grid) // with its edges, else the manifest's -- and every cut ↔ source mapping below // goes through them: the footage is the kept seconds, and a second inside a // gap plays at its join. // THE RENDER'S EDGES (`cuts`, lib/report/cutPoints.mjs): the build snaps every // clip edge to a silence, so the clip it renders is longer or shorter than // its play window -- by up to a second at each edge on the Huck cut. Given // them, the plan plays each clip from the render's first source second to its // last, and every later entry moves by what the clips before it gained or // lost: Play's clock is the render's. The chrome was composed on the // estimate's clock, so each item keeps its estimate (`est`), and // `chromeTime` maps a Play second to the second the pages are seeked to: by // SOURCE second inside a clip (a stamp lands on its claim's word, as the // render lands it), held at the item's own handover where the render plays // more than the estimate did. /** @typedef {{ id: string, start: number, duration: number, hold?: number }} Segment */ /** * @typedef {{ * id: string, index: number, type: string, * start: number, end: number, the segment, in the cut's seconds * from: number, to: number, what the page shows of it: midpoint to midpoint * clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number, gaps?: Array<{ from: number, to: number }> }, * est?: { start: number, end: number, from: number, to: number, sourceFrom?: number, sourceTo?: number, playEnd?: number }, * with the render's edges: the item on the estimate's clock * }} PlayItem */ const fin = (v) => typeof v === "number" && Number.isFinite(v); const round = (v) => Math.round(v * 1000) / 1000; /** * @typedef {{ cutStart: number, cutEnd: number, footage?: number, snapped?: { start: boolean, end: boolean }, * sound?: [number, number], gainDb?: number, audio?: Record, muteFrom?: number, soundFrom?: number, * gaps?: Array<{ from: number, to: number }> }} RenderCut */ /** * The cut as the page plays it: one item per segment, in the cut's order. * `entries` are the cut's timeline entries (the variant's), matched to the * segments by id; a segment with no entry plays as a placeholder. With * `cuts` (id → the render's cut, cutPoints.mjs), each clip plays the render's * edges and the clock is re-timed by them (see THE RENDER'S EDGES above). * * @param {Segment[]} segments * @param {Array>} entries * @param {{ leadIn?: number, cuts?: Map | Record | null }} [opts] * @returns {{ items: PlayItem[], total: number, edges: "estimate" | "render" }} */ export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) { const est = estimatePlan(segments, entries, { leadIn }); if (!cuts) return est; const cutOf = (id) => (cuts instanceof Map ? cuts.get(id) : cuts[id]) ?? null; let shift = 0; const items = est.items.map((it) => { const before = shift; const c = it.clip ? cutOf(it.id) : null; const ok = !!c && fin(c.cutStart) && fin(c.cutEnd) && c.cutEnd > c.cutStart; const estAt = estOf(it); if (!ok) { return { ...it, start: round(it.start + before), end: round(it.end + before), from: round(it.from + before), to: round(it.to + before), clip: it.clip ? { ...it.clip, playEnd: round(it.clip.playEnd + before) } : null, est: estAt }; } // Its gaps as the render takes them out (the route's), else none. const gaps = Array.isArray(c.gaps) ? gapsWithin(c.gaps, c.cutStart, c.cutEnd) : []; // Its length in the cut: the encode's whole frames when the route said (`footage`), else the span (less its gaps). const foot = fin(c.footage) && /** @type {number} */ (c.footage) > 0 ? /** @type {number} */ (c.footage) : gappedLength(c.cutStart, c.cutEnd, gaps); // The estimate's segment is its footage (at least a second) and its hold; the render's, its cut and the same hold. const delta = foot + it.clip.hold - (it.end - it.start); shift += delta; const start = round(it.start + before); return { ...it, start, end: round(it.end + before + delta), from: round(it.from + before), to: round(it.to + before + delta), clip: { sourceFrom: c.cutStart, sourceTo: c.cutEnd, playEnd: round(start + foot), hold: it.clip.hold, ...(Array.isArray(c.sound) ? { sound: c.sound } : {}), ...(fin(c.gainDb) ? { gainDb: c.gainDb } : {}), ...(c.audio ? { audio: c.audio } : {}), ...(c.snapped ? { snapped: c.snapped } : {}), ...(fin(c.muteFrom) ? { muteFrom: c.muteFrom } : {}), ...(fin(c.soundFrom) ? { soundFrom: c.soundFrom } : {}), ...(gaps.length ? { gaps } : {}), }, est: estAt, }; }); return { items, total: items.length ? items[items.length - 1].end : 0, edges: "render" }; } /** * The second the chrome (composed on the estimate's clock) is seeked to at * Play's second t: t itself on a plan with no render edges; inside a clip, * the estimate's second for the SOURCE second playing (clamped into the * item's own share of the estimate, so the deck hands over at Play's join); * in a hold, its last frame's second on; a card, its own second. * * @param {{ items: Array }> }} plan * @param {number} t */ export function chromeTime(plan, t) { const i = itemIndexAt(plan, t); const it = plan?.items?.[i]; const e = it?.est; if (!it || !e || !fin(t)) return t; const clampTo = (v, lo, hi) => round(Math.min(hi, Math.max(lo, v))); if (it.clip && fin(e.sourceFrom)) { if (t > it.clip.playEnd) return clampTo(e.playEnd + (t - it.clip.playEnd), e.from, e.to); const src = /** @type {number} */ (sourceAt(it, t)); return clampTo(e.start + offsetIn(src, e.sourceFrom, e.gaps), e.from, it.clip.hold > 0 ? e.playEnd : e.to); } return clampTo(e.from + (t - it.from), e.from, e.to); } /** * The inverse, for what the estimate places (a stamp's `landed`, the * counter's steps): the Play second the estimate's second `tc` shows. * * @param {{ items: Array }> }} plan * @param {number} tc */ export function playTimeOfChrome(plan, tc) { const items = plan?.items ?? []; if (!items.length || !items[0].est || !fin(tc)) return tc; let k = 0; for (let i = items.length - 1; i >= 0; i -= 1) { if (tc >= /** @type {number} */ (items[i].est?.from)) { k = i; break; } } const it = items[k]; const e = /** @type {Record} */ (it.est); const clampTo = (v) => round(Math.min(it.to, Math.max(it.from, v))); if (it.clip && fin(e.sourceFrom)) { if (tc > e.playEnd) return clampTo(it.clip.playEnd + (tc - e.playEnd)); return clampTo(cutAtSource(it, sourceAtOffset(tc - e.start, e.sourceFrom, e.gaps))); } return clampTo(it.from + (tc - e.from)); } /** * The plan with some entries LEFT OUT (Play the cut skips the clips ruled * incorrect unless asked to show them): each skipped item's shown span * (`from`–`to`) is taken out of the clock and every later item moves up by * it, so its neighbours meet at the same seam the render would cut them at. * Every item keeps (or is given) its place on the estimate's clock (`est`), * which the chrome was composed on, so `chromeTime` still seeks the pages to * the second each item shows. `skipped` lists what was left out: its id and * the Play second it would have been at (the strip's marker). * * @template {{ items: Array }>, total: number, edges: string }} P * @param {P} plan * @param {Set | string[] | null} ids * @returns {P & { skipped: Array<{ id: string, at: number }> }} */ export function skipEntries(plan, ids) { const skip = ids instanceof Set ? ids : new Set(ids ?? []); if (!skip.size || !plan?.items?.length) return { ...plan, skipped: [] }; let shift = 0; /** @type {Array }>} */ const items = []; /** @type {Array<{ id: string, at: number }>} */ const skipped = []; for (const it of plan.items) { if (skip.has(it.id)) { skipped.push({ id: it.id, at: round(it.from - shift) }); shift += Math.max(0, it.to - it.from); continue; } const est = it.est ?? estOf(it); const s = (v) => round(v - shift); items.push({ ...it, index: items.length, start: s(it.start), end: s(it.end), from: items.length ? s(it.from) : 0, to: s(it.to), clip: it.clip ? { ...it.clip, playEnd: s(it.clip.playEnd) } : null, est, }); } return { ...plan, items, total: items.length ? items[items.length - 1].end : 0, skipped }; } /** An item's place on the estimate's clock (`est`), its gaps with it when it has any. */ function estOf(it) { return { start: it.start, end: it.end, from: it.from, to: it.to, ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), ...(it.clip?.gaps ? { gaps: it.clip.gaps } : {}), }; } /** The plan on the estimate's clock alone (playPlan without the render's edges). */ function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) { const byId = new Map((entries ?? []).map((e) => [e?.id, e])); const segs = (segments ?? []).filter((s) => s && fin(s.start) && fin(s.duration)); const items = segs.map((s, i) => { const e = byId.get(s.id) ?? null; const end = s.start + s.duration; const prev = segs[i - 1]; const next = segs[i + 1]; // The midpoint of the overlap with each neighbour (a hard cut has none: its start). const from = prev ? Math.min(s.start + Math.max(0, prev.start + prev.duration - s.start) / 2, end) : 0; const to = next ? Math.max(next.start + Math.max(0, end - next.start) / 2, from) : end; let clip = null; if (e?.type === "clip" && fin(e.start) && fin(e.end)) { const pw = livePlayWindow(/** @type {any} */ (e), leadIn); const hold = fin(s.hold) && /** @type {number} */ (s.hold) > 0 ? /** @type {number} */ (s.hold) : 0; const gaps = gapsWithin(gapsOf(e), pw.from, pw.to); clip = { sourceFrom: pw.from, sourceTo: pw.to, playEnd: round(s.start + Math.max(0, gappedLength(pw.from, pw.to, gaps))), hold, ...(gaps.length ? { gaps } : {}), }; } return { id: s.id, index: i, type: String(e?.type ?? "entry"), start: round(s.start), end: round(end), from: round(from), to: round(to), clip }; }); const total = items.length ? items[items.length - 1].end : 0; return { items, total: round(total), edges: /** @type {"estimate" | "render"} */ ("estimate") }; } /** The item on screen at cut second t (the last whose `from` ≤ t); -1 for an empty plan. */ export function itemIndexAt(plan, t) { const items = plan?.items ?? []; if (!items.length) return -1; if (!fin(t) || t <= items[0].from) return 0; for (let i = items.length - 1; i >= 0; i -= 1) if (t >= items[i].from) return i; return 0; } /** * The SOURCE second a clip item shows at cut second t: its play window's, * clamped into it -- before its footage its first frame, past it (the hold) * its last. null for an item that is not a clip. * * @param {PlayItem} item * @param {number} t */ export function sourceAt(item, t) { if (!item?.clip || !fin(t)) return null; const c = item.clip; return round(Math.min(c.sourceTo, Math.max(c.sourceFrom, sourceAtOffset(t - item.start, c.sourceFrom, c.gaps)))); } /** The cut second a clip item's source second plays at (the inverse inside its footage; inside a gap, its join). */ export function cutAtSource(item, src) { if (!item?.clip || !fin(src)) return item?.start ?? 0; return round(item.start + offsetIn(src, item.clip.sourceFrom, item.clip.gaps)); } /** * Where a clip item's gaps fall on the cut's clock: one cut second per gap * (its join), with the source span it leaves out -- the strip's tick and the * readout's "jump". [] without gaps. * * @param {PlayItem} item * @returns {Array<{ at: number, from: number, to: number }>} */ export function gapJoins(item) { const c = item?.clip; if (!c?.gaps?.length) return []; return c.gaps.map((g) => ({ at: cutAtSource(item, g.from), from: g.from, to: g.to })); } /** Is cut second t past the clip's footage, in its hold (its last frame shown)? */ export const inHold = (item, t) => !!item?.clip && fin(t) && t > item.clip.playEnd; /** The cut second a jump to item i lands on: where the page starts showing it. */ export const startOf = (plan, i) => plan?.items?.[Math.max(0, Math.min(i, (plan?.items?.length ?? 1) - 1))]?.from ?? 0; /** How long the page shows an item (its share of the cut, midpoint to midpoint). */ export const shownSeconds = (item) => round(Math.max(0, (item?.to ?? 0) - (item?.from ?? 0))); export { clockText }; /** How many characters "Send all open notes" may send (the video assistant's request cap). */ export const SEND_ALL_MAX = 2000; /** * "Send all open notes": the open notes taken while playing, in cut order, as * ONE request in words for the video assistant -- each with where it was * taken (the cut second, the clip, the source second), cut to the request's * cap. null when there is nothing open. * * @param {Array<{ status: string, text: string, anchor: { kind: string, t?: number, entry?: string, take?: string, sourceT?: number, ask?: string } }>} notes * @param {{ take?: string | null, max?: number }} [opts] */ export function cutNotesRequest(notes, { take = null, max = SEND_ALL_MAX } = {}) { const open = (notes ?? []) .filter((n) => n.status === "open" && n.anchor?.kind === "cut" && (n.anchor.take ?? null) === (take ?? null)) .sort((a, b) => (a.anchor.t ?? 0) - (b.anchor.t ?? 0)); if (!open.length) return null; const head = `Notes taken while playing ${take ? `take ${take}` : "the cut"}, in order:`; const lines = [head]; let len = head.length; for (const [i, n] of open.entries()) { const ask = n.anchor.ask && n.anchor.ask !== "other" ? ` [${n.anchor.ask}]` : ""; const line = `${i + 1}. ${cutPlace(n.anchor)}${ask}: ${String(n.text).replace(/\s+/g, " ").trim()}`; if (len + 1 + line.length > max) { const rest = `(${open.length - i} more not sent)`; if (len + 1 + rest.length <= max) lines.push(rest); break; } lines.push(line); len += 1 + line.length; } return lines.join("\n"); } /** Where a cut note was taken, in words: "at 1:12.4, in clip c04 (source 194.2 s)". */ export function cutPlace(a) { const parts = [`at ${clockText(a?.t ?? 0)}`]; if (a?.entry) parts.push(`in clip ${a.entry}${fin(a.sourceT) ? ` (source ${Number(a.sourceT).toFixed(1)} s)` : ""}`); return parts.join(", "); } // --------------------------------------------------------------------------- // THE REEL STRIP (PlayCut.tsx): the whole cut as a strip of film -- a cell // per entry as wide as it is shown, tinted by its recording's date, the // sections' seams, the counter's staircase, the time ruler. // --------------------------------------------------------------------------- /** * Each entry's place on the date ramp, 0 (the oldest recording) to 1 (the * newest), by `dateKey` (YYYYMMDD); null for an entry with no date. One date * throughout is 1 for every dated entry. * * @param {Array<{ id: string, dateKey?: number | null }>} entries * @returns {Map} */ export function dateRamp(entries) { const days = (k) => { const y = Math.floor(k / 10000); const m = Math.floor((k % 10000) / 100); const d = k % 100; return Date.UTC(y, m - 1, d) / 86400000; }; const dated = (entries ?? []).filter((e) => fin(e.dateKey)).map((e) => days(/** @type {number} */ (e.dateKey))); const lo = Math.min(...dated); const hi = Math.max(...dated); return new Map( (entries ?? []).map((e) => [e.id, fin(e.dateKey) ? (hi > lo ? round((days(/** @type {number} */ (e.dateKey)) - lo) / (hi - lo)) : 1) : null]), ); } /** * Where the cut changes section: before entry i when it is the first clip of * a new `section` (sections.mjs's rule), or right after a deck marker's * `after` clip. Each seam names the first date after it (the first dated * clip from there on) and the marker's label when a marker made it. * * A claim group (lib/report/claimGroups.mjs) that does not open a section * opens a GROUP seam before its first clip -- `kind: "group"`, its claim the * label -- which the strip draws lighter than a section's. Without `groups` * the seams are exactly the sections'. * * @param {Array<{ id: string, type: string, section?: unknown, dateLabel?: string | null }>} entries the cut's, in order * @param {Array<{ after: string, label?: string }>} [markers] render.chrome.deck.markers * @param {Array<{ id: string, claim?: string, ids: string[] }>} [groups] the manifest's claim groups * @returns {Array<{ before: string, index: number, date: string | null, label: string | null, kind?: "group", group?: string }>} */ export function seamsOf(entries, markers = [], groups = []) { const list = entries ?? []; /** @type {Map} */ const at = new Map(); let prev; list.forEach((e, i) => { if (e.type !== "clip") return; const s = e.section; if (s !== undefined && s !== null && prev !== undefined && s !== prev && i > 0) at.set(i, null); if (s !== undefined && s !== null) prev = s; }); for (const m of markers ?? []) { const i = list.findIndex((e) => e.id === m?.after); if (i >= 0 && i + 1 < list.length) at.set(i + 1, typeof m.label === "string" && m.label ? m.label : (at.get(i + 1) ?? null)); } const dateAt = (i) => list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null; const seams = [...at.entries()] .sort((a, b) => a[0] - b[0]) .map(([i, label]) => ({ before: list[i].id, index: i, date: dateAt(i), label, })); if (!Array.isArray(groups) || !groups.length) return seams; // A group's seam: before its first clip in the cut, where no section's is. const index = new Map(); list.forEach((e, i) => { if (!index.has(e.id)) index.set(e.id, i); }); /** @type {Array<{ before: string, index: number, date: string | null, label: string | null, kind?: "group", group?: string }>} */ const out = [...seams]; for (const g of groups) { const firsts = (Array.isArray(g?.ids) ? g.ids : []).map((id) => index.get(id)).filter((i) => i !== undefined); if (!firsts.length) continue; const i = Math.min(...firsts); if (i === 0 || at.has(i)) continue; out.push({ before: list[i].id, index: i, date: dateAt(i), label: typeof g.claim === "string" && g.claim ? g.claim : null, kind: "group", group: String(g.id) }); } return out.sort((a, b) => a.index - b.index); } /** * The counter as a staircase: for one verdict (or every one, `verdict` * null), the running total after each stamp lands, in cut order -- * `[{ t, n }]`, one point per step (stamps landing together are one step). * * @param {Array<{ landed: number, verdict: string, count?: number }>} stamps the schedule's factcheck stamps * @param {string | null} [verdict] */ export function counterSteps(stamps, verdict = null) { const mine = (stamps ?? []).filter((s) => fin(s.landed) && (verdict === null || s.verdict === verdict)).sort((a, b) => a.landed - b.landed); /** @type {Array<{ t: number, n: number }>} */ const out = []; let n = 0; for (const s of mine) { n += fin(s.count) ? /** @type {number} */ (s.count) : 1; const last = out[out.length - 1]; if (last && last.t === round(s.landed)) last.n = n; else out.push({ t: round(s.landed), n }); } return out; } /** The counter's total at cut second t (the steps that landed by then). */ export function counterAt(steps, t) { let n = 0; for (const s of steps ?? []) if (s.t <= t) n = s.n; return n; } /** * The time ruler's ticks: a round step (seconds) that gives at most * `maxTicks` ticks over the cut, and each tick's second. * * @param {number} total * @param {number} [maxTicks] */ export function rulerTicks(total, maxTicks = 12) { const steps = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600]; const T = fin(total) && total > 0 ? total : 0; const step = steps.find((s) => T / s <= maxTicks) ?? steps[steps.length - 1]; const ticks = []; for (let t = 0; t <= T + 1e-9; t += step) ticks.push(t); return { step, ticks }; } /** `m:ss` (or `h:mm:ss`): a ruler's or the running time's label. */ export function runningTime(t) { const s = Math.max(0, Math.floor(fin(t) ? t : 0)); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const ss = String(s % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${String(m).padStart(2, "0")}:${ss}`; } /** YYYYMMDD → "24 Oct 2020". */ export function dateKeyLabel(k) { if (!fin(k)) return null; const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const y = Math.floor(k / 10000); const m = Math.floor((k % 10000) / 100); const d = k % 100; return m >= 1 && m <= 12 ? `${d} ${MON[m - 1]} ${y}` : null; } /** * WHAT TO DECODE FOR A GAPPED CLIP (the picture's half of a jump cut): the * kept piece playing at cut second t, and -- when the next join is at most * `ahead` cut seconds away -- the piece after it, from its first second. Play * keeps one WebCodecs decoder per piece (codecPicture.ts keys `#p`), * so the piece after a long gap is decoded BEFORE the join: one decoder that * jumped at the join had to seek to a keyframe, fetch its block and decode up * through a long GOP, and the picture held its last frame 2-4 s while the * sound had already jumped. `mediaTime` is in the window's own seconds * (source minus `mediaFrom`, the cached file's first second). * * @param {PlayItem} item * @param {number} t * @param {number} mediaFrom * @param {{ ahead?: number }} [o] * @returns {Array<{ piece: number, mediaTime: number }>} */ export function pieceWants(item, t, mediaFrom, { ahead = 2 } = {}) { const src = sourceAt(item, t) ?? item?.clip?.sourceFrom ?? 0; const gaps = item?.clip?.gaps ?? []; let k = 0; for (const g of gaps) if (src >= g.to - 1e-6) k += 1; const out = [{ piece: k, mediaTime: Math.max(0, src - mediaFrom) }]; const g = gaps[k]; if (g) { const at = cutAtSource(item, g.from); if (at >= t - 1e-6 && at - t <= ahead) out.push({ piece: k + 1, mediaTime: Math.max(0, g.to - mediaFrom) }); } return out; }