Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 27c58f8bed26b5ad2cc16ae864bc007e651401de
parent 65c57cb80d3654030fa8f5fb93ad783585bde96e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 20 Nov 2026 17:02:55 -0500

Merge lane/gap-cue: a mark where a clip skips time, set on the bench; no rail of one or two items

A clip's gaps can show a small mark at each join (render.gapCue, off by default; project < clip < gap; a reason, a border, a corner per gap), set on the clip bench and the Modules panel and shown in Play the cut. The deck draws no rail under three pips. take --at aims its window on the played clock. The mark is drawn in the segment for now; the HyperFrames module that takes it over on deck takes is designed (slice 1d), not built.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Acommon/lib/report/gapCue.d.mts | 42++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/gapCue.mjs | 337+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/gapCue.test.ts | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/look.d.mts | 2+-
Mcommon/lib/report/look.mjs | 13+++++++++++--
Mcommon/lib/report/videoAssistOps.test.ts | 2+-
Mcommon/package.json | 1+
Meditor/CHANGELOG.md | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/window/route.ts | 5+++++
Mumtool/components/projects/ClipBench.tsx | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mumtool/components/projects/bench/BenchWave.tsx | 8+++++---
Aumtool/components/projects/bench/GapCueTools.tsx | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/GapsZoom.tsx | 65+++++++++++++++++++++++++++++++++++++++++++++--------------------
Mumtool/components/projects/bench/useGapEditor.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/components/projects/review/GapMarkChip.tsx | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 6++++--
Mumtool/components/projects/review/playCore.tsx | 16+++++++++++++++-
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/e2e/fixtures/make-fixture.mjs | 13+++++++++++++
Aumtool/e2e/gap-cue.spec.ts | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/gaps-zoom.spec.ts | 6++++--
Mumtool/lib/cli/groups.mjs | 4++--
Mumtool/lib/report/benchData.ts | 20+++++++++++++++++++-
Aumtool/lib/report/gapCueView.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/gapCueView.test.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/gaps-writer.test.mjs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/knobsCli.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/look.test.mjs | 2+-
Mumtool/lib/report/manifest.mjs | 58+++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/lib/report/playView.mjs | 13++++++++++++-
Mumtool/lib/report/takeMaker.mjs | 24+++++++++++++++++-------
Mumtool/lib/report/takeMaker.test.mjs | 8++++++++
Mumtool/lib/report/takePreview.mjs | 17+++++++++--------
Mumtool/report-to-video/build-video.mjs | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/chrome-deck.mjs | 4++--
Mumtool/report-to-video/chrome-finale.mjs | 13++++++++-----
Mumtool/report-to-video/chrome-vdeck.mjs | 6+++---
Mumtool/report-to-video/deck.mjs | 13+++++++++++++
Aumtool/report-to-video/gap-mark.mjs | 341+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/gap-mark.test.mjs | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/gaps-render.test.mjs | 191++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/gaps.mjs | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/report-to-video/gaps.test.mjs | 43++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/modules/config-loader.test.mjs | 16++++++++++++++++
Aumtool/report-to-video/modules/gap-cue.mjs | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/modules/index.mjs | 3++-
Mumtool/report-to-video/modules/panel.mjs | 11++++++++++-
Mumtool/report-to-video/modules/rail.mjs | 1+
Aumtool/report-to-video/rail-min.test.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
50 files changed, 3033 insertions(+), 144 deletions(-)

diff --git a/common/lib/report/gapCue.d.mts b/common/lib/report/gapCue.d.mts @@ -0,0 +1,42 @@ +// Types for ./gapCue.mjs (lane gap-cue): the gap cue's settings, label and timing. + +type Render = Record<string, unknown> | null | undefined; +type Entry = Record<string, unknown> | null | undefined; + +export type GapCueCorner = "auto" | "tl" | "tr" | "bl" | "br"; +export type GapCue = { mark: boolean; min: number; corner: GapCueCorner; label: string }; +export type GapCueMark = { at: number; until: number; seconds: number; count: number; why?: string; corner?: string }; +export type GapJoin = { at: number; seconds: number; mark: boolean; play?: number; why?: string; corner?: string | null }; +export type GapWhy = "dead-air" | "idle" | "other"; + +export const GAP_CUE_DEFAULTS: Readonly<GapCue>; +export const GAP_CUE_KEYS: readonly ("mark" | "min" | "corner" | "label")[]; +export const GAP_CUE_CORNERS: readonly GapCueCorner[]; +export const GAP_CUE_MIN: Readonly<{ min: number; max: number }>; +export const GAP_CUE_LABEL_MAX: number; +export const GAP_WHY: readonly GapWhy[]; +export const GAP_WHY_WORDS: Readonly<Record<GapWhy, string>>; +export const GAP_REASON_MAX: number; +export const GAP_OWN_CORNERS: readonly ("tl" | "tr" | "bl" | "br")[]; +export const GAP_REASON_RULE: string; +export function gapReasonOk(v: unknown): v is string; +export const GAP_CUE_LOOK: Readonly<{ + font: number; pad: number; inset: number; stroke: number; strokeMin: number; + fg: string; box: string; boxAlpha: number; strokeColor: string; strokeAlpha: number; +}>; +export const GAP_CUE_MOTION: Readonly<{ in: number; hold: number; out: number; peak: number }>; +export const GAP_CUE_LIFE: number; + +export function gapCueErrors(v: unknown, where?: string): string[]; +export function validateGapCue(manifest: unknown): string[]; +export function gapCueOf(render: Render): GapCue; +export function clipGapCueOf(render: Render, entry: Entry): GapCue; +export function gapMarkOn(cue: { mark: boolean }, gap: ({ mark?: unknown } & Record<string, unknown>) | null | undefined): boolean; +export function gapCueWanted(render: Render, entry: Entry): boolean; +export function gapCueLength(seconds: number): string; +export function gapWhyWord(gap: { why?: unknown; reason?: unknown } | null | undefined): string; +export function gapOwnSays(own: Array<{ why?: unknown; reason?: unknown; corner?: unknown }>): { why?: string; corner?: string }; +export function gapCueText(seconds: number, label?: string, why?: string): string; +export function gapCues(joins: GapJoin[], opts?: { min?: number; seconds?: number; life?: number }): GapCueMark[]; +export function gapCueAlpha(t: number, cue: { at: number; until: number }): number; +export function patchGapCue(current: unknown, patch: unknown): Record<string, unknown> | null; diff --git a/common/lib/report/gapCue.mjs b/common/lib/report/gapCue.mjs @@ -0,0 +1,337 @@ +// THE GAP CUE (lane gap-cue, slice 1): a small mark at the join a clip's gap +// leaves -- "» 27 s" -- so a viewer can tell that time was skipped, and +// roughly how much, without the mark pulling the eye from the footage. +// +// This module is the RULE, once, for every reader: the build draws the mark +// into the clip's segment (umtool report-to-video gap-mark.mjs), and umtool's +// pages (Play the cut, the clip bench) draw the same mark at the same seconds +// from the same functions. It holds the settings and their precedence, the +// label, and the timing; nothing here knows about ffmpeg or the DOM. +// +// THE SETTINGS, most specific wins: +// +// render.gapCue { mark?, min?, corner?, label? } the project's (a look key: a preset, a style or +// a take patch carries it like any other) +// clip.gapCue { mark?, min?, corner?, label? } one clip's, over the project's +// a gap's `mark` true | false one gap's, over both +// +// mark draw the mark at a join (default false: OFF, so a cut that says nothing renders as it always did) +// min a gap shorter than this draws nothing (seconds, default 2: a breath taken out is not worth a mark) +// corner auto | tl | tr | bl | br (default auto: the layout's own free corner) +// label the text: `{s}` the length skipped, `{why}` the gap's reason, and a part in [ ] drawn only when +// the gap has one (default "» {s}[ · {why}]": "» 27 s", or "» 26 s · dead air"; from a minute "» 1:12") +// +// A gap may also carry `why` ("dead-air" | "idle" | "other"): what it was cut +// for, and `reason`, a few words of its own (at most GAP_REASON_MAX). The mark +// says the reason (operator, 20 Nov: "add the reason to the mark"): `reason` +// when it is set, else why's word (GAP_WHY_WORDS: "dead air", "idle"; "other" +// says nothing). A fast-forward default (slice 3) will reach only the gaps +// marked dead air, so a gap cut to HIDE what is in it never plays. A gap's +// `corner` stands its mark in that corner, over its clip's (a stream's layout +// can change inside one clip). +// +// THE LOOK (GAP_CUE_LOOK) is here too, so the build's drawtext (gap-mark.mjs) +// and the pages' element (GapMarkChip) draw one mark. +// +// THE TIMING, on the segment's clock (seconds from its first frame): the mark +// comes up over GAP_CUE_MOTION.in at the join, holds, and goes over +// GAP_CUE_MOTION.out -- GAP_CUE_LIFE in all. Joins closer together than that +// are ONE mark: it comes up at the first, says the seconds of all of them, and +// goes a life after the last. It never outlives the segment. +// +// PURE and dependency-free: the client bundle takes it as it is. + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const EPS = 1e-6; + +/** The settings a cut that says nothing has: the mark off. */ +export const GAP_CUE_DEFAULTS = Object.freeze({ mark: false, min: 2, corner: "auto", label: "» {s}[ · {why}]" }); +/** The keys `render.gapCue` and a clip's `gapCue` take. */ +export const GAP_CUE_KEYS = Object.freeze(["mark", "min", "corner", "label"]); +/** Where the mark may stand: the layout's choice, or a corner of its box. */ +export const GAP_CUE_CORNERS = Object.freeze(["auto", "tl", "tr", "bl", "br"]); +/** `min`'s range, in seconds. */ +export const GAP_CUE_MIN = Object.freeze({ min: 0.5, max: 60 }); +/** A label's longest, in characters. */ +export const GAP_CUE_LABEL_MAX = 40; +/** What a gap was cut for (`why`). */ +export const GAP_WHY = Object.freeze(["dead-air", "idle", "other"]); +/** What the mark says for each `why` ("other" says nothing: a gap's `reason` says it). */ +export const GAP_WHY_WORDS = Object.freeze({ "dead-air": "dead air", idle: "idle", other: "" }); +/** A gap's own `reason`'s longest, in characters (one line). */ +export const GAP_REASON_MAX = 24; +/** The corners a gap's own `corner` may name (its mark stands there, over its clip's). */ +export const GAP_OWN_CORNERS = Object.freeze(["tl", "tr", "bl", "br"]); +/** + * The characters a label or a reason may not hold: every control character (a tab, a newline, NUL…), DEL and the + * line and paragraph separators -- the mark is ONE line, drawn as written (gap-mark.mjs: drawtext, expansion=none). + */ +const CONTROL = /[\u0000-\u001f\u007f\u2028\u2029]/; +/** Is `v` a gap's reason: one line of words, 1 to GAP_REASON_MAX characters once trimmed, no control character and no `[ ] { }`. */ +export const gapReasonOk = (v) => + typeof v === "string" && v.trim().length > 0 && v.trim().length <= GAP_REASON_MAX && !CONTROL.test(v) && !/[[\]{}]/.test(v); +/** The sentence for a reason that is not one. */ +export const GAP_REASON_RULE = `a few words, at most ${GAP_REASON_MAX} characters on one line (no [ ] { }, no tab or other control character)`; +/** Is `v` a label's text, its length and characters (its {s} and [ ] parts aside). */ +const labelLineOk = (v) => v.length <= GAP_CUE_LABEL_MAX && !CONTROL.test(v); +/** + * THE LOOK, once (operator, 20 Nov: "more visible and readable with a border"): sizes as fractions of the + * frame's short side -- `font` the text (0.03: 32 px at 1080), `inset` from the box it stands in, `stroke` the + * border's width (at least `strokeMin` px) -- `pad` the box round the text in ems; the text `fg` on `box` at + * `boxAlpha`, inside a `strokeColor` border at `strokeAlpha`. The whole mark fades together (GAP_CUE_MOTION). + */ +export const GAP_CUE_LOOK = Object.freeze({ + font: 0.03, pad: 0.38, inset: 0.026, stroke: 0.0019, strokeMin: 2, + fg: "#ffffff", box: "#101010", boxAlpha: 0.86, strokeColor: "#ffffff", strokeAlpha: 0.9, +}); +/** The mark's motion (seconds) and its opacity at full. */ +export const GAP_CUE_MOTION = Object.freeze({ in: 0.15, hold: 0.6, out: 0.35, peak: 0.9 }); +/** How long one mark is up: in, hold and out. */ +export const GAP_CUE_LIFE = GAP_CUE_MOTION.in + GAP_CUE_MOTION.hold + GAP_CUE_MOTION.out; + +const q = (v) => JSON.stringify(v); + +/** + * Every reason a `gapCue` block cannot be built ([] when it can; absent is fine). + * + * @param {unknown} v + * @param {string} [where] + * @returns {string[]} + */ +export function gapCueErrors(v, where = "render.gapCue") { + if (v === undefined || v === null) return []; + if (!isObj(v)) return [`${where} must be { mark?, min?, corner?, label? }`]; + const errors = []; + for (const k of Object.keys(v)) if (!GAP_CUE_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${GAP_CUE_KEYS.join(", ")})`); + if (v.mark !== undefined && typeof v.mark !== "boolean") errors.push(`${where}.mark is true (draw the mark at a join) or false, not ${q(v.mark)}`); + if (v.min !== undefined && !(fin(v.min) && v.min >= GAP_CUE_MIN.min && v.min <= GAP_CUE_MIN.max)) { + errors.push(`${where}.min is seconds from ${GAP_CUE_MIN.min} to ${GAP_CUE_MIN.max} (a shorter gap draws nothing), not ${q(v.min)}`); + } + if (v.corner !== undefined && !GAP_CUE_CORNERS.includes(/** @type {string} */ (v.corner))) errors.push(`${where}.corner is one of ${GAP_CUE_CORNERS.join(", ")}, not ${q(v.corner)}`); + if (v.label !== undefined) { + if (typeof v.label !== "string" || !v.label.includes("{s}")) errors.push(`${where}.label is text holding {s} (the seconds skipped), e.g. "» {s}" or "{s} later"`); + else if (!labelLineOk(v.label)) errors.push(`${where}.label is one line of at most ${GAP_CUE_LABEL_MAX} characters (no tab or other control character)`); + else if (!labelPartsOk(v.label)) errors.push(`${where}.label: a part in [ ] holds {why} and is drawn only when the gap has a reason, e.g. "» {s}[ · {why}]" (no [ ] inside another)`); + } + return errors; +} + +/** + * Every reason a manifest's gap cue settings cannot be built: `render.gapCue` + * and each clip's `gapCue` (a gap's own `mark` and `why` are gaps.mjs's). + * + * @param {{ render?: unknown, timeline?: unknown }} manifest + * @returns {string[]} + */ +export function validateGapCue(manifest) { + const render = isObj(manifest?.render) ? manifest.render : {}; + const errors = gapCueErrors(render.gapCue, "render.gapCue"); + const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + timeline.forEach((e, i) => { + if (!isObj(e) || e.gapCue === undefined) return; + const where = `timeline[${i}] (${e.id ?? "?"}).gapCue`; + if (e.type !== "clip") errors.push(`${where}: only a clip has gaps to mark`); + else errors.push(...gapCueErrors(e.gapCue, where)); + }); + return errors; +} + +/** Are a label's [ ] parts well formed: not nested, each closed, each holding {why}. */ +function labelPartsOk(label) { + let open = -1; + for (let i = 0; i < label.length; i += 1) { + if (label[i] === "[") { + if (open >= 0) return false; + open = i; + } else if (label[i] === "]") { + if (open < 0 || !label.slice(open, i).includes("{why}")) return false; + open = -1; + } + } + return open < 0; +} + +/** The well-formed keys of a `gapCue` block (anything else dropped). */ +function own(v) { + if (!isObj(v)) return {}; + const out = {}; + if (typeof v.mark === "boolean") out.mark = v.mark; + if (fin(v.min) && v.min >= GAP_CUE_MIN.min && v.min <= GAP_CUE_MIN.max) out.min = v.min; + if (GAP_CUE_CORNERS.includes(v.corner)) out.corner = v.corner; + if (typeof v.label === "string" && v.label.includes("{s}") && labelLineOk(v.label) && labelPartsOk(v.label)) out.label = v.label; + return out; +} + +/** + * The project's settings, the defaults filled in. + * + * @param {Record<string, any> | null | undefined} render + * @returns {{ mark: boolean, min: number, corner: string, label: string }} + */ +export const gapCueOf = (render) => ({ ...GAP_CUE_DEFAULTS, ...own(render?.gapCue) }); + +/** + * One clip's settings: its own `gapCue` over the project's. + * + * @param {Record<string, any> | null | undefined} render + * @param {Record<string, any> | null | undefined} entry + */ +export const clipGapCueOf = (render, entry) => ({ ...gapCueOf(render), ...own(entry?.gapCue) }); + +/** + * Is one gap marked: its own `mark` when it says, else its clip's (`cue`, clipGapCueOf). + * + * @param {{ mark: boolean }} cue + * @param {{ mark?: unknown } | null | undefined} gap + */ +export const gapMarkOn = (cue, gap) => (typeof gap?.mark === "boolean" ? gap.mark : cue.mark); + +/** Is the mark on anywhere in this clip: for the clip, or for one of its gaps? */ +export function gapCueWanted(render, entry) { + const cue = clipGapCueOf(render, entry); + const gaps = Array.isArray(entry?.gaps) ? entry.gaps : []; + return gaps.some((g) => gapMarkOn(cue, g)); +} + +/** + * The length skipped, as the mark says it: whole seconds under a minute + * ("27 s"), then m:ss ("1:12"), then h:mm:ss ("1:02:03"). + * + * @param {number} seconds + */ +export function gapCueLength(seconds) { + const r = Math.max(0, Math.round(Number(seconds) || 0)); + if (r < 60) return `${r} s`; + const p2 = (n) => String(n).padStart(2, "0"); + const h = Math.floor(r / 3600); + const m = Math.floor((r % 3600) / 60); + const s = r % 60; + return h ? `${h}:${p2(m)}:${p2(s)}` : `${m}:${p2(s)}`; +} + +/** + * What a gap's mark says it was cut for: its own `reason` when set, else its + * `why`'s word (GAP_WHY_WORDS), else "". + * + * @param {{ why?: unknown, reason?: unknown } | null | undefined} gap + */ +export function gapWhyWord(gap) { + const r = typeof gap?.reason === "string" ? gap.reason.trim() : ""; + if (r) return r; + return typeof gap?.why === "string" ? (GAP_WHY_WORDS[/** @type {keyof typeof GAP_WHY_WORDS} */ (gap.why)] ?? "") : ""; +} + +/** + * What a join's own gaps (`own`: the clip's gaps it is -- one, or two the + * frame grid joined) say beyond their seconds: their reason when they all + * give the same (gapWhyWord), and the first corner one names. Only the keys + * they have. + * + * @param {Array<{ why?: unknown, reason?: unknown, corner?: unknown }>} own + * @returns {{ why?: string, corner?: string }} + */ +export function gapOwnSays(own) { + const words = (own ?? []).map((c) => gapWhyWord(c)); + const why = words.length && words.every((w) => w && w === words[0]) ? words[0] : ""; + const corner = (own ?? []).map((c) => c?.corner).find((c) => typeof c === "string" && GAP_OWN_CORNERS.includes(/** @type {any} */ (c))); + return { ...(why ? { why } : {}), ...(typeof corner === "string" ? { corner } : {}) }; +} + +/** + * The mark's text: `label` with `{s}` the length skipped and `{why}` the + * reason (gapWhyWord); a part in [ ] only when there is a reason. + * + * @param {number} seconds + * @param {string} [label] + * @param {string} [why] + */ +export function gapCueText(seconds, label = GAP_CUE_DEFAULTS.label, why = "") { + const w = String(why ?? "").trim(); + return String(label) + .replace(/\[([^\]]*)\]/g, (_, part) => (w ? part : "")) + .split("{why}").join(w) + .split("{s}").join(gapCueLength(seconds)); +} + +/** + * The marks a segment draws, from its joins. + * + * `joins`: each `{ at, seconds, mark, play?, why?, corner? }` -- `at` the + * join on the segment's clock, `seconds` the source seconds the gap left + * out, `mark` whether this gap is marked (gapMarkOn), `play` the seconds the + * gap itself plays (0, a skip; slice 3's fast-forward), `why` what its mark + * says it was cut for (gapWhyWord), `corner` its own corner. A gap unmarked, + * or under `min`, draws nothing and joins no mark. Marked joins less than + * `life` apart are one mark, the seconds of each in it -- its reason only + * when they all say the same, its corner the first that names one. A mark never outlives + * the segment (`seconds`), and one with under a fifth of a second left is + * not drawn. `why` and `corner` are on a mark only when it has them. + * + * @param {Array<{ at: number, seconds: number, mark: boolean, play?: number, why?: string, corner?: string | null }>} joins + * @param {{ min?: number, seconds?: number, life?: number }} [opts] + * @returns {Array<{ at: number, until: number, seconds: number, count: number, why?: string, corner?: string }>} + */ +export function gapCues(joins, { min = GAP_CUE_DEFAULTS.min, seconds = Infinity, life = GAP_CUE_LIFE } = {}) { + const marked = (joins ?? []) + .filter((j) => j && j.mark === true && fin(j.at) && fin(j.seconds) && j.seconds >= min - EPS) + .sort((a, b) => a.at - b.at); + const out = []; + let open = null; + for (const j of marked) { + const end = j.at + (fin(j.play) && j.play > 0 ? j.play : 0) + life; + const why = typeof j.why === "string" ? j.why : ""; + if (open && j.at < open.until - EPS) { + open.until = Math.max(open.until, end); + open.seconds += j.seconds; + open.count += 1; + if (open.why !== why) open.why = ""; + // Its corner the first of its joins' that names one (gapOwnSays's rule for one join's own gaps). + if (!open.corner && typeof j.corner === "string" && j.corner) open.corner = j.corner; + continue; + } + open = { at: j.at, until: end, seconds: j.seconds, count: 1, why, corner: typeof j.corner === "string" ? j.corner : "" }; + out.push(open); + } + const r4 = (v) => Math.round(v * 10000) / 10000; + return out + .map((c) => ({ + at: r4(Math.max(0, c.at)), until: r4(Math.min(seconds, c.until)), seconds: r4(c.seconds), count: c.count, + ...(c.why ? { why: c.why } : {}), ...(c.corner ? { corner: c.corner } : {}), + })) + .filter((c) => c.until - c.at >= 0.2 - EPS); +} + +/** + * The mark's opacity at `t` (the segment's clock): up over `in`, down over + * `out`, GAP_CUE_MOTION.peak between; 0 outside it. The build's alpha + * expression is this, written for ffmpeg (gap-mark.mjs). + * + * @param {number} t + * @param {{ at: number, until: number }} cue + */ +export function gapCueAlpha(t, cue) { + if (!(t >= cue.at && t <= cue.until)) return 0; + const k = Math.min((t - cue.at) / GAP_CUE_MOTION.in, (cue.until - t) / GAP_CUE_MOTION.out); + return GAP_CUE_MOTION.peak * Math.max(0, Math.min(1, k)); +} + +/** + * A patch of a `gapCue` block applied (the look's writer and a clip's): each + * key merged over what it holds, a key null drops it, nothing left is no + * block (null). `patch` null drops the whole block. + * + * @param {unknown} current + * @param {unknown} patch + * @returns {Record<string, unknown> | null} + */ +export function patchGapCue(current, patch) { + if (patch === null) return null; + if (!isObj(patch)) return /** @type {any} */ (patch); + const next = { ...(isObj(current) ? current : {}) }; + for (const [k, v] of Object.entries(patch)) { + if (v === null) delete next[k]; + else next[k] = v; + } + return Object.keys(next).length ? next : null; +} diff --git a/common/lib/report/gapCue.test.ts b/common/lib/report/gapCue.test.ts @@ -0,0 +1,142 @@ +// gapCue.mjs (lane gap-cue): the settings and their precedence (project < +// clip < gap), the label, the timing of the marks, and the look's writer. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + GAP_CUE_DEFAULTS, + GAP_CUE_LIFE, + clipGapCueOf, + gapCueAlpha, + gapCueLength, + gapCueOf, + gapCueText, + gapCueWanted, + gapCues, + gapMarkOn, + gapReasonOk, + gapWhyWord, + validateGapCue, +} from "./gapCue.mjs"; +import { applyLookPatch, lookErrors } from "./look.mjs"; + +test("the defaults: the mark OFF, 2 s, the layout's corner, '» {s}[ · {why}]'", () => { + assert.deepEqual(gapCueOf(undefined), { mark: false, min: 2, corner: "auto", label: "» {s}[ · {why}]" }); + assert.deepEqual(gapCueOf({}), GAP_CUE_DEFAULTS); + assert.equal(gapCueWanted({}, { type: "clip", gaps: [{ from: 1, to: 9 }] }), false, "a cut that says nothing marks nothing"); +}); + +test("precedence: a gap's mark over its clip's over the project's", () => { + const render = { gapCue: { mark: true, min: 3 } }; + const clip = { type: "clip", gapCue: { mark: false, corner: "tr" }, gaps: [{ from: 1, to: 9 }, { from: 12, to: 20, mark: true }] }; + const cue = clipGapCueOf(render, clip); + assert.deepEqual(cue, { mark: false, min: 3, corner: "tr", label: "» {s}[ · {why}]" }); + assert.equal(gapMarkOn(cue, clip.gaps[0]), false, "the clip's off"); + assert.equal(gapMarkOn(cue, clip.gaps[1]), true, "the gap's own on"); + assert.equal(gapCueWanted(render, clip), true); + assert.equal(gapMarkOn(gapCueOf(render), { from: 1, to: 2, mark: false }), false, "a gap's off beats the project's on"); +}); + +test("the label: whole seconds, then m:ss, then h:mm:ss; {s} is the length", () => { + assert.equal(gapCueLength(27.4), "27 s"); + assert.equal(gapCueLength(59.4), "59 s"); + assert.equal(gapCueLength(59.6), "1:00"); + assert.equal(gapCueLength(72), "1:12"); + assert.equal(gapCueLength(3723), "1:02:03"); + assert.equal(gapCueText(27), "» 27 s"); + assert.equal(gapCueText(72, "{s} later"), "1:12 later"); +}); + +test("the reason in the mark (operator, 20 Nov): why's word, or the gap's own reason; none, the length alone as before", () => { + assert.equal(gapWhyWord({ why: "dead-air" }), "dead air"); + assert.equal(gapWhyWord({ why: "idle" }), "idle"); + assert.equal(gapWhyWord({ why: "other" }), "", "other says nothing"); + assert.equal(gapWhyWord({ why: "other", reason: " ad break " }), "ad break", "a reason of its own says it"); + assert.equal(gapWhyWord({}), ""); + assert.equal(gapCueText(26, undefined, "dead air"), "» 26 s · dead air"); + assert.equal(gapCueText(26, undefined, ""), "» 26 s", "no reason: exactly the slice 1 text"); + assert.equal(gapCueText(72, "{s} skipped[ ({why})]", "idle"), "1:12 skipped (idle)"); + assert.equal(gapCueText(72, "{s} skipped[ ({why})]"), "1:12 skipped"); + // A merged mark says a reason only when every join in it says the same. + const same = gapCues([{ at: 2, seconds: 5, mark: true, why: "dead air" }, { at: 2.5, seconds: 6, mark: true, why: "dead air" }]); + assert.equal(same[0]!.why, "dead air"); + const mixed = gapCues([{ at: 2, seconds: 5, mark: true, why: "dead air" }, { at: 2.5, seconds: 6, mark: true }]); + assert.equal("why" in mixed[0]!, false); + // Its corner is the first join's own. + assert.equal(gapCues([{ at: 2, seconds: 5, mark: true, corner: "tr" }])[0]!.corner, "tr"); + // The label's [ ] parts: closed, not nested, each holding {why}. + assert.deepEqual(validateGapCue({ render: { gapCue: { label: "» {s}[ · {why}]" } } }), []); + assert.match(validateGapCue({ render: { gapCue: { label: "» {s}[ · why]" } } }).join("\n"), /a part in \[ \] holds \{why\}/); + assert.match(validateGapCue({ render: { gapCue: { label: "» {s}[ · {why}" } } }).join("\n"), /a part in \[ \]/); +}); + +test("the marks: under min nothing, marked only, joins within a life are one mark summing their seconds", () => { + assert.deepEqual(gapCues([{ at: 2, seconds: 1.5, mark: true }]), [], "a breath taken out draws nothing"); + assert.deepEqual(gapCues([{ at: 2, seconds: 27, mark: false }]), [], "unmarked"); + assert.deepEqual(gapCues([{ at: 2, seconds: 27, mark: true }], { seconds: 10 }), [{ at: 2, until: 2 + GAP_CUE_LIFE, seconds: 27, count: 1 }]); + const two = gapCues([{ at: 5, seconds: 10, mark: true }, { at: 2, seconds: 27, mark: true }, { at: 2.6, seconds: 4, mark: true }], { seconds: 20 }); + assert.deepEqual(two, [ + { at: 2, until: 2.6 + GAP_CUE_LIFE, seconds: 31, count: 2 }, + { at: 5, until: 5 + GAP_CUE_LIFE, seconds: 10, count: 1 }, + ]); + // Never past the segment; nothing with under 0.2 s left. + assert.deepEqual(gapCues([{ at: 3, seconds: 9, mark: true }], { seconds: 3.5 }), [{ at: 3, until: 3.5, seconds: 9, count: 1 }]); + assert.deepEqual(gapCues([{ at: 3.4, seconds: 9, mark: true }], { seconds: 3.5 }), []); + // A fast-forward's play seconds (slice 3) keep it up that much longer. + assert.equal(gapCues([{ at: 1, seconds: 30, mark: true, play: 0.8 }])[0]!.until, Number((1 + 0.8 + GAP_CUE_LIFE).toFixed(4))); +}); + +test("a merged mark's corner: the first of its joins that names one, not only the first join's (review 1, 7)", () => { + const joins = [{ at: 2, seconds: 27, mark: true }, { at: 2.5, seconds: 4, mark: true, corner: "br" }, { at: 3, seconds: 3, mark: true, corner: "tr" }]; + const [m] = gapCues(joins, { seconds: 20 }); + assert.equal(m!.count, 3); + assert.equal(m!.corner, "br"); + // The first naming one wins over a later one. + assert.equal(gapCues([{ ...joins[0]!, corner: "tl" }, joins[1]!], { seconds: 20 })[0]!.corner, "tl"); +}); + +test("a label or a reason holds no control character: one line, drawn as written (review 1, 1)", () => { + for (const bad of ["{s}\tlater", "{s}\u0000", "{s}\u2028", "{s}\u2029", "{s}\u007f", "{s}\nlater"]) { + assert.match(validateGapCue({ render: { gapCue: { label: bad } } }).join("\n"), /one line of at most 40 characters/, JSON.stringify(bad)); + assert.equal(gapCueOf({ gapCue: { label: bad } }).label, GAP_CUE_DEFAULTS.label, `${JSON.stringify(bad)} is not taken`); + } + // A % or a backslash is words like any other: the build draws it as written. + assert.deepEqual(validateGapCue({ render: { gapCue: { label: "{s} (90%) \\ {why}" } } }), []); + assert.equal(gapReasonOk("100% idle"), true); + assert.equal(gapReasonOk("back\\slash"), true); + for (const bad of ["a\tb", "a\u0001", "a\u2028b", "a\u2029", "x\u007f", "a\nb", "[x]", "{x}", "", " ", "x".repeat(25)]) { + assert.equal(gapReasonOk(bad), false, JSON.stringify(bad)); + } +}); + +test("the opacity: up over 0.15 s, 0.9 at full, down over 0.35 s", () => { + const c = { at: 2, until: 2 + GAP_CUE_LIFE }; + assert.equal(gapCueAlpha(1.9, c), 0); + assert.equal(gapCueAlpha(2, c), 0); + assert.ok(Math.abs(gapCueAlpha(2.075, c) - 0.45) < 1e-9); + assert.equal(gapCueAlpha(2.5, c), 0.9); + assert.equal(gapCueAlpha(c.until, c), 0); +}); + +test("validation: the project's block and each clip's, in the build's words", () => { + assert.deepEqual(validateGapCue({ render: {}, timeline: [] }), []); + assert.deepEqual(validateGapCue({ render: { gapCue: { mark: true, min: 4, corner: "bl", label: "{s} later" } } }), []); + const errs = validateGapCue({ + render: { gapCue: { mark: "yes", min: 0.1, corner: "middle", label: "skipped", size: 3 } }, + timeline: [{ type: "clip", id: "c1", gapCue: { mark: 1 } }, { type: "card", id: "k1", gapCue: {} }], + }); + assert.equal(errs.length, 7, errs.join("\n")); + assert.match(errs.join("\n"), /render\.gapCue\.size is not a key/); + assert.match(errs.join("\n"), /label is text holding \{s\}/); + assert.match(errs.join("\n"), /\(c1\)\.gapCue\.mark is true/); + assert.match(errs.join("\n"), /\(k1\)\.gapCue: only a clip has gaps to mark/); +}); + +test("the look's writer: gapCue merged over what it holds, a key null drops it, null drops the block", () => { + const m = { render: { gapCue: { mark: true, min: 3 } }, timeline: [] }; + assert.deepEqual(applyLookPatch(m, { gapCue: { corner: "tl" } }).render.gapCue, { mark: true, min: 3, corner: "tl" }); + assert.deepEqual(applyLookPatch(m, { gapCue: { min: null } }).render.gapCue, { mark: true }); + assert.equal(applyLookPatch(m, { gapCue: null }).render.gapCue, undefined); + assert.match(applyLookPatch(m, { gapCue: { min: 99 } }).errors.join("\n"), /render\.gapCue\.min is seconds from 0\.5 to 60/); + assert.deepEqual(lookErrors({ render: { gapCue: { mark: true } } }), []); +}); diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts @@ -4,7 +4,7 @@ type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>; type Render = Record<string, unknown> | null | undefined; -export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows" | "desktop" | "promo" | "zooms" | "censor"; +export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro" | "format" | "vertical" | "mode" | "basic" | "tallWindows" | "desktop" | "promo" | "zooms" | "censor" | "gapCue"; export const LOOK_KEYS: readonly LookKey[]; export const QR_CORNERS: readonly ["br", "bl", "tr", "tl"]; export const QR_LINK_VALUES: readonly ["cite", "moment", "channel"]; diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs @@ -19,6 +19,8 @@ import { introPatchValue, validateIntro } from "./intro.mjs"; // `format` and `vertical` (lane vertical): the cut rendered 9:16, and a clip's side post (./vertical.mjs). import { CLIP_OWN_LAYOUTS, validateVerticalFormat } from "./vertical.mjs"; +// `gapCue` (lane gap-cue): the mark at a clip gap's join (./gapCue.mjs). +import { patchGapCue, validateGapCue } from "./gapCue.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); @@ -29,7 +31,7 @@ const round2 = (n) => Number(Number(n).toFixed(2)); /** The corner code's corners and links (lane clip-kit; umtool report-to-video clip-kit.mjs draws them). */ export const QR_CORNERS = Object.freeze(["br", "bl", "tr", "tl"]); export const QR_LINK_VALUES = Object.freeze(["cite", "moment", "channel"]); -export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo", "zooms", "censor"]); +export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo", "zooms", "censor", "gapCue"]); /** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */ export const BAND_MAX = 240; @@ -384,7 +386,7 @@ export function validateLook(manifest) { // render.blur (the uncensored variant's switch) is part of the look too. return [ ...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest), ...validateRenderBlur(manifest), ...validateIntro(manifest), - ...validateVerticalFormat(manifest), ...validateRenderMode(manifest), + ...validateVerticalFormat(manifest), ...validateRenderMode(manifest), ...validateGapCue(manifest), ]; } @@ -486,6 +488,13 @@ export function applyLookPatch(manifest, patch) { else if (v === false) delete render.tallWindows; else errors.push("render.tallWindows must be true (windows up to render.maxHeightSource) or false (720, the default)"); break; + case "gapCue": { + // Merged over what it holds (a key null drops it); validateGapCue (lookErrors, below) says what is wrong. + const next = patchGapCue(render.gapCue, v); + if (next === null) delete render.gapCue; + else render.gapCue = next; + break; + } case "format": // "landscape" is the default: written as no key at all. if (v === "landscape") delete render.format; diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts @@ -26,7 +26,7 @@ test("the look's rules: one patch function — keys refused, null removes, qr on assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } })); assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } })); assert.deepEqual(lookErrors(m), []); - assert.equal(LOOK_KEYS.length, 20); + assert.equal(LOOK_KEYS.length, 21); }); test("render.mode and render.basic: deck is the default (no key), basic the footage alone; the fades checked", () => { diff --git a/common/package.json b/common/package.json @@ -62,6 +62,7 @@ "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", "./lib/report/look.mjs": "./lib/report/look.mjs", + "./lib/report/gapCue.mjs": "./lib/report/gapCue.mjs", "./lib/report/vertical.mjs": "./lib/report/vertical.mjs", "./lib/report/intro.mjs": "./lib/report/intro.mjs", "./lib/report/fxParams.mjs": "./lib/report/fxParams.mjs", diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,53 @@ # Changelog ## [Unreleased] +- **umtool: the gap mark is set on the clip bench and shows while playing.** + - A click on a gap's band now picks the gap. A row under the waveform shows its seconds, how it shows (skip; + fast-forward is not built yet), its own mark (as the clip's, on or off), what it was cut for, its own words, its + corner, what its mark will say, and Remove. `G` still puts back the gap at the playhead. Beside it are the clip's + mark settings: on or off, the shortest gap marked, the corner and the label. + - Each control writes what its CLI twin writes (`umtool set … gap.*`, `gapCue.*`), and each write that changes + something is an undo point. The project's settings are in the Media tab's Modules panel (Gap mark). A field + cleared there now clears. + - A gap grown over another (Cut gap on a span that touches it, `gap.add=`, `--gap`) keeps that gap's settings: its + why and words when the gaps it took in agree, the first corner, and the mark on if any was. The note says what it + kept. + - Play the cut and the bench draw the mark at the same seconds, with the same text and look as the render. +- **umtool: the gap mark says why, and reads on busy footage.** + - A gap with a reason shows it: `» 26 s · dead air`. `why` is `dead-air`, `idle` or `other`, or the gap can have + its own words (`gap.reason=<s>:walks off`, up to 24 characters). A gap with no reason reads `» 27 s`, as before. + The label's `{why}` and its `[ ]` part (default `» {s}[ · {why}]`) control this. The text is drawn as written: a + `%` or a backslash is shown, and a tab or other control character is refused. + - A mark too wide for its place is drawn smaller, then cut with `…`. It never runs off the frame. + - The mark is larger (3 % of the frame's short side), on a near-opaque dark box inside a 2 px light border. One set + of numbers draws both the render's mark and the pages' mark. + - A gap can stand its mark in its own corner (`gap.corner=<s>:tr`), over the clip's. The automatic corner does not + know where a stream's own chat or banners are, so on that kind of footage, set the corner. +- **umtool: a small mark where a clip skips time.** + - With `render.gapCue.mark` on, each join a clip's gap leaves shows `» 27 s` (from a minute `» 1:12`) near a + corner of the footage for about a second, fading in and out. There is no sound, flash or wipe. Gaps under 2 s + draw nothing, and joins closer together than the mark's life are one mark that adds up their seconds. + - It is drawn after hidden regions and the blur, at a corner the layout leaves free: the deck's footage bottom + left, the plain cut's picture top left, and in a 9:16 cut the picture's top left (framed, quote) or top right + (split, full bleed, a twocrop clip's crop one), always inside the safe area. When a hidden region or a code is in + that corner while the mark is up, the mark moves to the next free corner. A clip cut from its pieces marks the + join between them too. + - The settings layer from broad to narrow: the project's `render.gapCue` (`umtool look <p> gapCue='{"mark":true}'`, + and a preset, style or take patch carries it), then a clip's `gapCue` (`umtool set <p> <clip> gapCue.mark=…`), + then a gap's own `mark` (`gap.mark=<sec>:off`). The label is a setting (`gapCue.label='{s} later'`), as are the + minimum length and the corner. A gap's reason and its own corner are in the bullet above. + - It is off by default, and a cut that sets nothing renders byte for byte as before. Turning it on re-renders + only the segments of clips that have a marked gap. Montages, basic mode and Export one clip draw no mark. + `--chrome-only` rebuilds no clip segment, so it lays a changed mark as it was built, and says so for each clip. +- **umtool: no rail of one or two items.** A rail with fewer than three pips is no longer drawn. That covers a cut + of one or two clips, and a window take over one or two (a window take lays out only the clips it covers, so it + cannot light the whole cut's rail). It applies to the deck's pip track (its fuse, marker and flags with it), the + stacked deck's rail and count, and the finale's large rail. Nothing moves into the room they leave. With three + pips or more, the pages are the markup they always were. +- **umtool: `take --at` lands on the right clip after a clip with gaps.** When the window was timed by the + manifest's estimates, a clip counted at its whole cut span, gaps included. A window aimed at the clip after it + then landed earlier by the gaps' total and rendered the gapped clip instead. The estimate now counts the seconds + that play, as the build and Play the cut do. Under `render.montage`, which applies no gaps, it counts the whole cut. - **A chat captured while the stream was live is on the recording's clock.** - yt-dlp times a chat captured live from the moment its capture began, not from the broadcast's start. A chat fetched while a from-start recording ran therefore showed every message as early as the capture was late: 37 diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -83,6 +83,11 @@ export async function PUT(request: Request) { "gaps", "gapAdd", "gapRemove", + // One gap's own settings, its seconds as they are (`gapEdit`: {at, mark?, why?, reason?, corner?}, a key null drops it), + // and the mark at this clip's gaps' joins (`gapCue`: {mark?, min?, corner?, label?}, null clears it; + // common lib/report/gapCue.mjs). + "gapEdit", + "gapCue", // Whether the walk has looked at this clip: "confirmed", "incorrect" (a // fact error, with its correction), "rejected" (with its `reason` and an // optional `rejectNote`), or empty to clear it (lib/report/rejectReasons.mjs). diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -35,7 +35,11 @@ import { attributionLine } from "umtool-report-to-video/attribution"; import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs"; // Gaps inside a clip: the rule (the writer's and the build's) and the pieces that play. import { gapSpan, gapWalls, gappedLength, validateGaps } from "umtool-report-to-video/gaps"; -import { useGapEditor } from "./bench/useGapEditor"; +import { useGapEditor, type SavedGap } from "./bench/useGapEditor"; +import GapCueTools from "./bench/GapCueTools"; +import GapMarkChip from "./review/GapMarkChip"; +import { clipGapMarks, clipPlayClock, gapMarkAt, gapMarkCorner } from "@/lib/report/gapCueView.mjs"; +import { clipGapCueOf, gapCueOf, type GapCue } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; import { BenchWaveBox, GapTools } from "./bench/BenchWave"; import { CutEdges } from "./bench/CutEdges"; import { sourceWindowMedia } from "./bench/benchMedia"; @@ -142,9 +146,12 @@ type Clip = { /** * GAPS: source seconds cut out of the clip's middle (gaps.mjs), so it plays * as one segment of jump cuts. Written at once (Cut gap, a click on a band), - * not drafted like the edges; every playback here skips them. + * not drafted like the edges; every playback here skips them. Each with + * its own `mark` and `why` when it says (common gapCue.mjs). */ - gaps: Span[]; + gaps: SavedGap[]; + /** The mark at its gaps' joins, its own settings over the project's (common gapCue.mjs); absent: none. */ + gapCue?: Partial<GapCue> | null; /** * The seconds no gap may cover (lane/clip-fixes): each claim mark's or * stamp's `at` (`claims`, else `claim`; gaps.mjs gapWalls), read so the @@ -252,7 +259,8 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({ cutEnd: e.cutEnd == null ? null : Number(e.cutEnd), lockCut: !!e.lockCut, muteFrom: e.muteFrom == null ? null : Number(e.muteFrom), - gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [], + gaps: Array.isArray(e.gaps) ? (e.gaps as SavedGap[]) : [], + gapCue: e.gapCue && typeof e.gapCue === "object" ? (e.gapCue as Partial<GapCue>) : null, marks: Array.isArray(e.marks) ? (e.marks as Clip["marks"]) : marksOf(e), verdict: e.verdict === "confirmed" || e.verdict === "incorrect" || e.verdict === "rejected" ? e.verdict : null, walkNote: (e.walkNote as string) ?? null, @@ -320,6 +328,8 @@ export type ClipBenchData = { deckOn: boolean; /** Every region the cut hides on this clip (clip-censor.mjs censorRegionsOf): drawn over the raw window. */ hidden?: CensorRegion[]; + /** The project's `render.gapCue` as the build reads it (the look preset under it): the mark at gaps' joins. */ + gapCue?: Record<string, unknown> | null; /** The manifest's `generatedBy`: edits here are noted for the agent that runs it. */ generatedBy?: string | null; /** @@ -1375,7 +1385,8 @@ export default function ClipBench({ // of jump cuts rather than as two clips with a crossfade, a second pip and a // second card. A span is dragged on the waveform with Alt held (or after `g` // / Select a gap) and written by Cut gap (or `g`); a click on a gap's band - // puts it back. Unlike the edges these are WRITTEN AT ONCE, through the one + // picks it -- its mark, its why and Remove under the waveform (bench/GapCueTools.tsx) + // -- and `G` puts back the one at the playhead. Unlike the edges these are WRITTEN AT ONCE, through the one // window writer (`gapAdd` / `gapRemove`), which refuses what the build would // -- and leaves an undo point (auto-before-gaps) -- and Undo here writes the // list back as it was. The rule is checked here first, with the same @@ -1419,12 +1430,20 @@ export default function ClipBench({ gaps: clip.gaps ?? [], span: gapsSpan, refusal: gapRefusal, + // A clip's gap has settings of its own (its mark, its why): a click on its band picks it (bench/GapCueTools.tsx). + settings: true, write: async (op, _next) => { // A moved edge rides along: the gap was checked against the edges as drafted. const win = windowMoved || muteMoved ? windowPatch() : null; const ok = await save({ ...(win ?? {}), - ...("add" in op ? { gapAdd: op.add } : "remove" in op ? { gapRemove: (op.remove.from + op.remove.to) / 2 } : { gaps: op.set }), + ...("add" in op + ? { gapAdd: op.add } + : "remove" in op + ? { gapRemove: (op.remove.from + op.remove.to) / 2 } + : "edit" in op + ? { gapEdit: op.edit } + : { gaps: op.set }), }); return ok; }, @@ -1446,6 +1465,30 @@ export default function ClipBench({ : `stopped at the start of what plays (${hms(at)}) — drag the start handle out first${atStartEdge ? ", past the cache: Fetch more" : ""}`, }); + // ---- the mark at the gaps' joins (lane gap-cue; common gapCue.mjs, lib/report/gapCueView.mjs) ---------------- + // + // The project's settings (the look preset under them), the clip's over them, and the marks what plays draws: + // on the clock of what plays (the cut, else the extent, as drafted -- the gaps' span), the render's own rule. + const projectCue = useMemo(() => gapCueOf({ gapCue: data.gapCue ?? undefined }), [data.gapCue]); + const clipCue = useMemo(() => clipGapCueOf({ gapCue: data.gapCue ?? undefined }, { gapCue: clip.gapCue ?? undefined }), [data.gapCue, clip.gapCue]); + const benchMarks = useMemo( + () => clipGapMarks({ cue: clipCue, gaps: clip.gaps ?? [], from: gapsSpan.from, to: gapsSpan.to }), + [clipCue, clip.gaps, gapsSpan.from, gapsSpan.to], + ); + // The recording's hidden regions drawn over the bench's picture (CensorOverlay). + const hasHidden = (data.hidden?.length ?? 0) > 0; + const benchMark = benchMarks.length ? gapMarkAt(benchMarks, clipPlayClock({ gaps: clip.gaps ?? [], from: gapsSpan.from, to: gapsSpan.to }, playhead)) : null; + // A gap's own corner over the clip's (a stream's layout can change inside one clip). + const benchMarkCorner = gapMarkCorner(benchMark?.corner ?? clipCue.corner, { deck: data.deckOn }); + const writeGapCue = useCallback( + async (patch: Record<string, unknown>) => { + const ok = await save({ gapCue: patch }); + if (ok) setNote(`the mark at this clip's joins: ${Object.entries(patch).map(([k, v]) => `${k} ${v === null ? "as the project's" : JSON.stringify(v)}`).join(", ")}`); + return ok; + }, + [save], + ); + // ---- the cut, cleared and put back ------------------------------------------- // // Use the whole clip (and Clear cut) clears the cut -- what plays becomes the @@ -2938,17 +2981,26 @@ export default function ClipBench({ > {placeBar} <div className="flex md:contents"> - {cached && (data.hidden?.length ?? 0) > 0 ? ( - // With hidden regions the picture sits in a box of its own, the regions drawn over it (an editing - // surface: outlined, a Peek toggle off by default). Without, the <video> is the flex item as before. + {cached ? ( + // The picture sits in a box of its own whenever media is cached, ONE <video> whatever is drawn over it: the + // hidden regions (an editing surface: outlined, a Peek toggle off by default) and the gap mark mount and + // unmount inside the box, so turning a mark on mid-playback never replaces the element (its source, its + // playback, useBenchPlayer's session on it). <div - data-bench-censor="" + data-bench-picture="" + data-bench-censor={hasHidden ? "" : undefined} className={cn("relative aspect-video w-full lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", inspector && "hidden")} > <video ref={video} data-testid="clip-video" src={media.src ?? undefined} + // object-contain, because the height is now whatever is left + // rather than whatever 16:9 asks for. + // The picture and the words SHARE what is left, 3:2, rather + // than either taking a fixed number of pixels: a laptop and a + // 1080p screen have very different amounts to give away, and a + // 130px player is not a player. className="absolute inset-0 h-full w-full rounded border border-[var(--color-line)] bg-black object-contain" preload="metadata" controls @@ -2956,30 +3008,14 @@ export default function ClipBench({ const el = e.currentTarget; if (el.videoWidth > 0 && el.videoHeight > 0) setBenchAspect(el.videoWidth / el.videoHeight); }} - onTimeUpdate={(e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime)} - onSeeked={(e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime)} + // The regions' clock: only while there are regions (the page is not re-drawn on every tick without). + onTimeUpdate={hasHidden ? (e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime) : undefined} + onSeeked={hasHidden ? (e) => setBenchAt((cached?.from ?? 0) + e.currentTarget.currentTime) : undefined} /> - <CensorOverlay regions={data.hidden ?? []} at={benchAt} aspect={benchAspect} mode="edit" testId="bench-censor" /> + {hasHidden && <CensorOverlay regions={data.hidden ?? []} at={benchAt} aspect={benchAspect} mode="edit" testId="bench-censor" />} + {/* The mark at a gap's join, as the render draws it (lane gap-cue): up while what plays crosses a marked join. */} + {benchMarks.length > 0 && <GapMarkChip mark={benchMark} corner={benchMarkCorner} aspect={benchAspect} testId="bench-gap-mark" />} </div> - ) : cached ? ( - <video - ref={video} - data-testid="clip-video" - src={media.src ?? undefined} - // object-contain, because the height is now whatever is left - // rather than whatever 16:9 asks for. - // The picture and the words SHARE what is left, 3:2, rather - // than either taking a fixed number of pixels: a laptop and a - // 1080p screen have very different amounts to give away, and a - // 130px player is not a player. - className={cn( - "aspect-video w-full rounded border border-[var(--color-line)] bg-black object-contain lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", - // The workspace's viewer is the picture: the inspector keeps the element (the bench plays through it), unseen. - inspector && "hidden", - )} - preload="metadata" - controls - /> ) : ( <div data-walk-pin-empty="" className={cn("flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)] lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", inspector && "aspect-auto py-3 lg:aspect-auto lg:min-h-0")}> nothing fetched for this clip yet @@ -3398,6 +3434,17 @@ export default function ClipBench({ </span> <ZoomControls zoom={zoom} whole={view} selection={gap.sel ?? sel} playhead={playhead} /> </div> + {/* ---- the mark at the gaps' joins: the picked gap's own, the clip's (bench/GapCueTools.tsx) ---- */} + <GapCueTools + gap={gap} + cue={clipCue} + project={projectCue} + own={clip.gapCue ?? null} + busy={!!busy} + fmt={hms} + writeCue={writeGapCue} + hasGaps={(clip.gaps ?? []).length > 0} + /> </div> {/* Offered at the edge of the cache, as always -- and also whenever diff --git a/umtool/components/projects/bench/BenchWave.tsx b/umtool/components/projects/bench/BenchWave.tsx @@ -6,7 +6,7 @@ import { buttonVariants } from "@/components/ui/button"; import { GAP_LIMITS, gappedLength } from "umtool-report-to-video/gaps"; import { GapLayer, type GapWallsView, type WaveZoom } from "./GapsZoom"; import type { Span } from "./benchMedia"; -import type { GapEditor } from "./useGapEditor"; +import type { GapEditor, SavedGap } from "./useGapEditor"; // --------------------------------------------------------------------------- // THE BENCH'S WAVEFORM AND ITS GAPS (lifted out of ClipBench.tsx; shared with @@ -46,7 +46,7 @@ export function BenchWaveBox({ playhead: number | null; onSel: (next: Span, dragging: boolean, edge?: "start" | "end" | null) => void; gap: GapEditor; - gaps: Span[]; + gaps: SavedGap[]; silences: Span[] | null; words: { start: number; end?: number; w?: string }[] | null; busy: boolean; @@ -118,8 +118,10 @@ export function BenchWaveBox({ silences={silences} words={words} busy={busy} - onRemove={gap.remove} + onBand={gap.band} onSelect={gap.select} + picked={gap.picked} + pickable={gap.settings} /> {children} </div> diff --git a/umtool/components/projects/bench/GapCueTools.tsx b/umtool/components/projects/bench/GapCueTools.tsx @@ -0,0 +1,248 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { GAP_CUE_CORNERS, GAP_CUE_MIN, GAP_OWN_CORNERS, GAP_REASON_MAX, gapCueText, gapMarkOn, gapWhyWord, type GapCue } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; +import type { GapEditor } from "./useGapEditor"; + +// --------------------------------------------------------------------------- +// THE MARK AT A GAP'S JOIN, SET ON THE BENCH (lane gap-cue, slice 1b; common +// lib/report/gapCue.mjs is the rule). Under the gaps' tools, in Cut mode: +// +// the picked gap (a click on its band) its seconds, how it shows (a skip: +// fast-forward is not built yet), its own mark (as the +// clip's, on, off), what it was cut for (its mark says it: +// "» 26 s · dead air"), a few words of its own instead, its +// own corner (a stream's layout can change inside a clip), +// what its mark will say, Remove +// the clip's the mark at its joins (as the project's, on, off), the +// shortest gap marked, the corner, the label +// +// Every control writes at once through the window writer -- `gapEdit` for the +// gap (useGapEditor's editPicked: an undo point, and the bench's Undo), +// `gapCue` for the clip (an undo point) -- the same writes as their CLI twins, +// named on each control. +// --------------------------------------------------------------------------- + +const sel = + "rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-1 py-0.5 text-[11px] text-[var(--color-text)] disabled:opacity-60"; +const onOff = (v: boolean) => (v ? "on" : "off"); +const CORNER_WORDS: Record<string, string> = { auto: "the layout's", tl: "top left", tr: "top right", bl: "bottom left", br: "bottom right" }; + +export default function GapCueTools({ + gap, + cue, + project, + own, + busy, + fmt, + writeCue, + hasGaps, +}: { + gap: GapEditor; + /** The clip's settings, its own over the project's (clipGapCueOf). */ + cue: GapCue; + /** The project's (gapCueOf(render), the look preset under it): what the clip's "as the project's" means. */ + project: GapCue; + /** The clip's own `gapCue` block, as saved (null: none). */ + own: Partial<GapCue> | null; + busy: boolean; + fmt: (t: number) => string; + /** Write the clip's `gapCue` patch (a key null drops it); resolves whether it was written. */ + writeCue: (patch: Record<string, unknown>) => Promise<boolean>; + hasGaps: boolean; +}) { + const g = gap.picked; + // The two typed fields: drafted, written on Enter or leaving them. + const [min, setMin] = useState(own?.min === undefined ? "" : String(own.min)); + const [label, setLabel] = useState(own?.label ?? ""); + const [reason, setReason] = useState(g?.reason ?? ""); + useEffect(() => setMin(own?.min === undefined ? "" : String(own.min)), [own?.min]); + useEffect(() => setLabel(own?.label ?? ""), [own?.label]); + useEffect(() => setReason(g?.reason ?? ""), [g?.from, g?.to, g?.reason]); + if (!hasGaps) return null; + + const commitMin = () => { + const v = min.trim(); + const was = own?.min === undefined ? "" : String(own.min); + if (v === was) return; + void writeCue({ min: v === "" ? null : Number(v) }); + }; + const commitLabel = () => { + if (label === (own?.label ?? "")) return; + void writeCue({ label: label === "" ? null : label }); + }; + const commitReason = () => { + if (!g || reason.trim() === (g.reason ?? "")) return; + void gap.editPicked({ reason: reason.trim() === "" ? null : reason.trim() }); + }; + const len = g ? g.to - g.from : 0; + const at = g ? ((g.from + g.to) / 2).toFixed(2) : ""; + return ( + <div data-gap-settings="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> + {g && ( + <span data-gap-picked-row={`${g.from}-${g.to}`} className="flex flex-wrap items-center gap-1.5 rounded border border-[var(--color-sel)] px-1.5 py-0.5"> + <span className="num text-[var(--color-text)]"> + gap {fmt(g.from)}–{fmt(g.to)} <span className="text-[var(--color-dim)]">({len.toFixed(2)} s)</span> + </span> + <span data-gap-show="skip" className="text-[var(--color-dim)]" title="how the gap plays: a jump cut (fast-forward through it is a later slice)"> + shows as <span className="text-[var(--color-text)]">skip</span> · fast-forward: not built yet + </span> + <label className="flex items-center gap-1"> + <span className="micro">mark</span> + <select + data-gap-mark-select="" + className={sel} + disabled={busy} + value={typeof g.mark === "boolean" ? onOff(g.mark) : ""} + title={`umtool set <p> <clip> gap.mark=${at}:on|off|default`} + onChange={(e) => void gap.editPicked({ mark: e.target.value === "" ? null : e.target.value === "on" })} + > + <option value="">as the clip&rsquo;s ({onOff(cue.mark)})</option> + <option value="on">on</option> + <option value="off">off</option> + </select> + </label> + <label className="flex items-center gap-1"> + <span className="micro">why</span> + <select + data-gap-why-select="" + className={sel} + disabled={busy} + value={g.why ?? ""} + title={`what it was cut for, said in its mark (umtool set <p> <clip> gap.why=${at}:dead-air|idle|other|default)`} + onChange={(e) => void gap.editPicked({ why: e.target.value === "" ? null : (e.target.value as "dead-air" | "idle" | "other") })} + > + <option value="">not said</option> + <option value="dead-air">dead air</option> + <option value="idle">idle</option> + <option value="other">other</option> + </select> + </label> + <input + data-gap-reason="" + className={`${sel} w-28`} + disabled={busy} + maxLength={GAP_REASON_MAX} + value={reason} + placeholder="own words" + title={`a few words the mark says instead (at most ${GAP_REASON_MAX}; umtool set <p> <clip> gap.reason=${at}:<words>, gap.reason=${at}: drops them)`} + onChange={(e) => setReason(e.target.value)} + onBlur={commitReason} + onKeyDown={(e) => { + if (e.key === "Enter") commitReason(); + }} + /> + <label className="flex items-center gap-1"> + <span className="micro">corner</span> + <select + data-gap-corner-select="" + className={sel} + disabled={busy} + value={g.corner ?? ""} + title={`where this gap's mark stands, over the clip's (umtool set <p> <clip> gap.corner=${at}:tl|tr|bl|br|default)`} + onChange={(e) => void gap.editPicked({ corner: e.target.value === "" ? null : (e.target.value as "tl" | "tr" | "bl" | "br") })} + > + <option value="">as the clip&rsquo;s ({CORNER_WORDS[cue.corner] ?? cue.corner})</option> + {GAP_OWN_CORNERS.map((c) => ( + <option key={c} value={c}> + {CORNER_WORDS[c] ?? c} + </option> + ))} + </select> + </label> + {gapMarkOn(cue, g) && len >= cue.min && ( + <span data-gap-says={gapCueText(len, cue.label, gapWhyWord(g))} className="font-mono text-[11px] text-[var(--color-dim)]" title="what its mark says"> + {gapCueText(len, cue.label, gapWhyWord(g))} + </span> + )} + {gapMarkOn(cue, g) && len < cue.min && ( + <span data-gap-under-min="" className="text-[var(--color-dim)]"> + under {cue.min} s: no mark + </span> + )} + <button + type="button" + data-gap-remove="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={busy} + title={`put these seconds back in the clip (G at the playhead; umtool set <p> <clip> gap.remove=${at})`} + onClick={() => gap.remove(g)} + > + Remove + </button> + </span> + )} + <span data-gap-cue-clip="" className="flex flex-wrap items-center gap-1.5"> + <span className="micro">mark at joins</span> + <select + data-gap-cue-mark="" + className={sel} + disabled={busy} + value={typeof own?.mark === "boolean" ? onOff(own.mark) : ""} + title="this clip's, over the project's (umtool set <p> <clip> gapCue.mark=true|false; gapCue.mark= as the project's)" + onChange={(e) => void writeCue({ mark: e.target.value === "" ? null : e.target.value === "on" })} + > + <option value="">as the project&rsquo;s ({onOff(project.mark)})</option> + <option value="on">on</option> + <option value="off">off</option> + </select> + <label className="flex items-center gap-1"> + <span className="micro">from</span> + <input + data-gap-cue-min="" + type="number" + min={GAP_CUE_MIN.min} + max={GAP_CUE_MIN.max} + step={0.5} + className={`${sel} w-14`} + disabled={busy} + value={min} + placeholder={String(project.min)} + title="the shortest gap marked, in seconds (umtool set <p> <clip> gapCue.min=<s>)" + onChange={(e) => setMin(e.target.value)} + onBlur={commitMin} + onKeyDown={(e) => { + if (e.key === "Enter") commitMin(); + }} + /> + <span className="micro">s</span> + </label> + <label className="flex items-center gap-1"> + <span className="micro">corner</span> + <select + data-gap-cue-corner="" + className={sel} + disabled={busy} + value={own?.corner ?? ""} + title="umtool set <p> <clip> gapCue.corner=auto|tl|tr|bl|br" + onChange={(e) => void writeCue({ corner: e.target.value === "" ? null : e.target.value })} + > + <option value="">as the project&rsquo;s ({CORNER_WORDS[project.corner] ?? project.corner})</option> + {GAP_CUE_CORNERS.map((c) => ( + <option key={c} value={c}> + {CORNER_WORDS[c] ?? c} + </option> + ))} + </select> + </label> + <label className="flex items-center gap-1"> + <span className="micro">label</span> + <input + data-gap-cue-label="" + className={`${sel} w-24 font-mono`} + disabled={busy} + value={label} + placeholder={project.label} + title="{s} is the time skipped, {why} the gap's reason, [ ] drawn only with a reason (umtool set <p> <clip> gapCue.label='» {s}[ · {why}]')" + onChange={(e) => setLabel(e.target.value)} + onBlur={commitLabel} + onKeyDown={(e) => { + if (e.key === "Enter") commitLabel(); + }} + /> + </label> + </span> + </div> + ); +} diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx @@ -29,7 +29,9 @@ import { // its text (a caption word's box runs to the next word's start), // so a gap's edge -- or a tightened edge -- goes between two words. // gaps each a hatched band over the waveform, `cut` on it; a click on -// one removes it. A span for a new one is dragged with Alt held +// one picks it where a gap has settings of its own (a clip's: its +// mark, why and Remove under the waveform), else puts it back (a +// reel beat's). A span for a new one is dragged with Alt held // (or after `g` / Select a gap); Cut gap (or `g`) writes it. // // At fit -- the default, and on every clip's arrival -- the waveform is exactly @@ -178,7 +180,7 @@ export function ZoomRuler({ vis }: { vis: Span }) { /** * Over the waveform (absolutely placed, the waveform's box): the gaps, the * span being selected for one, and -- close in -- the silences and the pauses - * between words. `onRemove` on a gap's click; while `picking` (or with Alt + * between words. `onBand` on a gap's click (pick it, or put it back: useGapEditor's `band`); while `picking` (or with Alt * held over the waveform, the caller's capture handler) a drag selects a span. */ /** What GapLayer draws of the walls: gapWalls's shape, the zones' kinds open (a reel adds its master's gaps). */ @@ -198,13 +200,19 @@ export function GapLayer({ silences, words, busy, - onRemove, + onBand, onSelect, live = null, walls = null, + picked = null, + pickable = false, }: { vis: Span; - gaps: Span[]; + gaps: Array<Span & { mark?: boolean; why?: string }>; + /** The gap whose settings are shown (useGapEditor's `picked`): outlined. */ + picked?: Span | null; + /** A click on a band picks the gap (its settings) rather than putting it back (useGapEditor's `settings`). */ + pickable?: boolean; selection: Span | null; /** What the selection would do, checked on every move (useGapEditor's GapLive). */ live?: { why: string | null; wall: string | null; merged: { from: number; to: number } | null; short: boolean } | null; @@ -221,7 +229,8 @@ export function GapLayer({ /** The recording's words (the clip-editor route's): timed (`end`), or a caption word's start only. */ words: { start: number; end?: number; w?: string }[] | null; busy: boolean; - onRemove: (g: Span) => void; + /** A click on a gap's band: useGapEditor's `band` (picks it with `settings`, else puts it back). */ + onBand: (g: Span) => void; onSelect: (s: Span, done: boolean) => void; }) { const span = Math.max(1e-6, vis.to - vis.from); @@ -280,21 +289,37 @@ export function GapLayer({ <div key={`q-${t}`} data-wave-quiet={t} aria-hidden className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-meter)_55%,transparent)]" style={{ left: pct(t) }} /> ))} {walls && <GapWallsLayer walls={walls} vis={vis} pct={pct} width={width} full={picking || !!selection} />} - {gaps.filter(inView).map((g) => ( - <button - key={`gap-${g.from}`} - type="button" - data-gap-band={`${g.from}-${g.to}`} - disabled={busy} - title={`a gap: ${g.from.toFixed(2)}–${g.to.toFixed(2)} (${(g.to - g.from).toFixed(2)} s) is cut out of the clip — click to put it back`} - onPointerDown={(e) => e.stopPropagation()} - onClick={() => onRemove(g)} - className="absolute top-0 z-[5] h-full cursor-pointer overflow-hidden border-x border-[var(--color-dirty)] p-0 text-left [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-ground)_70%,transparent)_0_5px,color-mix(in_srgb,var(--color-dirty)_22%,transparent)_5px_9px)]" - style={{ left: pct(g.from), width: width(g.from, g.to) }} - > - <span className="pointer-events-none absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-dirty)]">cut</span> - </button> - ))} + {gaps.filter(inView).map((g) => { + const on = !!picked && picked.from === g.from && picked.to === g.to; + return ( + <button + key={`gap-${g.from}`} + type="button" + data-gap-band={`${g.from}-${g.to}`} + data-gap-picked={on ? "" : undefined} + data-gap-own-mark={typeof g.mark === "boolean" ? (g.mark ? "on" : "off") : undefined} + data-gap-why={g.why} + aria-pressed={pickable ? on : undefined} + disabled={busy} + title={ + pickable + ? `a gap: ${g.from.toFixed(2)}–${g.to.toFixed(2)} (${(g.to - g.from).toFixed(2)} s) is cut out of the clip — click for its settings and Remove` + : `a gap: ${g.from.toFixed(2)}–${g.to.toFixed(2)} (${(g.to - g.from).toFixed(2)} s) is cut out of the clip — click to put it back` + } + onPointerDown={(e) => e.stopPropagation()} + onClick={() => onBand(g)} + className={cn( + "absolute top-0 z-[5] h-full cursor-pointer overflow-hidden border-x border-[var(--color-dirty)] p-0 text-left [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-ground)_70%,transparent)_0_5px,color-mix(in_srgb,var(--color-dirty)_22%,transparent)_5px_9px)]", + on && "outline outline-2 -outline-offset-2 outline-[var(--color-sel)]", + )} + style={{ left: pct(g.from), width: width(g.from, g.to) }} + > + <span className="pointer-events-none absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-dirty)]"> + cut + </span> + </button> + ); + })} {selection && inView(selection) && ( <div data-gap-selection={`${selection.from.toFixed(2)}-${selection.to.toFixed(2)}`} diff --git a/umtool/components/projects/bench/useGapEditor.ts b/umtool/components/projects/bench/useGapEditor.ts @@ -9,14 +9,39 @@ import type { Span } from "./benchMedia"; // out of the middle of a span (umtool-report-to-video gaps.mjs), so it plays // as one run of jump cuts. A span is dragged on the waveform with Alt held // (or after `g` / Select a gap) and written by Cut gap (or `g`); a click on a -// gap's band puts it back; Undo writes the list back as it was. Written AT +// gap's band puts it back -- or, where a gap has settings of its own (a +// clip's: its mark and why, lane gap-cue), picks it, its settings and Remove +// shown under the waveform; Undo writes the list back as it was. Written AT // ONCE, through the caller's writer -- a clip's window writer (`gapAdd` / // `gapRemove`) or a reel's beat writer -- which refuses what the build would; // the rule is checked here first (`refusal`), with the same sentences, so a // refusal is said before anything is sent. // --------------------------------------------------------------------------- -export type GapOp = { add: Span } | { remove: Span } | { set: Span[] }; +/** A gap's own settings (common gapCue.mjs): its mark over the clip's, what it was cut for. */ +export type GapOwn = { mark?: boolean; why?: "dead-air" | "idle" | "other"; reason?: string; corner?: "tl" | "tr" | "bl" | "br" }; +/** A gap as saved: its seconds and its own settings. */ +export type SavedGap = Span & GapOwn; +/** One gap's own settings changed, its seconds as they are (the window writer's `gapEdit`; null drops a key). */ +export type GapEdit = { + at: number; + mark?: boolean | null; + why?: "dead-air" | "idle" | "other" | null; + reason?: string | null; + corner?: "tl" | "tr" | "bl" | "br" | null; +}; + +export type GapOp = { add: Span } | { remove: Span } | { set: Span[] } | { edit: GapEdit }; + +/** What a grown gap kept of its own settings, as a note says it ("its mark on, dead air, its words, its corner tr"); "" for none. */ +export function keptSaid(g: SavedGap): string { + return [ + typeof g.mark === "boolean" ? `its mark ${g.mark ? "on" : "off"}` : null, + g.why ? (g.why === "dead-air" ? "dead air" : g.why) : null, + g.reason ? `its words “${g.reason}”` : null, + g.corner ? `its corner ${g.corner}` : null, + ].filter(Boolean).join(", "); +} /** * What the span being dragged for a gap would do, said WHILE it is dragged @@ -40,11 +65,12 @@ export function useGapEditor({ setNote, fmt, wall, + settings = false, }: { /** What the gaps belong to: another one starts with nothing selected and nothing to undo. */ key: string; - /** The gaps as saved. */ - gaps: Span[]; + /** The gaps as saved (a clip's with their own settings). */ + gaps: SavedGap[]; /** Where a gap may go (the clip's cut or extent; a beat's span). */ span: Span; /** Why `next` cannot be written, or null. */ @@ -57,6 +83,11 @@ export function useGapEditor({ fmt: (t: number) => string; /** The sentence for a drag stopped at `span`'s edge (the clip's cut, a beat's end); a plain one without. */ wall?: (side: "start" | "end", at: number) => string; + /** + * A gap has settings of its own (a clip's: its mark, its why; lane gap-cue): a click on its band PICKS it -- + * its settings and Remove under the waveform -- instead of putting it back. A reel beat's has none. + */ + settings?: boolean; }) { const [sel, setSelState] = useState<Span | null>(null); const [live, setLive] = useState<GapLive | null>(null); @@ -66,11 +97,19 @@ export function useGapEditor({ }, []); const [pick, setPick] = useState(false); const [undo, setUndo] = useState<{ gaps: Span[]; what: string } | null>(null); + // The saved gap whose settings are shown (a click on its band, `settings` only): by its seconds. + const [picked, setPicked] = useState<Span | null>(null); useEffect(() => { setSel(null); setPick(false); setUndo(null); + setPicked(null); }, [key, setSel]); + // The gap picked as it is saved now; none once it is gone (put back, merged into another). + const pickedGap = picked ? (gaps.find((g) => g.from === picked.from && g.to === picked.to) ?? null) : null; + useEffect(() => { + if (picked && !pickedGap) setPicked(null); + }, [picked, pickedGap]); const run = useCallback( async (op: GapOp, next: Span[], what: string) => { @@ -101,13 +140,17 @@ export function useGapEditor({ setNote(e instanceof Error ? e.message : String(e)); return; } - // A span touching a gap GROWS it (editGaps): say which one it became. - const grown = next.find((x) => x.from <= g.from + 1e-6 && x.to >= g.to - 1e-6); + // A span touching a gap GROWS it (editGaps): say which one it became, and what of the gaps it took in it kept + // (gaps.mjs mergedOwnKeys: their why and words when they agree, the first corner, the mark on if any was). + const grown = next.find((x) => x.from <= g.from + 1e-6 && x.to >= g.to - 1e-6) as SavedGap | undefined; const merged = grown && (Math.abs(grown.from - g.from) > 0.005 || Math.abs(grown.to - g.to) > 0.005) ? grown : null; + const kept = merged ? keptSaid(merged) : ""; const ok = await run( { add: g }, next, - merged ? `cut ${fmt(g.from)}–${fmt(g.to)} out, merged with the gap beside it into ${fmt(merged.from)}–${fmt(merged.to)}` : `cut ${fmt(g.from)}–${fmt(g.to)} out`, + merged + ? `cut ${fmt(g.from)}–${fmt(g.to)} out, merged with the gap beside it into ${fmt(merged.from)}–${fmt(merged.to)}${kept ? ` — kept ${kept}` : ""}` + : `cut ${fmt(g.from)}–${fmt(g.to)} out`, ); if (ok) { setSel(null); @@ -123,17 +166,58 @@ export function useGapEditor({ [gaps, run, fmt], ); + /** + * A click on a gap's band: with `settings`, it picks the gap (again: lets it go) and says so; without, + * it puts the gap back, as it always has. + */ + const band = useCallback( + (g: Span) => { + if (!settings) { + remove(g); + return; + } + setSel(null); + setPick(false); + setPicked((p) => (p && p.from === g.from && p.to === g.to ? null : { from: g.from, to: g.to })); + }, + [settings, remove, setSel], + ); + + /** One of the picked gap's own settings changed (its mark, its why): one write, an undo point, Undo here. */ + const editPicked = useCallback( + (change: Omit<GapEdit, "at">) => { + const g = pickedGap; + if (!g) return Promise.resolve(false); + const edit: GapEdit = { at: Number(((g.from + g.to) / 2).toFixed(3)), ...change }; + let next: Span[]; + try { + next = editGaps(gaps, { edit }); + } catch (e) { + setNote(e instanceof Error ? e.message : String(e)); + return Promise.resolve(false); + } + const said = [ + "mark" in change ? `its mark ${change.mark === true ? "on" : change.mark === false ? "off" : "as the clip's"}` : null, + "why" in change ? `cut for ${change.why === "dead-air" ? "dead air" : change.why ?? "no reason given"}` : null, + "reason" in change ? (change.reason ? `its mark says “${change.reason}”` : "its own words dropped") : null, + "corner" in change ? `its mark at ${change.corner ?? "the clip's corner"}` : null, + ].filter(Boolean).join(", "); + return run({ edit }, next, `the gap ${fmt(g.from)}–${fmt(g.to)}: ${said}`); + }, + [pickedGap, gaps, run, setNote, fmt], + ); + /** `G`: the gap the playhead is in (or at the edge of). */ const removeAt = useCallback( (t: number | null) => { const g = t == null ? null : gaps.find((x) => t >= x.from - 0.05 && t <= x.to + 0.05); if (!g) { - setNote("the playhead is not on a gap — play to it, or click its band"); + setNote(settings ? "the playhead is not on a gap — play to it, or pick its band and Remove" : "the playhead is not on a gap — play to it, or click its band"); return; } remove(g); }, - [gaps, remove, setNote], + [gaps, remove, setNote, settings], ); const undoLast = useCallback(() => { @@ -197,7 +281,7 @@ export function useGapEditor({ [span.from, span.to, gaps, refusal, setNote, fmt, wall, setSel], ); - return { sel, setSel, live, pick, setPick, undo, cut, remove, removeAt, undoLast, select }; + return { sel, setSel, live, pick, setPick, undo, cut, remove, removeAt, undoLast, select, settings, picked: pickedGap, setPicked, band, editPicked }; } export type GapEditor = ReturnType<typeof useGapEditor>; diff --git a/umtool/components/projects/review/GapMarkChip.tsx b/umtool/components/projects/review/GapMarkChip.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { GAP_CUE_LOOK } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; + +// THE GAP MARK OVER A PLAYER (lane gap-cue, slice 1b): "» 27 s" at a clip gap's join, drawn where the render +// draws it -- Play the cut over its footage, the clip bench over its picture -- at the second +// lib/report/gapCueView.mjs says (common gapCue.mjs's timing, the build's own). The look is common GAP_CUE_LOOK, +// the numbers the build's drawtext reads (gap-mark.mjs), in the frame's proportions (cqmin: the frame's short +// side): Plex Mono Bold, the box round it in ems, its border, the inset; the box over the border's colour inside +// the border, as the build lays its two boxes; the text, its box and its border faded together. Nothing to press. +// +// box where the mark stands inside the frame (Play's deck: the footage's rect, in % of the frame); the whole +// frame when absent +// aspect the picture is fitted inside this element (object-contain: the bench's <video>): its rect is measured, +// and the picture is the frame + +export type GapMarkCorner = "tl" | "tr" | "bl" | "br"; + +/** `#rrggbb` at `a`, for CSS. */ +const rgba = (hex: string, a: number) => { + const n = Number.parseInt(hex.replace(/^#/, ""), 16); + return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${a})`; +}; + +export default function GapMarkChip({ + mark, + corner, + box = null, + aspect = null, + testId = "gap-mark", +}: { + mark: { text: string; alpha: number } | null; + corner: GapMarkCorner; + box?: { left: string; top: string; width: string; height: string } | null; + aspect?: number | null; + testId?: string; +}) { + const el = useRef<HTMLDivElement | null>(null); + const [size, setSize] = useState<{ w: number; h: number } | null>(null); + useEffect(() => { + const node = el.current; + if (!node || !aspect) return; + const ro = new ResizeObserver(() => setSize({ w: node.clientWidth, h: node.clientHeight })); + ro.observe(node); + setSize({ w: node.clientWidth, h: node.clientHeight }); + return () => ro.disconnect(); + }, [aspect]); + // The picture's rect in a fitted player, as CensorOverlay measures it. + let frame: React.CSSProperties = { inset: 0 }; + if (aspect && size && size.w > 0 && size.h > 0) { + const k = Math.min(size.w / aspect, size.h); + frame = { left: (size.w - k * aspect) / 2, top: (size.h - k) / 2, width: k * aspect, height: k }; + } + const L = GAP_CUE_LOOK; + const inset = `${L.inset * 100}cqmin`; + const at: React.CSSProperties = { + [corner.startsWith("t") ? "top" : "bottom"]: inset, + [corner.endsWith("l") ? "left" : "right"]: inset, + }; + return ( + <div ref={el} data-testid={testId} data-gap-mark-layer={corner} aria-hidden className="pointer-events-none absolute inset-0 z-[4] overflow-hidden"> + <div className="absolute" style={{ ...frame, containerType: "size" }}> + <div className="absolute" style={box ?? { inset: 0 }}> + {mark && ( + <span + data-gap-mark-chip={mark.text} + data-gap-mark-alpha={mark.alpha.toFixed(2)} + className="absolute whitespace-nowrap font-mono font-bold leading-[1.2]" + style={{ + ...at, + fontSize: `max(9px, ${L.font * 100}cqmin)`, + padding: `${L.pad}em`, + color: L.fg, + border: `max(1.5px, ${L.stroke * 100}cqmin) solid ${rgba(L.strokeColor, L.strokeAlpha)}`, + // The build's two boxes: its box over the border's colour (gap-mark.mjs gapMarkFilters). + background: `linear-gradient(${rgba(L.box, L.boxAlpha)}, ${rgba(L.box, L.boxAlpha)}), ${rgba(L.strokeColor, L.strokeAlpha)}`, + backgroundClip: "padding-box", + opacity: mark.alpha, + // Never off its box: a long label and reason end "…" (the build shrinks the face first: gap-mark.mjs gapMarkFit). + maxWidth: `calc(100% - ${2 * L.inset * 100}cqmin)`, + overflow: "hidden", + textOverflow: "ellipsis", + }} + > + {mark.text} + </span> + )} + </div> + </div> + </div> + ); +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -117,8 +117,10 @@ export type PlayEntry = { end?: number; cutStart?: number | null; cutEnd?: number | null; - /** Seconds taken out of its middle (gaps.mjs): one item of jump cuts. */ - gaps?: { from: number; to: number }[]; + /** Seconds taken out of its middle (gaps.mjs): one item of jump cuts; each with its own mark and why when it says. */ + gaps?: { from: number; to: number; mark?: boolean; why?: string }[]; + /** The mark at its gaps' joins (common gapCue.mjs clipGapCueOf), only when a gap of it is marked. */ + gapCue?: { mark: boolean; min: number; corner: string; label: string }; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; /** Its hidden regions (clip-censor.mjs censorRegionsOf): drawn over the picture as the cut hides them. */ censor?: CensorRegion[]; diff --git a/umtool/components/projects/review/playCore.tsx b/umtool/components/projects/review/playCore.tsx @@ -3,7 +3,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { footageAt } from "@/lib/report/footage-move.mjs"; import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs"; -import { chromeTime, playPlan, skipEntries } from "@/lib/report/playCut.mjs"; +import { chromeTime, gapJoins, playPlan, skipEntries } from "@/lib/report/playCut.mjs"; +import { gapMarkAt, gapMarkCorner, playGapMarks } from "@/lib/report/gapCueView.mjs"; +import GapMarkChip from "./GapMarkChip"; import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck"; import { fullFrameItems, layerOffOver } from "umtool-report-to-video/full-frame"; import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type FullFrameTraits, type Rect } from "../OnscreenSection"; @@ -376,6 +378,14 @@ export function PlayStage({ core, basic = false, plainClassName }: { core: PlayC const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => ( <canvas ref={engine.canvasRef} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} /> ); + // The mark at a gap's join (lane gap-cue): the render's, at Play's joins on the cut's clock (lib/report/gapCueView.mjs). + const cueEntry = item?.clip ? entryOf.get(item.id) : null; + const gapMarks = useMemo( + () => (item?.clip && cueEntry?.gapCue ? playGapMarks(gapJoins(item), { cue: cueEntry.gapCue, entryGaps: cueEntry.gaps ?? [], playEnd: item.clip.playEnd }) : []), + [item, cueEntry], + ); + const gapMark = gapMarks.length ? gapMarkAt(gapMarks, t) : null; + const gapCorner = gapMarkCorner(gapMark?.corner ?? cueEntry?.gapCue?.corner, { deck: !!doc }); const sideNow = item && sideEntry ? <SidePostOverlay project={project} take={take} clipId={item.id} side={sideEntry} s={Math.max(0, t - item.start)} published={asPublished} /> : null; const postPlayer = (box2: { width: number; height: number }) => postNow ? ( @@ -498,6 +508,9 @@ export function PlayStage({ core, basic = false, plainClassName }: { core: PlayC {introCard} {placeholderCard} {sideNow && rect && <div className="pointer-events-none absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }}>{sideNow}</div>} + {gapMarks.length > 0 && rect && ( + <GapMarkChip mark={gapMark} corner={gapCorner} box={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }} testId="play-gap-mark" /> + )} {/* Over a full-frame item (full-frame.mjs) a layer that keeps no time of its own is not drawn (layerOff): kept mounted, transparent, so its page is ready and seeked when the item after it comes up. The feed follows the deck (followsDeck), as the deck's own page does: off over a video entry or an analysis item. */} @@ -539,6 +552,7 @@ export function PlayStage({ core, basic = false, plainClassName }: { core: PlayC {!basic && introCard} {!basic && placeholderCard} {!basic && sideNow} + {!basic && gapMarks.length > 0 && <GapMarkChip mark={gapMark} corner={gapCorner} testId="play-gap-mark" />} </div> )} {dipVeil} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -53,9 +53,9 @@ Inbox cannot disagree about what is wrong with one. | `reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo [--dry-run]` | **Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace -- These reads only while the draft is still exactly what it left (a re-read landing or any edit since: refused, said why), an Everywhere back to the entry it changed (its spoken form and note) or the entry it added removed; `--dry-run` says which, or why not. A flag a subcommand does not take is refused; `--` ends the flags. | | `reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new|--old [--only <id>,…] [--dry-run] [--json]` | **the re-read queue** (`lib/report/readsQueue.mjs`): the stale reads (or `--only` those) queued on the app's durable queue (`umtool queue ls`), ONE step per item in cut order, none waiting on another — `reads <p> reread --one <item> --only <ids>`, which judges the item again and runs the item's bench command (`readAgainArgv.mjs`: a post's take as the bench asks it, `--bench-slurs`; a thread piece's `--for`/`--tuned … reading:next`; a card's own reading), the tuning a plain press asks (only what the line owned). The editor's `tts-file` jobs, one at a time; render mode holds them. A re-read joins its list UNPICKED. `queue` says each row's state and, in one sentence, why they wait; `--stop` cancels what has not started; `--retry` puts one back. `pick --new` makes every unpicked re-read play, `--old` goes back to what played before (a card: its old words and reading) — one undo point. | | `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) | -| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) | +| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)), its **gaps** `gap.add=12.3-15.1` `gap.remove=<sec>` `gaps=…` and a gap's own `gap.mark=<sec>:on|off|default` `gap.why=<sec>:dead-air|idle|other|default` `gap.reason=<sec>:<words>` (its mark says them) `gap.corner=<sec>:tl|tr|bl|br|default`, the **mark at its gaps' joins** `gapCue.mark=true` `gapCue.min` `gapCue.corner` `gapCue.label` over the project's `render.gapCue` (`gapCue=` clears it; [knobs.md](knobs.md#gaps-inside-a-clip)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) | | `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) | -| `look <project> key=value … [--unset render.<key>]… [--take <t>]` | the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** | +| `look <project> key=value … [--unset render.<key>]… [--take <t>]` | the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades), `gapCue=<json>` (the mark at the joins clips' gaps leave, `{"mark":true}`; [knobs.md](knobs.md#gaps-inside-a-clip)) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** | | `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) | | `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -40,7 +40,8 @@ that generates it ([notes.md](notes.md)). | `chapter` — the entry's name in the chapter list (`out/…chapters`, `youtube.txt`, `umtool export --format chapters`): one line of at most 100 characters. An authored `chapter` wins over the entry's on-screen title (under the deck) and the line derived from its record; without one the list is as before. Any entry, a post item too | — | `umtool set <p> <entry> chapter='The weigh-in'` (`chapter=` clears it; `--take <t>` writes the take's patch, the project's manifest untouched) | — | | `fx.zoom` — `{shot, focus, at?, hold?}`: a screenshot (a file in the project; a bare name under its `shots/` is written as `shots/<name>`) that comes up over the footage and pushes in on `focus` (`[left, top, right, bottom]`, fractions of the shot) — drawn once `render.chrome.fx.zoom` is on ([Effects](#effects)). **How long it stays**: up 0.2 s into the clip's clean span (rising in over 0.38 s), its focus box drawn 0.55 s later, the push at `at` (seconds into the clip; default as soon as the box has drawn) over 1 s, then a slow drift on the detail; it leaves with a 0.3 s fade 0.3 s before the clip's clean span ends — or, with `hold` (0.5–10 s), that long after the push lands (never past the clip's own leave) | — | `umtool set <p> <clip> fx.zoom='{"shot":"shots/x.png","focus":[0.1,0.2,0.9,0.4],"at":5.9,"hold":4}'` (`fx.zoom=` clears it) | `PUT /api/report/window {project, clip, "fx.zoom": {…} \| null}` | | `fx.receipts`, `fx.punch`, `fx.quote`, `fx.punchIn`, `fx.speakers` — the clip's other effect fields (`[{shot, mark?, at?, hold?, label?}]` 1–4, `at` the source second a receipt flies in at (default: as the clip comes up), `hold` 0.5–10 s it stays once landed (on every one: they leave then, not with the clip), `label` a line of at most 80 characters in a band under the screenshot (when it was taken, what it is); the words to punch; `false`: no line; 1–8 source seconds inside the clip; `[{at, who: 0\|1}]`), each inert until its effect is on; `fx` is all of them at once. Checked by the build's own `validateFxEntries` | — | `fx.punch="the words"` `fx.punchIn='[231.4]'` · `fx='{…}'` sets them all, `fx=` clears every one | `PUT /api/report/window {project, clip, fx}` (or one `"fx.<field>"`) | -| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band puts it back (`G`: the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps}` | +| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band picks it: its settings and **Remove** under the waveform (`G`: put back the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` · a gap's own: `gap.mark=12.3:off` `gap.why=12.3:dead-air` `gap.reason=12.3:walks off` `gap.corner=12.3:tr` (`…:default`, `gap.reason=12.3:` drop one) | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps \| gapEdit}` | +| `gapCue` — `{mark?, min?, corner?, label?}`: the mark at this clip's gaps' joins, over the project's `render.gapCue` ([below](#gaps-inside-a-clip)) | clip bench, under the waveform: **mark at joins**, **from** (s), **corner**, **label** | `umtool set <p> <clip> gapCue.mark=true gapCue.corner=tr` (`gapCue=` clears it) | `PUT /api/report/window {project, clip, token, gapCue}` | `key=` (nothing after the `=`) clears a knob; in umtool, **Clear** beside a field (Audio: **Clear all**). A claim's knobs are read from the clip that **stamps** it — the last clip carrying the claim id; the box on any other @@ -271,7 +272,59 @@ seconds (`report-to-video/gaps.mjs` is the rule and both clocks). phrase: gaps are not applied there (noted). Absent or `[]`, the render is byte for byte what it was. - **The bench** draws each gap as a hatched band on the waveform (and on the cue rail); every playback there skips them as the cut will. Gap writes go through the one window writer at once (not drafted like the edges), each an undo - point (`auto-before-gaps`: `umtool timeline <p> undo`), and **Undo** beside them writes the list back. + point (`auto-before-gaps`: `umtool timeline <p> undo`), and **Undo** beside them writes the list back. A click on a + band picks the gap (outlined): the row under the waveform shows its seconds, how it shows (skip; fast-forward is not + built yet), its **mark** (as the clip's, on, off), **why** (dead air, idle, other), its own words, its **corner**, + what its mark will say, and **Remove**. Beside it, the clip's **mark at joins** (as the project's, on, off), **from** + (its `min`), **corner** and **label**. Every control writes what its CLI twin writes (each one's tooltip names it): + a gap's through `gapEdit`, the clip's through `gapCue`, each an undo point (a write that changes nothing takes + none). A reel beat's band keeps its old click (it puts the gap back): a beat's gap has no settings. A gap grown over + others (**Cut gap** on a span touching one, `gap.add=`, `--gap`) keeps what they said of themselves: `why` and + `reason` when they all gave the same, the first `corner`, and its `mark` on when any was (off only when all were); + the bench's note says what it kept. +- **The mark at the join** (`render.gapCue`, off by default; common `lib/report/gapCue.mjs` is the rule, + `report-to-video/gap-mark.mjs` draws it): with `mark` on, each join a gap of `min` seconds or more (default 2) leaves + shows a small `» 27 s` near a corner of the footage for 1.1 s -- up over 0.15 s, held, down over 0.35 s; no sound. + It says the gap's reason when it has one: `» 26 s · dead air` (`label` is `» {s}[ · {why}]` by default: `{s}` the + time skipped, from a minute `1:12`; `{why}` the reason; a part in `[ ]` drawn only with one). The reason is the + gap's own words (`reason`, 1-24 characters) or its `why`'s word: `dead-air` "dead air", `idle` "idle", `other` + nothing. THE LOOK is one set of numbers, common `GAP_CUE_LOOK`, which the build's drawtext and umtool's pages both + read: IBM Plex Mono Bold at 3 % of the frame's short side (32 px at 1080), light text on a #101010 box at 86 % inside + a 2 px white border at 90 %, the box 0.38 em round the text, inset 2.6 %; the text, box and border fade together. + Joins less than 1.1 s apart are ONE mark saying their seconds together (and their reason only when they all give + the same). It is drawn into the clip's segment after its hidden regions and its blur (chrome over the footage, + never blurred), at the layout's free corner (`corner: auto`): the deck's footage bottom left (its stamp stands top + left, its posts top right), the plain cut's picture top left (never the corner code's corner), a vertical clip's + picture top left (framed, quote), its picture's top right (split: its captions are at the picture's foot) or the + safe area's top right (full bleed, desktop), and a twocrop clip's crop one top right -- every vertical mark inside + the safe area, whatever corner is asked; a hidden region up while the mark is, or a code, under that corner moves + it to the next free one. A mark too wide for its box (a long label with a long reason on a 1080-wide frame) is + drawn smaller, down to 75 % of its size, then cut to fit, ending `…`: never off its box. Its text is drawn as + written (`expansion=none`): a `%` or a `\` in a label or a reason is words; a tab or any other control character + is refused there. A clip cut from its pieces marks the join between two pieces too (the recording's seconds left + out, even with no pad between them). **The automatic corner + knows only our own hidden regions and codes, not what a stream burned into its picture** (a chat bottom left, a + banner, a camera box): on such footage set the corner -- the clip's `gapCue.corner`, or one gap's own `corner` + (`gap.corner=<s>:tr`; a stream's layout can change inside one clip), which wins over the clip's. Precedence: a gap's + own `mark` and `corner` over its clip's `gapCue` over `render.gapCue` (a look key: a preset, a style or a take patch + carries it -- `umtool look <p> gapCue='{"mark":true}'`, `umtool take <p> --id marks --set render.gapCue.mark=true`; + the Media tab's Modules panel, **Gap mark**). Turning it on re-renders only the segments of clips with a + marked gap of `min` or more, and the chunks over them; off, unset or under `min`, every segment is byte for byte + what it was (its key is the same). Not drawn: a montage (it applies no gaps), `render.mode: basic` and **Export + one clip** (the footage alone); a trailer beat cut across a marked join plays the master's mark. **Play the cut and + the bench draw it too**, at the same seconds with the same text and look (`lib/report/gapCueView.mjs` lays out the + joins and asks gapCue.mjs, the build's own timing): Play over the deck's footage or the plain picture, the bench over + its picture. Where the pages differ from the render: they do not move it off a hidden region or a code as the build + does; a vertical cut's page uses the deck's or the plain cut's corner; **Play stands it in the corner of the deck's + footage box**, where the render stands it in the corner of the picture as fitted in that box (a 4:3 source in a 16:9 + box: the render's mark is that much further in); and **the bench sizes it from the source picture** (3 % of its + short side as shown), where the render sizes it from the output frame's. A long text the pages cut with `…` at the + box's width, without first drawing it smaller. The record says where each was drawn (`gapMarks` in + `segments/<id>.cut.json`: its text as drawn, its corner and rect, the corner it asked for). +- **`--chrome-only` rebuilds no clip segment**, and the mark is in the segment: a mark changed since the segment was + built (turned on or off, its label, a gap's reason or corner) is laid as it was built, and the build says so, one + note per clip (`<id>: its gap mark changed since its segment was built (…) — --chrome-only rebuilds no clip + segment: build without it (or --only <id>) to draw it`). - **Play the cut** plays the clip as one item: its sound one span per kept piece on the cut's clock with the same fades, the picture past the gap at the join, the clock and the scrub bar in cut seconds, a dashed tick on the reel strip at each jump. @@ -2956,6 +3009,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr | [Teaser](#teaser) `teaser` | A full-frame card of lines popping in on the beat, inserted as its own segment. (a segment cut into the timeline) | -- | | [Intro](#intro) `intro` | The brand sting the cut opens with, a site's name swapped in on the chime. (a segment cut into the timeline) | `render.intro` | | [Blur](#blur) `blur` | A clip's picture blurred at its encode, a caption on it, the sound as recorded. (a filter on the footage) | `render.blur` | +| [Gap mark](#gap-mark) `gap-cue` | A small mark at each join a clip's gap leaves, saying how much was skipped. (a filter on the footage) | `render.gapCue` | | [Posts feed](#posts-feed) `feed` | The cut's posts in a column beside the footage, each ticking in as its clip starts. (a page over the whole cut) | `render.chrome.deck.posts` | | [Popup posts](#popup-posts) `popup-posts` | A clip's posts as cards over the footage, each window its own short page at its own second. (pages at their own seconds) | `render.chrome.deck.posts` | | [Stamps](#stamps) `stamp` | Each counted mark's word, stamped over the footage as it lands. (a page over the whole cut) | `render.chrome.factcheck.stamp` | @@ -3048,6 +3102,7 @@ The pip track along the top of the deck; the markers' flags stand over it ([mark | `deck.pip.sectionColor0` | the section before the first marker, with `color: "section"`: a `#hex` or a palette key (`fg`, `muted`, `accent`, `amber`, `dim`) · default the accent | `umtool look <p> deck.pip='{"color":"section","sectionColor0":"#5fa8d3"}'` | | `deck.markers[].label` | optional: a marker with none (or `""`) draws a tick at its boundary, no words, and takes no band over the track | `umtool look <p> deck.markers='[{"after":"c04","color":"#e07a9a"}]'` | | `deck.markers[].level` | `1` (a section, the default) · `2` (a subsection of the section before it: a shorter flag or a half-height tick, its label smaller and quieter, and in sections no colour of its own -- its pips, fuse and ring keep its section's; to every edit a section like any other; the cut's first marker must be a section) · at most 32 markers in all; past a dozen labelled, a label too crowded to say anything is drawn as a tick | `umtool look <p> deck.markers='[{"after":"c04","label":"Early days","level":2}]'` | +| a rail of one or two pips | never drawn (deck.mjs `RAIL_MIN_PIPS`, 3): a cut -- or a window take, which lays only the clips it covers -- of one or two clips draws no pip track, no fuse, no marker and no flags; the stacked deck no rail and no count; the finale no large rail. Nothing moves into the room. No setting draws one under three | — | | `deck.rail.labels` | `false` draws every marker as a tick, no words, and no band over the track (the current section's name can stand under the rail instead: [Section title](#section-title)) · default `true` | `umtool look <p> deck.rail='{"labels":false}'` | ### Counter @@ -3121,6 +3176,19 @@ The full reference is [A clip's picture, blurred](#a-clips-picture-blurred). | `render.blur` | `on` · `off` (the uncensored variant) · default `on` | `umtool look <p> blur=off` | | a clip's `blur` | `{on, caption?, strength?, from?, to?}` -- caption ≤ 120, strength 2–15 (default 5) | `umtool set <p> <clip> blur.on=true` | +### Gap mark + +The full reference is [Gaps inside a clip](#gaps-inside-a-clip) (the mark at the join). + +| Knob | Range · default | From a terminal | +|---|---|---| +| `render.gapCue.mark` | `true` · `false` · default `false` (off: every cut renders as it did) | `umtool look <p> gapCue='{"mark":true}'` · a take: `--set render.gapCue.mark=true` | +| `render.gapCue.min` | 0.5–60 s · default 2 (a shorter gap draws nothing) | `umtool look <p> gapCue='{"min":4}'` | +| `render.gapCue.corner` | `auto` (the layout's free corner) · `tl` · `tr` · `bl` · `br` · default `auto` | `umtool look <p> gapCue='{"corner":"br"}'` | +| `render.gapCue.label` | text holding `{s}` (the time skipped: `27 s`, from a minute `1:12`) and maybe `{why}` (the gap's reason); a part in `[ ]` is drawn only when the gap has one; at most 40 characters · default `» {s}[ · {why}]` (`» 27 s`, `» 26 s · dead air`) | `umtool look <p> gapCue='{"label":"{s} later"}'` | +| a clip's `gapCue` | the same keys, over the project's | `umtool set <p> <clip> gapCue.mark=false gapCue.corner=tr` (`gapCue=` clears them) | +| a gap's `mark`, `why`, `reason`, `corner` | `mark` `true` · `false` (over the clip's and the project's); `why` `dead-air` · `idle` · `other` (the mark says "dead air", "idle", nothing); `reason` its own words, 1-24 characters, said instead; `corner` `tl` · `tr` · `bl` · `br` (its mark there, over the clip's) | `umtool set <p> <clip> gap.mark=12.3:off gap.why=12.3:dead-air gap.reason=12.3:walks off gap.corner=12.3:tr` (`…:default`, `gap.reason=12.3:` drop one) · the bench: click the gap's band | + ### Posts feed `deck.posts.layout: "feed"` with posts to draw: a column for the whole cut, each post ticking in as its clip starts; no hold, no footage move. Shares `deck.posts` with the popup posts. diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -2000,6 +2000,19 @@ makeMediaScenesFixture({ reports, deckManifest }); mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4")); } +// The gap mark (lane gap-cue, slice 1b; gap-cue.spec.ts), which WRITES (the spec puts the gaps and the settings back +// before each test): gc01 gapcuevid 0.5-8.5 and gc02 1.0-3.0, both locked, on the tone window cached as +// gapcuevid_0.00-9.00.mp4 -- the gaps fixture's shape, its own project so the two specs never share a manifest. +{ + const g = manifest("gapcue-fixture", "The Gap Mark Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "gc01", video: "gapcuevid", start: 0.5, end: 8.5, cite: 1, section: 0, lock: true, quote: "a clip with a marked gap" }, + { type: "clip", id: "gc02", video: "gapcuevid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "the clip after it" }, + ]); + g.render.fetchPad = 0; + const dir = writeProject("gapcue-fixture", g); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapcuevid_0.00-9.00.mp4")); +} // Fetch more from where the edge is now (clip-bench.spec.ts): one clip, r01 reachvid 300-306, on a // recording a thousand seconds long; nothing cached -- the spec fetches through the editor stub. writeProject( diff --git a/umtool/e2e/gap-cue.spec.ts b/umtool/e2e/gap-cue.spec.ts @@ -0,0 +1,180 @@ +import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { readFileSync, readdirSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// The gap mark set and seen in umtool (lane gap-cue, slice 1b; common +// lib/report/gapCue.mjs is the rule, lib/report/gapCueView.mjs lays it out on a +// page's clock): +// +// - the bench: a click on a gap's band picks it; its mark, why, own words and +// corner, and the clip's mark settings, each written through the window +// route (gapEdit / gapCue) as an undo point; the bench's Undo; Remove +// - Play the cut: the mark is up at the join for its life, then gone, saying +// the gap's reason +// - the Modules panel: the project's label, and the mark in Play says it +// +// Fixture: gapcue-fixture (make-fixture.mjs), which this spec WRITES: gc01 +// gapcuevid 0.5-8.5 and gc02 1.0-3.0, on the tone window gapcuevid_0.00-9.00.mp4. +// Every test starts from one gap, 3.5-5.5 (2 s: the default shortest marked), +// and no mark settings. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PROJECT = "reports/gapcue-fixture"; +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "gapcue-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +type Gap = { from: number; to: number; mark?: boolean; why?: string; reason?: string; corner?: string }; +type Manifest = { render: { gapCue?: Record<string, unknown> }; timeline: { id: string; gaps?: Gap[]; gapCue?: Record<string, unknown> }[] }; +const read = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as Manifest; +const clipOf = (id = "gc01") => read().timeline.find((e) => e.id === id)!; +const undoPoints = () => { + try { + return readdirSync(path.join(DIR, "revisions")).filter((f) => f.includes("auto-before-gaps")).length; + } catch { + return 0; + } +}; + +const token = async (request: APIRequestContext, clip = "gc01") => + ((await (await request.get(`/api/report/clip?project=${encodeURIComponent(PROJECT)}&clip=${clip}`)).json()) as { token: string }).token; +const putWindow = async (request: APIRequestContext, data: Record<string, unknown>, clip = "gc01") => + request.put("/api/report/window", { data: { project: PROJECT, clip, token: await token(request, clip), ...data } }); +const putLook = async (request: APIRequestContext, patch: Record<string, unknown>) => { + const t = ((await (await request.get(`/api/report/render?project=${encodeURIComponent(PROJECT)}`)).json()) as { token: string }).token; + return request.put("/api/report/render", { data: { project: PROJECT, token: t, patch } }); +}; + +const openBench = async (page: Page) => { + await page.goto(urls.clipBenchHref(PROJECT, "gc01")); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(page.locator("[data-gap-band]")).toHaveCount(1); +}; + +test.beforeEach(async ({ request }) => { + test.setTimeout(120_000); + let r = await putWindow(request, { gaps: [{ from: 3.5, to: 5.5 }], gapCue: null }); + expect(r.ok(), await r.text()).toBeTruthy(); + r = await putLook(request, { gapCue: null }); + expect(r.ok(), await r.text()).toBeTruthy(); +}); + +test("the bench: a gap's band picks it; its mark, why, words and corner, and the clip's settings, are written as the CLI writes them, each an undo point", async ({ page }) => { + await openBench(page); + const row = page.locator("[data-gap-picked-row]"); + await expect(row).toHaveCount(0); + // The clip's settings are there with a gap, each saying the project's. + await expect(page.locator("[data-gap-cue-mark]")).toContainText("as the project"); + await page.locator("[data-gap-band]").click(); + await expect(page.locator("[data-gap-band][data-gap-picked]")).toHaveCount(1); + await expect(row).toBeVisible(); + // Fast-forward is said, not offered. + await expect(row.locator("[data-gap-show=skip]")).toContainText("fast-forward: not built yet"); + + // Its mark on: gapEdit, an undo point. The picture is the SAME <video> before and after the first mark appears + // over it (review 1, 5: it used to be replaced, its playback and the player's session lost). + const videoEl = page.getByTestId("clip-video"); + await expect(videoEl).toHaveCount(1); + await videoEl.evaluate((el) => { + (el as HTMLVideoElement).dataset.keep = "the same element"; + }); + const before = undoPoints(); + await row.locator("[data-gap-mark-select]").selectOption("on"); + await expect.poll(() => clipOf().gaps?.[0]?.mark).toBe(true); + expect(undoPoints()).toBeGreaterThan(before); + await expect(page.locator("[data-gap-mark-layer]")).toHaveCount(1); + await expect(page.locator('[data-testid="clip-video"][data-keep="the same element"]')).toHaveCount(1); + // Its why: the mark says it. + await row.locator("[data-gap-why-select]").selectOption("dead-air"); + await expect.poll(() => clipOf().gaps?.[0]?.why).toBe("dead-air"); + await expect(row.locator("[data-gap-says]")).toHaveAttribute("data-gap-says", "» 2 s · dead air"); + // Its own words, then its corner. + await row.locator("[data-gap-reason]").fill("walks off"); + await row.locator("[data-gap-reason]").press("Enter"); + await expect.poll(() => clipOf().gaps?.[0]?.reason).toBe("walks off"); + await expect(row.locator("[data-gap-says]")).toHaveAttribute("data-gap-says", "» 2 s · walks off"); + await row.locator("[data-gap-corner-select]").selectOption("tr"); + await expect.poll(() => clipOf().gaps?.[0]?.corner).toBe("tr"); + // The bench's Undo takes the last one back; the seconds never moved. + await page.locator("[data-gap-undo]").click(); + await expect.poll(() => clipOf().gaps?.[0]?.corner).toBeUndefined(); + expect(clipOf().gaps?.[0]).toMatchObject({ from: 3.5, to: 5.5, mark: true, why: "dead-air", reason: "walks off" }); + // Off, and back to the clip's. + await row.locator("[data-gap-mark-select]").selectOption("off"); + await expect.poll(() => clipOf().gaps?.[0]?.mark).toBe(false); + await row.locator("[data-gap-mark-select]").selectOption(""); + await expect.poll(() => clipOf().gaps?.[0]?.mark).toBeUndefined(); + + // The clip's own: gapCue on the window route, an undo point. + const before2 = undoPoints(); + await page.locator("[data-gap-cue-mark]").selectOption("on"); + await expect.poll(() => clipOf().gapCue?.mark).toBe(true); + await page.locator("[data-gap-cue-corner]").selectOption("br"); + await expect.poll(() => clipOf().gapCue?.corner).toBe("br"); + await page.locator("[data-gap-cue-min]").fill("1.5"); + await page.locator("[data-gap-cue-min]").press("Enter"); + await expect.poll(() => clipOf().gapCue?.min).toBe(1.5); + expect(undoPoints()).toBeGreaterThan(before2); + await page.locator("[data-gap-cue-corner]").selectOption(""); + await expect.poll(() => clipOf().gapCue?.corner).toBeUndefined(); + + // Remove puts the seconds back. + await row.locator("[data-gap-remove]").click(); + await expect.poll(() => clipOf().gaps).toBeUndefined(); + await expect(row).toHaveCount(0); +}); + +/** Play the cut, from the start, until cut second `until`: every (t, chip text) seen. */ +const playAndWatch = async (page: Page, until: number) => { + await page.goto(urls.playHref(PROJECT, {})); + const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(page.locator("[data-gap-mark-layer]")).toHaveCount(1); + await page.locator("[data-play-toggle]").click(); + const seen: { t: number; text: string | null }[] = []; + await expect + .poll(async () => { + const t = Number(await root.getAttribute("data-play-t")); + const chip = page.locator("[data-gap-mark-chip]"); + seen.push({ t, text: (await chip.count()) ? await chip.getAttribute("data-gap-mark-chip") : null }); + return t; + }, { timeout: 30_000, intervals: [80] }) + .toBeGreaterThan(until); + await page.keyboard.press("k"); + return seen; +}; + +test("Play the cut: the mark is up at the join for its life, saying the gap's reason, and gone after", async ({ page, request }) => { + expect((await putWindow(request, { gapEdit: { at: 4.5, why: "dead-air" } })).ok()).toBeTruthy(); + expect((await putLook(request, { gapCue: { mark: true } })).ok()).toBeTruthy(); + // gc01 plays 0.5-8.5 less 3.5-5.5: its join 3 s into the cut, the mark up 3-4.1. + const seen = await playAndWatch(page, 5); + console.log(`gap-cue: ${seen.map((s) => `${s.t.toFixed(2)}=${s.text ?? "-"}`).join(" ")}`); + const up = seen.filter((s) => s.t > 3.2 && s.t < 3.9); + expect(up.length, "sampled while it is up").toBeGreaterThan(0); + for (const s of up) expect(s.text).toBe("» 2 s · dead air"); + for (const s of seen.filter((x) => x.t < 2.9 || (x.t > 4.2 && x.t < 5))) expect(s.text).toBeNull(); +}); + +test("the Modules panel: the project's label, and Play's mark says it", async ({ page, request }) => { + expect((await putLook(request, { gapCue: { mark: true } })).ok()).toBeTruthy(); + await page.goto(urls.section(PROJECT, "onscreen")); + const card = page.getByTestId("module-gap-cue"); + await expect(card).toBeAttached({ timeout: 60_000 }); + await card.locator("summary").click(); + await card.getByTestId("module-field-gap-cue-label").fill("{s} later"); + await card.getByTestId("module-save-gap-cue").click(); + await expect(card.getByTestId("module-status-gap-cue")).toHaveText("saved"); + await expect.poll(() => read().render.gapCue).toEqual({ mark: true, label: "{s} later" }); + // Cleared there, it clears (the writer merges: the panel sends null). + await card.getByTestId("module-field-gap-cue-label").fill(""); + await card.getByTestId("module-save-gap-cue").click(); + await expect.poll(() => read().render.gapCue).toEqual({ mark: true }); + await card.getByTestId("module-field-gap-cue-label").fill("{s} later"); + await card.getByTestId("module-save-gap-cue").click(); + await expect.poll(() => read().render.gapCue?.label).toBe("{s} later"); + const seen = await playAndWatch(page, 4.5); + expect(seen.filter((s) => s.t > 3.2 && s.t < 3.9).map((s) => s.text)).toContain("2 s later"); +}); diff --git a/umtool/e2e/gaps-zoom.spec.ts b/umtool/e2e/gaps-zoom.spec.ts @@ -13,7 +13,7 @@ import * as urls from "./urls"; // silences; at fit it is what it always was // - a span selected on the waveform (Select a gap, or Alt + drag) is cut out // of the clip through the window writer; Undo puts the list back; a click -// on a gap's band removes it; a span the build would refuse is refused here +// on a gap's band picks it, its Remove puts it back; a span the build would refuse is refused here // - the bench's playback skips a gap, as the cut will // - Play the cut plays the clip as ONE item of jump cuts: the render's // footage less the gap, one sound node per kept piece, the picture past @@ -204,8 +204,10 @@ test("a gap: selected on the waveform, cut, undone; Alt + drag and g; a click on await expect.poll(() => clipOf("g01").gaps?.length ?? 0).toBe(1); expect(clipOf("g01").gaps![0].from).toBeCloseTo(4, 1); - // A click on the band puts the seconds back. + // A click on the band picks the gap (its settings, lane gap-cue); its Remove puts the seconds back. await page.locator("[data-gap-band]").click(); + await expect(page.locator("[data-gap-picked-row]")).toBeVisible(); + await page.locator("[data-gap-remove]").click(); await expect.poll(() => clipOf("g01").gaps).toBeUndefined(); // Too close to the clip's start: said, and nothing written. diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -347,7 +347,7 @@ export const GROUPS = [ ], docs: [ ["`set <project> <clip> key=value …`", - "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks))"], + "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)), its **gaps** `gap.add=12.3-15.1` `gap.remove=<sec>` `gaps=…` and a gap's own `gap.mark=<sec>:on|off|default` `gap.why=<sec>:dead-air|idle|other|default` `gap.reason=<sec>:<words>` (its mark says them) `gap.corner=<sec>:tl|tr|bl|br|default`, the **mark at its gaps' joins** `gapCue.mark=true` `gapCue.min` `gapCue.corner` `gapCue.label` over the project's `render.gapCue` (`gapCue=` clears it; [knobs.md](knobs.md#gaps-inside-a-clip)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks))"], ], }, { @@ -372,7 +372,7 @@ export const GROUPS = [ ], docs: [ ["`look <project> key=value … [--unset render.<key>]… [--take <t>]`", - "the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"], + "the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades), `gapCue=<json>` (the mark at the joins clips' gaps leave, `{\"mark\":true}`; [knobs.md](knobs.md#gaps-inside-a-clip)) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"], ], }, { diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -17,6 +17,7 @@ import { deckOn } from "umtool-report-to-video/deck"; import { censorRegionsOf } from "umtool-report-to-video/clip-censor"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import { effectiveManifest } from "@/lib/report/manifest.mjs"; import type { ProjectRef } from "@/lib/project-types"; // THE CLIP BENCH'S DATA, in one place: what `/projects/<p>/clip/<id>` renders @@ -134,10 +135,16 @@ export async function clipBenchData( muteFrom: ((manifest.timeline ?? []) as { id: string; muteFrom?: number }[]).find((e) => e.id === clipId) ?.muteFrom ?? null, - // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry. + // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry -- each with its own + // mark and why when it says (common gapCue.mjs). gaps: ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) ?.gaps ?? [], + // The mark at its gaps' joins, the clip's own settings (lane gap-cue), from the manifest's own entry. + gapCue: (() => { + const v = ((manifest.timeline ?? []) as { id: string; gapCue?: unknown }[]).find((e) => e.id === clipId)?.gapCue; + return v && typeof v === "object" && !Array.isArray(v) ? (v as NonNullable<ClipBenchData["clip"]["gapCue"]>) : null; + })(), // The seconds no gap may cover (claim marks, a stamp), from the manifest's own entry. marks: gapWalls({ ...(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}), type: "clip", muteFrom: null }) .marks.map((m) => ({ id: m.id, at: m.at })), @@ -166,6 +173,17 @@ export async function clipBenchData( // bench composes a preview of it; the fields are there either way. deckOn: deckOn(manifest.render ?? {}), // Every region the cut hides on it (clip-censor.mjs): the bench draws them over the raw window. + // The project's mark at gaps' joins (render.gapCue) as the build reads it: the look preset under it. + gapCue: (() => { + let render = (manifest.render ?? {}) as Record<string, unknown>; + try { + render = ((effectiveManifest(manifest) as { render?: Record<string, unknown> }).render ?? {}) as Record<string, unknown>; + } catch { + // An unknown preset: the manifest's own word (the build says what is wrong). + } + const v = render.gapCue; + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null; + })(), hidden: censorRegionsOf(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}, manifest.render ?? {}, manifest.provenance ?? {}), generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null, view, diff --git a/umtool/lib/report/gapCueView.mjs b/umtool/lib/report/gapCueView.mjs @@ -0,0 +1,112 @@ +// THE GAP MARK ON umtool's PAGES (lane gap-cue, slice 1b): the clip bench and +// Play the cut draw the mark the render draws at a gap's join ("» 27 s"), at +// the same seconds, with the same text and the same fade. Nothing here times +// a mark: the rule is common lib/report/gapCue.mjs's (gapCues, gapCueAlpha, +// gapCueText -- the build's gap-mark.mjs reads the same three), and the clocks +// are gaps.mjs's (offsetIn). This file only says which joins a page has, on +// the clock the page plays, and which mark is up at a second of it. +// +// PURE and dependency-free beyond those two: the client bundle takes it. +import { GAP_CUE_MOTION, gapCueAlpha, gapCueText, gapCues, gapMarkOn, gapOwnSays } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; +import { gappedLength, gapsWithin, offsetIn } from "umtool-report-to-video/gaps"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +/** How far a clip's own gap may sit from the one the render took out (the frame grid) and still be it. */ +const NEAR = 0.05; + +/** + * The corner a page draws the mark at: the clip's `corner`, or for `auto` the + * layout's own (gap-mark.mjs's `prefer`): the deck's footage bottom left, a + * plain cut's picture top left. + * + * @param {string | null | undefined} corner + * @param {{ deck: boolean }} layout + * @returns {"tl" | "tr" | "bl" | "br"} + */ +export function gapMarkCorner(corner, { deck }) { + if (corner === "tl" || corner === "tr" || corner === "bl" || corner === "br") return corner; + return deck ? "bl" : "tl"; +} + +/** + * Is one of the clip's own gaps (`own`, with their `mark`) the one a page + * plays from `from`–`to`: the same seconds, give or take the frame grid. + */ +const ownOf = (own, from, to) => (own ?? []).filter((c) => fin(c?.from) && fin(c?.to) && c.to > from - NEAR && c.from < to + NEAR); + +/** + * The marks of a clip played from `from` to `to` (source seconds) with its + * `gaps` (the clip's own, each with its `mark`), on the clock of what PLAYS: + * seconds from `from`, the gaps taken out -- the segment's clock, which is the + * render's. `cue` is the clip's settings (common gapCue.mjs clipGapCueOf). + * Each mark is `{ at, until, seconds, count, text }`; [] when nothing is + * marked. + * + * @param {{ cue: { mark: boolean, min: number, label: string }, gaps: Array<{ from: number, to: number, mark?: boolean }> | null | undefined, + * from: number, to: number }} o + * @returns {Array<{ at: number, until: number, seconds: number, count: number, text: string }>} + */ +export function clipGapMarks({ cue, gaps, from, to }) { + if (!fin(from) || !fin(to) || to <= from) return []; + const inside = gapsWithin(gaps ?? [], from, to).sort((a, b) => a.from - b.from); + const joins = inside.map((g) => { + const own = ownOf(gaps, g.from, g.to); + return { at: offsetIn(g.from, from, inside), seconds: g.to - g.from, mark: own.length ? own.some((c) => gapMarkOn(cue, c)) : cue.mark, ...gapOwnSays(own) }; + }); + return gapCues(joins, { min: cue.min, seconds: gappedLength(from, to, inside) }).map((c) => ({ ...c, text: gapCueText(c.seconds, cue.label, c.why) })); +} + +/** + * Source second `src` on clipGapMarks's clock (a page whose playhead is in + * source seconds: the bench), or null outside `from`–`to`. A second inside a + * gap is its join, where no mark is up yet. + * + * @param {{ gaps: Array<{ from: number, to: number }> | null | undefined, from: number, to: number }} o + * @param {number | null | undefined} src + */ +export function clipPlayClock({ gaps, from, to }, src) { + if (!fin(src) || !fin(from) || !fin(to) || /** @type {number} */ (src) < from - 1e-6 || /** @type {number} */ (src) > to + 1e-6) return null; + return offsetIn(/** @type {number} */ (src), from, gapsWithin(gaps ?? [], from, to).sort((a, b) => a.from - b.from)); +} + +/** + * The marks of one of Play's clip items, on the CUT's clock: its joins as + * Play lays them (playCut.mjs gapJoins: `{ at, from, to }`, the render's gaps + * when it said, so the join is where Play jumps), each marked as the clip's + * own gap there says (`entryGaps`), under the clip's settings (`cue`). A + * mark never outlives the clip's footage (`playEnd`). + * + * @param {Array<{ at: number, from: number, to: number }>} joins + * @param {{ cue: { mark: boolean, min: number, label: string }, entryGaps?: Array<{ from: number, to: number, mark?: boolean }> | null, + * playEnd: number }} o + */ +export function playGapMarks(joins, { cue, entryGaps = [], playEnd }) { + const marked = (joins ?? []).map((j) => { + const own = ownOf(entryGaps, j.from, j.to); + return { at: j.at, seconds: j.to - j.from, mark: own.length ? own.some((c) => gapMarkOn(cue, c)) : cue.mark, ...gapOwnSays(own) }; + }); + return gapCues(marked, { min: cue.min, seconds: fin(playEnd) ? playEnd : Infinity }).map((c) => ({ ...c, text: gapCueText(c.seconds, cue.label, c.why) })); +} + +/** + * The mark up at `t` (the marks' clock) and its opacity (gapCueAlpha), or + * null when none is. `peak` is its opacity at full, for a page that fades the + * text and its box together, as drawtext's alpha does. + * + * `corner` is the mark's own (its gap's), when it has one. + * + * @param {Array<{ at: number, until: number, text: string, corner?: string }>} marks + * @param {number | null | undefined} t + * @returns {{ text: string, alpha: number, at: number, until: number, corner?: string } | null} + */ +export function gapMarkAt(marks, t) { + if (!fin(t)) return null; + for (const m of marks ?? []) { + const alpha = gapCueAlpha(/** @type {number} */ (t), m); + if (alpha > 0) return { text: m.text, alpha, at: m.at, until: m.until, ...(m.corner ? { corner: m.corner } : {}) }; + } + return null; +} + +/** The mark's opacity at full (common gapCue.mjs GAP_CUE_MOTION.peak). */ +export const GAP_MARK_PEAK = GAP_CUE_MOTION.peak; diff --git a/umtool/lib/report/gapCueView.test.mjs b/umtool/lib/report/gapCueView.test.mjs @@ -0,0 +1,96 @@ +// gapCueView.mjs (lane gap-cue, slice 1b): the mark as umtool's pages draw it -- +// the bench on its source clock, Play on the cut's -- is the build's mark: the +// same joins, the same seconds up, the same text, the same fade. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { GAP_CUE_LIFE, GAP_CUE_MOTION, clipGapCueOf } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; +import { segmentGapJoins, segmentGapMarks } from "../../report-to-video/gap-mark.mjs"; +import { clipGapMarks, clipPlayClock, gapMarkAt, gapMarkCorner, playGapMarks } from "./gapCueView.mjs"; +import { gapJoins } from "./playCut.mjs"; + +const near = (a, b, what, tol = 1e-3) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +test("clipGapMarks: the build's marks for the same clip (segmentGapJoins + segmentGapMarks), at the same seconds with the same text", () => { + // A clip played 100–160 with gaps 110–137 (27 s, marked by the project), 150–151 (under min) and 154–157 (its own off). + const render = { gapCue: { mark: true, label: "{s} later" } }; + const entry = { type: "clip", gaps: [{ from: 110, to: 137 }, { from: 150, to: 151 }, { from: 154, to: 157, mark: false }] }; + const page = clipGapMarks({ cue: clipGapCueOf(render, entry), gaps: entry.gaps, from: 100, to: 160 }); + const segGaps = entry.gaps.map((g) => ({ from: g.from - 100, to: g.to - 100 })); + const seconds = 60 - 27 - 1 - 3; + const build = segmentGapMarks({ render, entry, seconds, joins: segmentGapJoins({ segGaps, clipGaps: entry.gaps, segStart: 100, cue: clipGapCueOf(render, entry) }) }); + assert.deepEqual(page, build); + assert.deepEqual(page.map((m) => [m.at, m.text]), [[10, "27 s later"]]); + near(page[0].until - page[0].at, GAP_CUE_LIFE, "a mark's life"); +}); + +test("clipGapMarks: nothing marked is no mark; a gap's own on over the clip's off; joins inside a life are one mark", () => { + const gaps = [{ from: 3.5, to: 5.5 }, { from: 6, to: 9, mark: true }]; + assert.deepEqual(clipGapMarks({ cue: clipGapCueOf({}, { gaps }), gaps: [{ from: 3.5, to: 5.5 }], from: 0.5, to: 12 }), [], "off by default"); + const own = clipGapMarks({ cue: clipGapCueOf({}, { gaps }), gaps, from: 0.5, to: 12 }); + assert.deepEqual(own.map((m) => [m.at, m.text]), [[3.5, "» 3 s"]], "only the gap that says so"); + // Both marked: 3.5–5.5 joins at 3, 6–9 at 3.5 (0.5 s later): one mark, both gaps' seconds. + const both = clipGapMarks({ cue: clipGapCueOf({ gapCue: { mark: true } }, { gaps }), gaps, from: 0.5, to: 12 }); + assert.equal(both.length, 1); + assert.deepEqual([both[0].at, both[0].count, both[0].text], [3, 2, "» 5 s"]); + near(both[0].until, 3.5 + GAP_CUE_LIFE, "a life after the last join"); + // A gap outside what plays draws nothing. + assert.deepEqual(clipGapMarks({ cue: clipGapCueOf({ gapCue: { mark: true } }, {}), gaps: [{ from: 20, to: 30 }], from: 0, to: 12 }), []); +}); + +test("clipPlayClock: a source second on the marks' clock; inside a gap its join; outside what plays null", () => { + const o = { gaps: [{ from: 3.5, to: 5.5 }], from: 0.5, to: 8.5 }; + assert.equal(clipPlayClock(o, 2), 1.5); + assert.equal(clipPlayClock(o, 4.2), 3, "inside the gap: its join"); + assert.equal(clipPlayClock(o, 6), 3.5); + assert.equal(clipPlayClock(o, 0.2), null); + assert.equal(clipPlayClock(o, null), null); +}); + +test("gapMarkAt: up over `in`, held at the peak, down over `out`; none before the join or after the life", () => { + const marks = [{ at: 3, until: 3 + GAP_CUE_LIFE, seconds: 2, count: 1, text: "» 2 s" }]; + assert.equal(gapMarkAt(marks, 2.9), null); + assert.equal(gapMarkAt(marks, 3), null, "at the join itself it is still 0"); + near(gapMarkAt(marks, 3 + GAP_CUE_MOTION.in / 2).alpha, GAP_CUE_MOTION.peak / 2, "half way up"); + near(gapMarkAt(marks, 3.5).alpha, GAP_CUE_MOTION.peak, "held"); + assert.equal(gapMarkAt(marks, 3.5).text, "» 2 s"); + assert.equal(gapMarkAt(marks, 3 + GAP_CUE_LIFE + 0.01), null); +}); + +test("playGapMarks: on the cut's clock at Play's joins, each marked as the clip's own gap says, never past the footage", () => { + // g01 0.5–8.5 with 3.5–5.5 out, starting at cut second 10: the join at 13, the footage to 16. + const item = { id: "g01", start: 10, clip: { sourceFrom: 0.5, sourceTo: 8.5, playEnd: 16, hold: 0, gaps: [{ from: 3.5, to: 5.5 }] } }; + const joins = gapJoins(item); + assert.deepEqual(joins, [{ at: 13, from: 3.5, to: 5.5 }]); + const on = playGapMarks(joins, { cue: clipGapCueOf({ gapCue: { mark: true } }, {}), entryGaps: [{ from: 3.5, to: 5.5 }], playEnd: 16 }); + assert.deepEqual(on.map((m) => [m.at, m.text]), [[13, "» 2 s"]]); + near(on[0].until, 13 + GAP_CUE_LIFE, "a mark's life"); + // The clip's own gap off (the render's gap a frame off the manifest's: still it). + assert.deepEqual(playGapMarks(joins, { cue: clipGapCueOf({ gapCue: { mark: true } }, {}), entryGaps: [{ from: 3.53, to: 5.47, mark: false }], playEnd: 16 }), []); + // A join near the footage's end: clamped to it. + const late = playGapMarks([{ at: 15.5, from: 3.5, to: 5.5 }], { cue: clipGapCueOf({ gapCue: { mark: true } }, {}), playEnd: 16 }); + assert.equal(late[0].until, 16); +}); + +test("gapMarkCorner: a clip's corner as it says; auto the layout's (the deck's footage bottom left, a plain cut's top left)", () => { + assert.equal(gapMarkCorner("br", { deck: true }), "br"); + assert.equal(gapMarkCorner("auto", { deck: true }), "bl"); + assert.equal(gapMarkCorner("auto", { deck: false }), "tl"); + assert.equal(gapMarkCorner(undefined, { deck: false }), "tl"); +}); + +test("the reason and the gap's own corner reach the page's mark as the build's (operator rulings, 20 Nov)", () => { + const gaps = [{ from: 3.5, to: 5.5, why: "dead-air", corner: "tr" }, { from: 7, to: 7.6 }]; + const cue = clipGapCueOf({ gapCue: { mark: true, min: 0.5 } }, { gaps }); + const page = clipGapMarks({ cue, gaps, from: 0.5, to: 12 }); + assert.deepEqual(page.map((m) => [m.text, m.corner ?? null]), [["» 2 s · dead air", "tr"], ["» 1 s", null]]); + const segGaps = gaps.map((g) => ({ from: g.from - 0.5, to: g.to - 0.5 })); + const build = segmentGapMarks({ render: { gapCue: { mark: true, min: 0.5 } }, entry: { type: "clip", gaps }, seconds: 11.5 - 2.6, joins: segmentGapJoins({ segGaps, clipGaps: gaps, segStart: 0.5, cue }) }); + assert.deepEqual(page, build); + assert.equal(gapMarkAt(page, 3.5).corner, "tr"); + // Play: the gap's own words over its why. + const play = playGapMarks([{ at: 13, from: 3.5, to: 5.5 }], { cue, entryGaps: [{ from: 3.5, to: 5.5, why: "other", reason: "ad break" }], playEnd: 20 }); + assert.equal(play[0].text, "» 2 s · ad break"); +}); diff --git a/umtool/lib/report/gaps-writer.test.mjs b/umtool/lib/report/gaps-writer.test.mjs @@ -99,6 +99,29 @@ test("updateClip: a gap edit leaves an undo point (auto-before-gaps); another ed assert.ok(r.snapshot, "the answer names it"); }); +test("the bench's mark settings leave an undo point, as a gap write does: a clip's gapCue (window route), the project's (look / Modules)", async () => { + const { updateRender } = await import("./manifest.mjs"); + const count = async (d) => (await readdir(path.join(d, "revisions")).catch(() => [])).filter((f) => f.includes("auto-before-gaps")).length; + const dir = await project(); + const r = await updateClip(dir, "c01", { gapCue: { mark: true } }); + assert.ok(r.snapshot, "the clip's: an undo point first"); + assert.equal(await count(dir), 1); + const dir2 = await project(); + const l = await updateRender(dir2, { gapCue: { mark: true, label: "{s} later" } }); + assert.ok(l.snapshot, "the project's: an undo point first"); + assert.equal(await count(dir2), 1); + // Another look key leaves none. + const dir3 = await project(); + const o = await updateRender(dir3, { headerHeight: 0 }); + assert.equal(o.snapshot, undefined); + assert.equal(await count(dir3), 0); + // A write that changes nothing is no edit and no undo point (review 1, 13): gapCue null where there is none. + const dir4 = await project(); + assert.equal((await updateClip(dir4, "c01", { gapCue: null })).snapshot, undefined); + assert.equal((await updateRender(dir4, { gapCue: null })).snapshot, undefined); + assert.equal(await count(dir4), 0); +}); + test("updateMarks: a mark's second inside a gap is refused", async () => { const dir = await project(); await updateClip(dir, "c01", { gapAdd: "15-17" }); @@ -127,6 +150,52 @@ test("splitClip: each half keeps the gaps on its side; a split inside a gap is r assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 14, to: 15 }, { from: 24, to: 25 }]); }); +test("the mark at the joins: a gap's own mark and why (gap.mark=, gap.why=, gapEdit), the clip's gapCue (gapCue.*), the project's (umtool look gapCue=)", async () => { + const dir = await project(); + const lines = []; + const io = { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }; + const run = (...args) => setCommand(args, io); + const name = path.basename(dir); + assert.equal(await run(name, "c01", "gap.add=15-17", "gap.add=20-21"), 0); + assert.equal(await run(name, "c01", "gap.mark=16:off", "gap.why=20.5:dead-air"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 15, to: 17, mark: false }, { from: 20, to: 21, why: "dead-air" }]); + assert.match(lines.at(-1), /c01: gaps 15–17 \(mark off\), 20–21 \(dead-air\)/); + // Another gap added keeps theirs; default drops one; its seconds never move. + assert.equal(await run(name, "c01", "gap.add=24-25", "gap.mark=16:default"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 15, to: 17 }, { from: 20, to: 21, why: "dead-air" }, { from: 24, to: 25 }]); + assert.equal(await run(name, "c01", "gap.mark=19:on"), 1, "no gap at 19"); + assert.equal(await run(name, "c01", "gap.why=20.5:boring"), 2); + // Its reason (the mark says it) and its own corner (lane gap-cue rulings, 20 Nov); `<sec>:` drops the words. + assert.equal(await run(name, "c01", "gap.why=16:idle", "gap.reason=16:walks off", "gap.corner=16:tr"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps[0], { from: 15, to: 17, why: "idle", reason: "walks off", corner: "tr" }); + assert.match(lines.at(-1), /15–17 \(idle, "walks off", at tr\)/); + assert.equal(await run(name, "c01", "gap.reason=16:", "gap.corner=16:default", "gap.why=16:dead-air"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps[0], { from: 15, to: 17, why: "dead-air" }); + assert.equal(await run(name, "c01", "gap.corner=16:middle"), 2); + assert.equal(await run(name, "c01", "gap.reason=16:a reason far too long for one small mark"), 1); + await assert.rejects(updateClip(dir, "c01", { gaps: [{ from: 15, to: 17, corner: "middle" }] }), /corner is one of tl, tr, bl, br/); + // The clip's own settings, merged; one cleared; all cleared. + assert.equal(await run(name, "c01", "gapCue.mark=true", "gapCue.corner=tr", "gapCue.label={s} later"), 0); + assert.deepEqual((await clip(dir, "c01")).gapCue, { mark: true, corner: "tr", label: "{s} later" }); + assert.equal(await run(name, "c01", "gapCue.corner="), 0); + assert.deepEqual((await clip(dir, "c01")).gapCue, { mark: true, label: "{s} later" }); + assert.equal(await run(name, "c01", "gapCue.min=99"), 1); + assert.match(lines.at(-1), /^ERR gapCue\.min is seconds from 0\.5 to 60/); + assert.equal(await run(name, "c01", "gapCue="), 0); + assert.equal("gapCue" in (await clip(dir, "c01")), false); + // The window route's gapEdit, through the one writer: an undo point, as every gap write. + const r = await updateClip(dir, "c01", { gapEdit: { at: 24.5, mark: true } }); + assert.deepEqual(r.entry.gaps[2], { from: 24, to: 25, mark: true }); + assert.ok(r.snapshot, "an undo point first"); + // The project's: a look key. + const { lookCommand } = await import("./knobsCli.mjs"); + assert.equal(await lookCommand([name, 'gapCue={"mark":true,"min":4}'], io), 0); + assert.deepEqual((await read(dir)).render.gapCue, { mark: true, min: 4 }); + assert.equal(await lookCommand([name, 'gapCue={"min":null}'], io), 0); + assert.deepEqual((await read(dir)).render.gapCue, { mark: true }); + assert.equal(await lookCommand([name, 'gapCue={"corner":"middle"}'], io), 1); +}); + test("umtool set: gap.add=, gap.remove=, gaps= (a list, JSON, or empty); timeline ls shows them", async () => { const dir = await project(); const lines = []; diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -54,14 +54,18 @@ const REVIEW_KEYS = ["verdict", "reason", "rejectNote", "correction"]; /** The clip's effects (report-to-video fx.mjs): `fx=<json>` whole (`fx=` clears it), `fx.<field>=<json>` one field. */ const FX_KEYS = ["fx", ...FX_ENTRY_FIELDS.map((k) => `fx.${k}`)]; /** Seconds taken out of the clip's middle (gaps.mjs): the whole list, one added, one removed. */ -const GAP_KEYS = ["gaps", "gap.add", "gap.remove"]; +const GAP_KEYS = ["gaps", "gap.add", "gap.remove", "gap.mark", "gap.why", "gap.reason", "gap.corner"]; +/** A gap's own settings (`gapEdit` on the window writer): its mark, why, reason and corner. */ +const GAP_OWN_SET_KEYS = ["gap.mark", "gap.why", "gap.reason", "gap.corner"]; +/** The mark at this clip's gaps' joins (common gapCue.mjs): its own settings over the project's render.gapCue. */ +export const GAP_CUE_SET_KEYS = Object.freeze(["gapCue", "gapCue.mark", "gapCue.min", "gapCue.corner", "gapCue.label"]); export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "vertical.layout", "vertical.aspect", "vertical.crops"]); export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]); /** The clip kit (lane clip-kit; report-to-video clip-kit.mjs): a clip's code in a per-clip build, its batch file name. */ export const KIT_SET_KEYS = Object.freeze(["qr", "qr.corner", "qr.links", "name", "promo", "promo.lead", "promo.fade", "promo.hold", "zooms", "coldOpen", "coldOpen.from", "coldOpen.to", "censor", "censor.boxes", "censor.style", "censor.strength", "censor.from", "censor.to"]); const SET_KEYS = [ "claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, - ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote", "chapter", + ...FX_KEYS, ...GAP_KEYS, ...GAP_CUE_SET_KEYS, "chat", "hideModules", "shelfNote", "chapter", // The vertical format (lane vertical): the clip's 9:16 crop and layout, and its side post. ...VERTICAL_SET_KEYS, ...SIDE_SET_KEYS, // The clip kit (lane clip-kit): its code and its name in a batch of shorts. @@ -134,6 +138,12 @@ export const SET_USAGE = [ " gap.add=12.3-15.1 cuts those source seconds out of the clip's middle (one segment of jump cuts; inside", " the cut, ≥ 0.2 s, 0.5 s kept between); gap.remove=<sec> the gap holding it; gaps=12.3-15.1,20-20.6 (or", " a JSON list of {from,to}) the whole list, `gaps=` none. The same as `umtool window --gap/--gap-remove/--gaps`.", + " gap.mark=<sec>:on|off|default marks (or not) the join of the gap holding <sec>, over the clip's and the", + " project's; gap.why=<sec>:dead-air|idle|other|default says what it was cut for (its mark says \"dead air\",", + " \"idle\"); gap.reason=<sec>:<a few words> says them instead (`<sec>:` drops them); gap.corner=<sec>:tl|tr|bl|br|default", + " stands its mark in that corner (its seconds never move).", + " gapCue.mark=true|false gapCue.min=<s> gapCue.corner=auto|tl|tr|bl|br gapCue.label='» {s}' the mark at this", + " clip's gaps' joins, over the project's (umtool look <p> gapCue='{\"mark\":true}'); `gapCue=` clears them.", ].join("\n"); export const LOOK_USAGE = [ @@ -296,6 +306,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso } if (GAP_KEYS.includes(key)) { if (key === "gap.add") (entryPatch.gapAdd ??= []).push(String(value ?? "")); + else if (GAP_OWN_SET_KEYS.includes(key)) (entryPatch.gapEdit ??= []).push(gapEditOf(key, value)); else if (key === "gap.remove") entryPatch.gapRemove = Number(value); else if (value === null || (Array.isArray(value) && !value.length)) entryPatch.gaps = []; else if (Array.isArray(value)) entryPatch.gaps = value; @@ -306,6 +317,16 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso } continue; } + if (GAP_CUE_SET_KEYS.includes(key)) { + if (key === "gapCue") { + if (value !== null && !(value && typeof value === "object")) throw new CliError("gapCue= clears the clip's own; gapCue='{\"mark\":true}' sets them"); + entryPatch.gapCue = value; + } else { + const k = key.slice("gapCue.".length); + entryPatch.gapCue = { ...(entryPatch.gapCue && typeof entryPatch.gapCue === "object" ? entryPatch.gapCue : {}), [k]: k === "label" && value !== null ? String(value) : value }; + } + continue; + } if (key === "claim") { // The clip's claim pin, off (owed 6 Nov: there was no way to take one off but a hand edit). Only clearing: // a claim is added as a mark (mark.add=<verdict>[@<s>]), its id and verdict edited in the On-screen table. @@ -378,7 +399,8 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if (Object.keys(entryPatch).some((k) => k === "censor" || k.startsWith("censor."))) results.censor = result.entry.censor ?? null; if (["coldOpen", "coldOpen.from", "coldOpen.to"].some((k) => k in entryPatch)) results.coldOpen = result.entry.coldOpen ?? null; if (FX_KEYS.some((k) => k in entryPatch)) results.fx = result.entry.fx ?? null; - if ("gaps" in entryPatch || "gapAdd" in entryPatch || "gapRemove" in entryPatch) { + if ("gapCue" in entryPatch) results.gapCue = result.entry.gapCue ?? null; + if ("gaps" in entryPatch || "gapAdd" in entryPatch || "gapRemove" in entryPatch || "gapEdit" in entryPatch) { results.gaps = result.entry.gaps ?? []; } if (REVIEW_KEYS.some((k) => k in entryPatch)) { @@ -420,7 +442,11 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("zooms" in results) out(`${clipId}: zooms ${results.zooms ? results.zooms.map((z) => `${z.at} s ×${z.scale ?? (z.box ? "box" : 1.3)}`).join(", ") : "none"}`); if ("promo" in results) out(`${clipId}: promo ${results.promo === false ? "none (it ends without the card)" : results.promo ? JSON.stringify(results.promo) : "the cut's"}`); if ("name" in results) out(`${clipId}: name ${results.name ? JSON.stringify(results.name) : "its title's slug"}`); - if ("gaps" in results) out(`${clipId}: ${results.gaps.length ? `gaps ${results.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps (the cut plays whole)"}`); + if ("gaps" in results) { + const own = (g) => [typeof g.mark === "boolean" ? `mark ${g.mark ? "on" : "off"}` : "", g.why ?? "", g.reason ? `"${g.reason}"` : "", g.corner ? `at ${g.corner}` : ""].filter(Boolean).join(", "); + out(`${clipId}: ${results.gaps.length ? `gaps ${results.gaps.map((g) => `${g.from}–${g.to}${own(g) ? ` (${own(g)})` : ""}`).join(", ")}` : "no gaps (the cut plays whole)"}`); + } + if ("gapCue" in results) out(`${clipId}: gapCue ${results.gapCue ? JSON.stringify(results.gapCue) : "the project's (render.gapCue)"}`); if (results.review) { const r = results.review; out(`${clipId}: ${r.verdict ?? "not reviewed"}${r.reason ? ` (${r.reason}${r.rejectNote ? `: ${r.rejectNote}` : ""})` : ""}${r.correction ? ` — ${r.correction}` : ""}`); @@ -440,6 +466,32 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** + * `gap.mark=<sec>:on|off|default`, `gap.why=<sec>:dead-air|idle|other|default`, + * `gap.reason=<sec>:<words>` (`<sec>:` drops it) and `gap.corner=<sec>:tl|tr|bl|br|default` + * as a window writer's `gapEdit`. + * + * @param {string} key + * @param {unknown} value + */ +export function gapEditOf(key, value) { + const field = key.slice("gap.".length); + const choices = { mark: "on|off|default", why: "dead-air|idle|other|default", reason: "<a few words>", corner: "tl|tr|bl|br|default" }[field] ?? ""; + const m = String(value ?? "").match(/^\s*(\d+(?:\.\d+)?)\s*:(.*)$/); + if (!m) throw new CliError(`${key}=${value ?? ""}: <a source second inside the gap>:${choices}`); + const at = Number(m[1]); + // The reason is words, whatever they are: the writer checks them (gaps.mjs). + if (field === "reason") return { at, reason: m[2].trim() ? m[2].trim() : null }; + const word = m[2].trim().toLowerCase(); + let v; + if (word === "default") v = null; + else if (field === "mark" && (word === "on" || word === "off")) v = word === "on"; + else if (field === "why" && ["dead-air", "idle", "other"].includes(word)) v = word; + else if (field === "corner" && ["tl", "tr", "bl", "br"].includes(word)) v = word; + else throw new CliError(`${key}=${value}: ${word || "nothing"} is not one of ${choices}`); + return { at, [field]: v }; +} + +/** * One `blur.*` assignment into the blur patch: a caption is text whatever it * parses as (`blur.caption=2025` is the words "2025"); `blur.on=true` turns it * on; the numbers as given (the writer refuses what the build would). diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs @@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => { const p = await project({ transition: 0.4, crf: 21 }); try { - assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo", "zooms", "censor"]); + assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro", "format", "vertical", "mode", "basic", "tallWindows", "desktop", "promo", "zooms", "censor", "gapCue"]); const token = await manifestToken(p.dir); const r = await updateRender(p.dir, { headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -60,7 +60,8 @@ import { counterOrder } from "umtool-report-to-video/counter"; import { validateFinaleEntries } from "umtool-report-to-video/finale"; import { validateFxEntries } from "umtool-report-to-video/fx"; import { validateClipAudio } from "umtool-report-to-video/clip-audio"; -import { editGaps, parseGapSpec, validateGaps } from "umtool-report-to-video/gaps"; +import { GAP_WHY_VALUES, editGaps, gapOwnKeys, parseGapSpec, validateGaps } from "umtool-report-to-video/gaps"; +import { gapCueErrors, patchGapCue } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, validateClipBlur, validateClipBlurEntries } from "umtool-report-to-video/clip-blur"; import { CLAIM_KNOBS, CLAIM_MARKS_MAX, claimKnobsOf, claimKnobValue, freshMarkId, marksCopyOf, normalizeClaimKnobPatch, rawMarksOf, setMarks, stampingEntryId, @@ -294,11 +295,15 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri // Re-read INSIDE the lock, every time. Nothing is held across requests. const raw = await readFile(manifestFile(dir), "utf8"); const manifest = JSON.parse(raw); + // The clip's gapCue as it was: a write that leaves it as it was is no edit (no undo point, below). + const cueBefore = patch.gapCue !== undefined ? JSON.stringify((manifest.timeline ?? []).find((e) => e?.id === clipId)?.gapCue ?? null) : null; const { entry, before, citeFollowed } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); // A gap cut or removed (gaps.mjs) changes what the clip IS in the cut, as a // split does, and so does a moved edge (one undo stack, L3 S5): an undo point // first (`umtool timeline <p> undo`, the Cut tab's Undo). - const gaps = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined); + // The mark at its gaps' joins (`gapCue`, lane gap-cue) is the gaps' too: the bench writes it as it writes a gap -- + // when it changes it (a `gapCue: null` on a clip with none is no edit, and no undo point). + const gaps = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) || (patch.gapCue !== undefined && JSON.stringify(entry.gapCue ?? null) !== cueBefore); const moved = !!before && (entry.start !== before.start || entry.end !== before.end); const snapshot = gaps ? await autoSnapshot(dir, "gaps") : moved ? await autoSnapshot(dir, "trim") : null; const nextToken = await writeManifestAtomic(dir, manifest); @@ -309,7 +314,7 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri } /** The patch keys that edit a clip's gaps (patchClipEntry, "gaps inside the clip"). */ -export const GAP_PATCH_KEYS = Object.freeze(["gaps", "gapAdd", "gapRemove"]); +export const GAP_PATCH_KEYS = Object.freeze(["gaps", "gapAdd", "gapRemove", "gapEdit"]); /** * Set an entry's `hideModules` (deck.mjs parseHideModules: a list, or "diet,streak"); null, "" or [] removes it. @@ -700,7 +705,7 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n // the gap holding a source second. Then the rule (validateGaps, the build's own check) on the // entry AFTER the patch, as for the mute mark: a window, cut or mark save // that leaves a gap outside the cut, or a mark inside a gap, is refused. - if (patch.gaps !== undefined || patch.gapAdd !== undefined || patch.gapRemove !== undefined) { + if (patch.gaps !== undefined || patch.gapAdd !== undefined || patch.gapRemove !== undefined || patch.gapEdit !== undefined) { let list = Array.isArray(entry.gaps) ? entry.gaps : []; if (patch.gaps !== undefined) { const v = patch.gaps; @@ -712,7 +717,16 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n const from = Number(g?.from); const to = Number(g?.to); if (!Number.isFinite(from) || !Number.isFinite(to)) throw new Error(`gaps[${k}] must be { from, to } in source seconds`); - return { from, to }; + // A gap's own mark, why, reason and corner (common gapCue.mjs) ride along, checked as they are. + if (g.mark !== undefined && g.mark !== null && typeof g.mark !== "boolean") throw new Error(`gaps[${k}].mark is true or false`); + if (g.why !== undefined && g.why !== null && !GAP_WHY_VALUES.includes(g.why)) throw new Error(`gaps[${k}].why is one of ${GAP_WHY_VALUES.join(", ")}`); + // Its reason and corner (lane gap-cue): kept only when well formed, so one that is not is refused here. + for (const key of ["reason", "corner"]) { + if (g[key] !== undefined && g[key] !== null && gapOwnKeys({ [key]: g[key] })[key] === undefined) { + throw new Error(validateGaps({ type: "clip", id: "gap", start: from, end: to, gaps: [{ from, to, [key]: g[key] }] }, `gaps[${k}]`).find((e) => e.includes(`.${key} `)) ?? `gaps[${k}].${key} is not one`); + } + } + return { from, to, ...gapOwnKeys(g) }; }), }); } @@ -725,12 +739,23 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n } } if (patch.gapRemove !== undefined) list = editGaps(list, { remove: Number(patch.gapRemove) }); + // `gapEdit: { at, mark?, why?, reason?, corner? }` (or a list): one gap's own settings, its seconds as they are. + if (patch.gapEdit !== undefined) { + for (const one of Array.isArray(patch.gapEdit) ? patch.gapEdit : [patch.gapEdit]) { + if (!isObj(one)) { + throw new Error( + `gapEdit is { at: <a source second inside the gap>, mark?: true|false|null, why?: ${GAP_WHY_VALUES.join("|")}|null, reason?: <a few words>|null, corner?: tl|tr|bl|br|null }`, + ); + } + list = editGaps(list, { edit: one }); + } + } if (list.length) entry.gaps = list; else delete entry.gaps; } if ( entry.gaps !== undefined && - ["start", "end", "cutStart", "cutEnd", "muteFrom", "gaps", "gapAdd", "gapRemove"].some((k) => patch[k] !== undefined) + ["start", "end", "cutStart", "cutEnd", "muteFrom", "gaps", "gapAdd", "gapRemove", "gapEdit"].some((k) => patch[k] !== undefined) ) { const errors = validateGaps(entry, clipId); if (errors.length) throw new Error(errors.join("; ")); @@ -803,6 +828,21 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n if (errors.length) throw new Error(errors.join("; ")); } + // ---- the mark at its gaps' joins (common gapCue.mjs) -------------------- + // + // `gapCue: { mark?, min?, corner?, label? }` -- this clip's, over the + // project's render.gapCue. Merged into what the clip has: a key null drops + // it, `gapCue: null` (or "") drops the block, nothing left is no block. + if (patch.gapCue !== undefined) { + const v = patch.gapCue === "" ? null : patch.gapCue; + if (v !== null && !isObj(v)) throw new Error("gapCue must be { mark?, min?, corner?, label? }, or null to clear it"); + const next = patchGapCue(entry.gapCue, v); + const errors = gapCueErrors(next, "gapCue"); + if (errors.length) throw new Error(errors.join("; ")); + if (next === null) delete entry.gapCue; + else entry.gapCue = next; + } + // ---- how the deck lays this entry out ----------------------------------- // // `layout: "finale"` (the deck's finale layout, render.chrome.deck.finale); @@ -1913,6 +1953,7 @@ export async function updateRender(dir, patch, { token = null } = {}) { const current = await manifestToken(dir); if (token !== null && current !== token) throw new StaleToken(token, current); const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const cueBefore = JSON.stringify(manifest.render?.gapCue ?? null); const { render, errors } = applyLookPatch(manifest, patch); // The channel promo (report-to-video promo-card.mjs) and the clip kit's QR: the build's own rules. if ("promo" in patch || "qr" in patch) errors.push(...validatePromo({ render }), ...validateClipKit({ render, timeline: manifest.timeline ?? [] })); @@ -1922,8 +1963,11 @@ export async function updateRender(dir, patch, { token = null } = {}) { if ("censor" in patch) errors.push(...renderCensorErrors(render.censor)); if (errors.length) throw new RenderRefused(errors); manifest.render = render; + // The mark at the gaps' joins (render.gapCue, lane gap-cue) leaves an undo point, as a gap's write does -- when + // it changes it (`gapCue: null` on a cut with none is no edit). + const snapshot = "gapCue" in patch && JSON.stringify(render.gapCue ?? null) !== cueBefore ? await autoSnapshot(dir, "gaps") : null; const nextToken = await writeManifestAtomic(dir, manifest); - return { look: lookOf(render), token: nextToken }; + return { look: lookOf(render), token: nextToken, ...(snapshot ? { snapshot } : {}) }; }); } diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -26,7 +26,8 @@ import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { draftLine, readWorkingCut } from "./workingCut.mjs"; import { listTakes, previewFile } from "./takes.mjs"; import { sectionModel } from "./sectionEdit.mjs"; -import { manifestToken } from "./manifest.mjs"; +import { effectiveManifest, manifestToken } from "./manifest.mjs"; +import { clipGapCueOf, gapCueWanted } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; import { videoAudio, videoEnter, videoFit, videoHidesChrome, videoLead, videoSeconds, videoSpan } from "umtool-report-to-video/video-entry"; @@ -186,6 +187,13 @@ export async function playViewWith(project, { take = null, bare = false, postFor (manifest.timeline ?? []).forEach((e, i) => e && typeof e === "object" && sourceAt.set(e, i)); const selected = selectVariant(manifest, DEFAULT_VARIANT); const render = selected.render ?? {}; + // The mark at the gaps' joins (lane gap-cue) as the build reads it: the look preset under the cut's own render. + let cueRender = render; + try { + cueRender = effectiveManifest(selected).render ?? render; + } catch { + // An unknown preset: the manifest's own word. + } // THE BASIC OUTPUT MODE (render.mode, report-to-video basic.mjs): Play plays what the basic render cuts -- // the clips alone, their spans exactly (no lead-in), hard cuts, nothing drawn over the footage. const basic = basicOn(render); @@ -233,6 +241,9 @@ export async function playViewWith(project, { take = null, bare = false, postFor cutEnd: fin(e.cutEnd) ? e.cutEnd : null, // Seconds taken out of its middle (gaps.mjs): the plan plays it as one item of jump cuts. ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), + // The mark at those gaps' joins (common gapCue.mjs): its settings, the clip's over the project's -- only when a + // gap of it is marked (lib/report/gapCueView.mjs draws it at Play's joins, on the render's timing). + ...(!basic && Array.isArray(e.gaps) && e.gaps.length && gapCueWanted(cueRender, e) ? { gapCue: clipGapCueOf(cueRender, e) } : {}), blur: e.blur && typeof e.blur === "object" ? e.blur : null, // Its hidden regions (report-to-video clip-censor.mjs): Play draws them over the picture as the cut hides them. censor: censorRegionsOf(e, render, selected.provenance ?? {}), diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -50,6 +50,7 @@ import { pathToFileURL } from "node:url"; import { mergePatch } from "umtool-report-to-video/montage-styles"; import { postItemSeconds } from "umtool-report-to-video/post-item"; import { videoSeconds } from "umtool-report-to-video/video-entry"; +import { gappedLength, renderGaps } from "umtool-report-to-video/gaps"; import { cutSlurState } from "umtool-report-to-video/post-slurs"; import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings"; import { markKeepFrames } from "umtool-report-to-video/prune-frames"; @@ -245,15 +246,23 @@ export async function loadMontageStyles({ file = montageStylesFile() } = {}) { // The window. // --------------------------------------------------------------------------- -/** An entry's length by the manifest's own numbers: a clip's cut, a post item's rule (post-item.mjs), else `seconds`, else 4 s. */ -export function estimatedSeconds(e) { +/** + * An entry's length by the manifest's own numbers: a clip's cut less its gaps (gaps.mjs: the seconds it plays, as + * the build and Play the cut count it -- not the cut's span, which put a window past a gapped clip that many seconds + * early), a post item's rule (post-item.mjs), else `seconds`, else 4 s. Under `render.montage` (the cut's `render`) + * a clip cuts to its phrase and applies no gaps (gaps.mjs renderGaps): its whole cut. + * + * @param {Record<string, any>} e + * @param {Record<string, any> | null} [render] + */ +export function estimatedSeconds(e, render = null) { if (e?.type === "post") return postItemSeconds(e); // A video entry (video-entry.mjs): its span and its hold (a take's hard cuts: no lead). if (e?.type === "video") return videoSeconds(e, 0); if (e?.type === "clip") { const a = Number(e.cutStart ?? e.start); const b = Number(e.cutEnd ?? e.end); - if (Number.isFinite(a) && Number.isFinite(b) && b > a) return b - a; + if (Number.isFinite(a) && Number.isFinite(b) && b > a) return gappedLength(a, b, renderGaps(e, render ?? {})); } const s = Number(e?.seconds); return Number.isFinite(s) && s > 0 ? s : 4; @@ -275,9 +284,10 @@ export const sourcedEntries = (timeline) => (Array.isArray(timeline) ? timeline * @param {Array<Record<string, any>>} timeline * @param {{ at: number, dur: number }} win * @param {{ segments?: Array<{ id: string, start: number, duration: number }> } | null} [schedule] + * @param {Record<string, any> | null} [render] the cut's render (estimatedSeconds: a montage applies no gaps) * @returns {{ ids: string[], basis: "schedule" | "estimate", total: number, missing: string[] }} */ -export function windowEntries(timeline, win, schedule = null) { +export function windowEntries(timeline, win, schedule = null, render = null) { const entries = sourcedEntries(timeline); if (!entries.length) throw new Error("the manifest's timeline is empty"); const segs = new Map((Array.isArray(schedule?.segments) ? schedule.segments : []).filter(isObj).map((s) => [s.id, s])); @@ -294,7 +304,7 @@ export function windowEntries(timeline, win, schedule = null) { const s = /** @type {any} */ (segs.get(e.id)); return { id: e.id, from: Number(s.start), to: Number(s.start) + Number(s.duration) }; } - const span = { id: e.id, from: t, to: t + estimatedSeconds(e) }; + const span = { id: e.id, from: t, to: t + estimatedSeconds(e, render) }; t = span.to; return span; }); @@ -682,7 +692,7 @@ export async function composeTake(projectDir, spec, opts = {}) { if (spec.window !== "full") { const scheduleFile = path.join(projectDir, "out", "sourced", "schedule.json"); const schedule = await readJson(scheduleFile); - covered = windowEntries(base.timeline, spec.window, schedule); + covered = windowEntries(base.timeline, spec.window, schedule, base.render ?? null); const [schedSt, manSt] = await Promise.all([stat(scheduleFile).catch(() => null), stat(path.join(projectDir, MANIFEST)).catch(() => null)]); log(`${spec.id}: ${windowBasisLine(covered, { schedule: !!schedule, scheduleOlder: !!(schedSt && manSt && schedSt.mtimeMs < manSt.mtimeMs) })}`); const present = new Set(sourcedEntries(ruled.manifest.timeline).map((e) => e.id)); @@ -692,7 +702,7 @@ export async function composeTake(projectDir, spec, opts = {}) { // its window is timed over its OWN timeline instead (by the estimates -- // the deck's schedule names the project's entries). if (!ids.length && isObj(spec.patch) && Array.isArray(spec.patch.timeline) && !covered.ids.some((id) => present.has(id))) { - covered = windowEntries(ruled.manifest.timeline, spec.window, null); + covered = windowEntries(ruled.manifest.timeline, spec.window, null, ruled.manifest.render ?? null); log( `${spec.id}: none of those is in the take's own timeline — the window covers ${covered.ids.length} of ITS entries ` + `(${covered.ids.join(", ")}), timed by their own lengths`, diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -124,6 +124,14 @@ test("windowEntries: by the manifest's own lengths, or by the deck's schedule wh assert.deepEqual(windowEntries(MANIFEST.timeline, { at: 500, dur: 10 }).ids, ["s04"]); // A clip's cut, not its extent, is what plays. assert.deepEqual(windowEntries([clip("a", 0, 100, { cutStart: 10, cutEnd: 12 }), clip("b", 0, 3)], { at: 2.5, dur: 1 }).ids, ["b"]); + // A clip's gaps never play: a window aimed at the clip after a gapped one gets that clip (lane gap-cue: it got the + // gapped one, the window that many seconds early). a is 40 s with 27 s of gaps: it plays 13 s; b 13–16. + const gapped = [clip("a", 0, 40, { gaps: [{ from: 5, to: 30 }, { from: 33, to: 35 }] }), clip("b", 0, 3)]; + assert.deepEqual(windowEntries(gapped, { at: 13.5, dur: 1 }).ids, ["b"]); + assert.equal(windowEntries(gapped, { at: 0, dur: 1 }).total, 16); + // Under render.montage a clip cuts to its phrase and applies no gaps (review 1, 10): its whole cut, 40 + 3. + assert.equal(windowEntries(gapped, { at: 0, dur: 1 }, null, { montage: { style: "wall" } }).total, 43); + assert.deepEqual(windowEntries(gapped, { at: 13.5, dur: 1 }, null, { montage: { style: "wall" } }).ids, ["a"]); const schedule = { segments: ["s01", "s02", "s03", "k1", "s04"].map((id, i) => ({ id, start: i * 2, duration: 2 })) }; assert.deepEqual(windowEntries(MANIFEST.timeline, { at: 3, dur: 2 }, schedule), { ids: ["s02", "s03"], basis: "schedule", total: 10, missing: [] }); // A schedule that misses an entry is not trusted -- one built before a clip diff --git a/umtool/lib/report/takePreview.mjs b/umtool/lib/report/takePreview.mjs @@ -151,11 +151,12 @@ export function windowPreviewMp4(takeDir, slug, win) { * @param {Array<Record<string, any>>} timeline the take's render timeline (its rulings applied) * @param {{ at: number, dur: number }} win * @param {{ segments?: Array<{ id: string, start: number, duration: number }>, estimated?: boolean } | null} schedule + * @param {Record<string, any> | null} [render] the take's render (an estimate under render.montage applies no gaps) * @returns {{ ids: string[], basis: "schedule" | "estimate", total: number }} */ -export function previewWindowPlan(timeline, win, schedule) { +export function previewWindowPlan(timeline, win, schedule, render = null) { const measured = schedule && schedule.estimated !== true ? schedule : null; - const w = windowEntries(timeline, win, measured); + const w = windowEntries(timeline, win, measured, render); if (!(win.at < w.total)) { const len = Math.round(w.total * 10) / 10; throw new Error( @@ -357,10 +358,10 @@ export function planRuns(ids, diff, { neighbours = 1 } = {}) { * "estimate"). * * @param {{ timeline: Array<Record<string, any>>, changedIds: Set<string>, base: { segments: Array<{ id: string, start: number, duration: number }>, transition?: number, estimated?: boolean } | null, - * measured: Map<string, number>, estimate?: (e: Record<string, any>) => number }} o + * measured: Map<string, number>, estimate?: (e: Record<string, any>, render?: Record<string, any> | null) => number, render?: Record<string, any> | null }} o * @returns {{ basis: "measured" | "estimate", times: Map<string, { start: number, end: number, exact: boolean }> }} */ -export function fullCutTimes({ timeline, changedIds, base, measured, estimate = estimatedSeconds }) { +export function fullCutTimes({ timeline, changedIds, base, measured, estimate = estimatedSeconds, render = null }) { const entries = sourcedEntries(timeline); const times = new Map(); const exactBase = !!base && base.estimated !== true && Array.isArray(base.segments) && base.segments.length > 0; @@ -369,7 +370,7 @@ export function fullCutTimes({ timeline, changedIds, base, measured, estimate = let exact = true; for (const e of entries) { const m = measured.get(e.id); - const d = m ?? estimate(e); + const d = m ?? estimate(e, render); if (m === undefined) exact = false; times.set(e.id, { start: t, end: t + d, exact }); t += d; @@ -394,7 +395,7 @@ export function fullCutTimes({ timeline, changedIds, base, measured, estimate = continue; } const m = measured.get(e.id); - const d = m ?? estimate(e); + const d = m ?? estimate(e, render); if (m === undefined) exactSoFar = false; const start = Math.max(0, prevEnd - (times.size ? D : 0)); times.set(e.id, { start, end: start + d, exact: exactSoFar }); @@ -672,7 +673,7 @@ async function windowPreview(projectDir, id, win, opts = {}) { const takeDir = path.join(takesDirOf(projectDir), id); const slug = String(c.manifest.slug ?? ""); const sched = await takeScheduleOf(takeDir); - const plan = previewWindowPlan(renderDoc.timeline, win, sched?.doc ?? null); + const plan = previewWindowPlan(renderDoc.timeline, win, sched?.doc ?? null, renderDoc.render ?? null); const outDir = path.join(takeDir, "out", WINDOW_DIR); // One window at a time (review 1, S3): its build dir, record and work files are shared. { @@ -846,7 +847,7 @@ export async function changesTake(projectDir, id, opts = {}) { try { const built = await buildPlaces(path.join(p.changesOut, "sourced"), [...want].sort((x, y) => ids.indexOf(x) - ids.indexOf(y)), since); const measured = new Map([...changedIds].filter((x) => built.places.has(x)).map((x) => [x, built.places.get(x).duration])); - const full = fullCutTimes({ timeline: ruled.timeline, changedIds, base: baseSchedule, measured }); + const full = fullCutTimes({ timeline: ruled.timeline, changedIds, base: baseSchedule, measured, render: ruled.render ?? null }); const pieces = reelPieces(runs, built.places, full.times, pad); // Cut, labelled, joined. const work = path.join(p.changesOut, "reel-work"); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -183,6 +183,11 @@ import { validateFinaleEntries } from "./finale.mjs"; import { fetchPieces, gapFilterParts, gapSeconds, gapsOnSegment, inGap, keptSpans, offsetIn, recordGaps, renderGaps, validateGapEntries, } from "./gaps.mjs"; +// The mark at a gap's join (gap-mark.mjs; the settings and timing: common gapCue.mjs). +import { + centredIn, censorAvoidRects, gapMarkAsked, gapMarkDrift, gapMarkFilters, gapMarkPlaces, gapMarkSize, segmentGapJoins, segmentGapMarks, twoCropMarkBox, verticalMarkBox, +} from "./gap-mark.mjs"; +import { clipGapCueOf, gapCueWanted } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -1682,6 +1687,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, }); } } + // Cut from its pieces: every source second the segment leaves out, in the recording's seconds -- its own gaps + // and the seconds between two pieces (a gap that shrank to nothing on the joined file's clock, with no pad, is + // still the recording's seconds between them). + const piecedGaps = pieced + ? pieced.clock.realGaps(fetchStart + segA, fetchStart + segB, segGaps.map((g) => ({ from: fetchStart + segA + g.from, to: fetchStart + segA + g.to }))) + : null; // Where in the SOURCE this segment really starts and ends, snapped: what a // `muteFrom` (source seconds) is measured from at the join, long after this // function is gone (`--chrome-only` rebuilds no segment). With room, the @@ -1694,11 +1705,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // Only with gaps, so a clip without them records what it always did. // Cut from its pieces: every source second left out, the seconds between pieces too. ...(pieced - ? { - gaps: pieced.clock - .realGaps(fetchStart + segA, fetchStart + segB, segGaps.map((g) => ({ from: fetchStart + segA + g.from, to: fetchStart + segA + g.to }))) - .map((g) => ({ from: Number(g.from.toFixed(3)), to: Number(g.to.toFixed(3)) })), - } + ? { gaps: piecedGaps.map((g) => ({ from: Number(g.from.toFixed(3)), to: Number(g.to.toFixed(3)) })) } : segGaps.length ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) } : {}), @@ -1828,6 +1835,60 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, return { parts, v: "[vcen]" }; }; + // THE GAP MARK (gap-mark.mjs): "» 27 s" at each marked join, drawn over the + // finished picture -- after its hidden regions and its blur: it is chrome, + // not footage. Only when a gap is marked (render.gapCue, the clip's gapCue, + // a gap's own mark: common gapCue.mjs): otherwise none, and every graph and + // record below is the one it always was. + // A clip cut from its pieces takes its joins from the recording's seconds (piecedGaps): with no pad, the join + // between two pieces is no gap on the joined file's clock, but it is one the viewer jumps -- and Play and the + // bench, which read the recording's seconds, mark it. + const realStart = toReal(fetchStart + segA); + const gapMarks = (pieced ? piecedGaps.length : segGaps.length) && gapCueWanted(render, clipE) + ? segmentGapMarks({ + render, entry: clipE, seconds: segSeconds, + joins: pieced + ? segmentGapJoins({ + segGaps: piecedGaps.map((g) => ({ from: g.from - realStart, to: g.to - realStart })), clipGaps: renderGaps(entry, render), segStart: realStart, + cue: clipGapCueOf(render, entry), + }) + : segmentGapJoins({ segGaps, clipGaps, segStart: fetchStart + segA, cue: clipGapCueOf(render, clipE), toReal }), + }) + : []; + /** + * The marks' filters for a layout: drawn in `box` (frame px) at its `prefer` + * corner unless the clip's `corner` says, kept off `avoid` (rects over their + * seconds) and the `busy` corners; "" with no marks. Records them. + */ + const markChain = async ({ box, prefer, avoid = [], busy = [] }) => { + if (!gapMarks.length) return ""; + const size = gapMarkSize(width, height); + const want = clipGapCueOf(render, clipE).corner; + // Each mark fitted to its box (gapMarkPlaces): its text as drawn, the file drawtext reads. + const places = gapMarkPlaces({ marks: gapMarks, box, want, prefer, size, avoid, busy }); + const files = []; + for (const k of gapMarks.keys()) { + const file = path.join(outDir, "segments", `${entry.id}.gapmark-${k}.txt`); + await replaceFile(file, places[k].text); + files.push(file); + } + // `asked`: the corner the mark asked for (its gap's, the clip's; none for auto), so `--chrome-only` sees a change. + cutRecord.gapMarks = gapMarks.map((m, k) => { + const asked = gapMarkAsked(m, want); + return { + at: m.at, until: m.until, seconds: m.seconds, ...(m.count > 1 ? { count: m.count } : {}), text: places[k].text, corner: places[k].corner, ...(asked ? { asked } : {}), + rect: places[k].rect, + }; + }); + return gapMarkFilters({ marks: gapMarks, places, files, size }); + }; + /** The picture's hidden regions as rects to keep the mark off: the source `sw` × `sh` (its `region`) shown in `dest`. */ + const censorAvoid = (sw, sh, dest, region = null) => + gapMarks.length && censorRegions.length + ? censorAvoidRects(censorRegions, { sw, sh, region, dest, from: cutRecord.start, gaps: cutRecord.gaps ?? [], seconds: segSeconds }) + : []; + const rectOf = (b) => ({ x: b.x, y: b.y, w: b.w ?? b.width, h: b.h ?? b.height }); + // THE SIDE POST (side-card.mjs): the post a clip carries beside it, up over its `from`-`to`, never read. const sidePost = dirs.sides ? sidePostOf(entry, dirs.sides.timeline) : null; const sideUp = sidePost ? sideSpan(entry.side, segSeconds) : null; @@ -1911,6 +1972,19 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const qrParts = qrBox ? [`[${qrIdx}:v]scale=${qrBox.size}:${qrBox.size}:flags=neighbor,setsar=1[vqr]`, `[vp0][vqr]overlay=x=${qrBox.x}:y=${qrBox.y}:format=auto[vp]`] : []; + // The gap mark, always inside the safe area (the platform's own buttons and bands are outside it): a framed or + // quote layout's on its picture's top left (the hook stands above a framed picture; a quote has no tag); a + // split's at its picture's top right (its tag is top left, its captions at the picture's foot); a full-bleed or + // desktop clip's at the safe area's top right (the tag and the hook are at its left); off the code and the + // hidden regions. + const vbox = rectOf(geo.video); + const vpic = geo.video.fill === "fit" + ? { dest: centredIn(vbox, fittedSize(sw, sh, vbox.w, vbox.h)), region: null } + : { dest: vbox, region: pictureRegion(geo, sw, sh, entry.vertical?.crop ?? null).region }; + const mark = await markChain({ + ...verticalMarkBox(geo, geo.safe ?? safeArea(render, width, height)), + avoid: [...censorAvoid(sw, sh, vpic.dest, vpic.region), ...(qrBox ? [{ x: qrBox.x, y: qrBox.y, w: qrBox.size, h: qrBox.size }] : [])], + }); // THE CHANNEL PROMO (promo-card.mjs): the last clip of a per-clip build ends on the card -- faded in over the // clip's last seconds, its sound on under it, then held in silence; the captions go on over it, in its band. const promo = promoSpec; @@ -1937,7 +2011,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, `${censored(g.v).v}${graph}${qrBox ? "[vp0]" : "[vp]"}`, ...qrParts, ...(promoPart ? promoPart.parts : []), - cap ? `${promoPart ? promoPart.v : "[vp]"}${cap.filter}[v]` : `${promoPart ? promoPart.v : "[vp]"}null[v]`, + `${promoPart ? promoPart.v : "[vp]"}${[cap?.filter, mark].filter(Boolean).join(",") || "null"}[v]`, ].join(";"), "-map", "[v]", "-map", promoPart ? promoPart.a : audioMap, ...encodeArgs(render), @@ -1973,6 +2047,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, }) : null; cutRecord.vertical = { layout: "twocrop", crops: twoCrop, width, height, enlarged: grow, ...(cap ? { captions: cap.lines } : {}) }; + // The gap mark at crop one's top right, inside the safe area (two crops: their hidden regions are under the + // crops, not mapped here; the source line and the rail stand above crop one, the strip under it). + const tmark = await markChain(twoCropMarkBox(stackedGeometry(render))); await encodeClipSegment({ seg, outDir, render, opts, id: entry.id, record: { ...cutRecord, framing: fr }, argv: [ @@ -1983,7 +2060,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...levelParts(null, g.a), ...censored(g.v).parts, `${censored(g.v).v}${graph}[vp]`, - cap ? `[vp]${cap.filter}[v]` : "[vp]null[v]", + `[vp]${[cap?.filter, tmark].filter(Boolean).join(",") || "null"}[v]`, ].join(";"), "-map", "[v]", "-map", audioMap, ...encodeArgs(render), @@ -2003,7 +2080,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const sideInput = sideGeo ? await sideCard(sideGeo.w, sideGeo.h) : []; const sideIdx = 1 + (pst ? 1 : 0) + (soundInput ? 1 : 0); const cen = pst ? { parts: [], v: "[pic]" } : censored(g.v); - const framed = `${cen.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}`; + // The gap mark at the footage's bottom left as it plays in the box (the stamp stands top left, the posts top + // right, the subtitle and the code in the band below), off its hidden regions. + const fbox = rectOf(fr.box); + const fdims = media.hasVideo && gapMarks.length ? await probeDims(raw) : null; + const fpic = fdims ? centredIn(fbox, fittedSize(fdims[0], fdims[1], fbox.w, fbox.h)) : fbox; + const dmark = await markChain({ box: fpic, prefer: "bl", avoid: fdims ? censorAvoid(fdims[0], fdims[1], fpic) : [] }); + const framed = `${cen.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}${dmark ? `,${dmark}` : ""}`; // The stacked vertical deck's captions (vertical-deck.mjs): under the picture, each word lit, over the frame. const vcap = dirs.vertical?.stacked && dirs.look ? await segmentCaptions({ @@ -2086,9 +2169,19 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ? verticalFilters(entry.vertical?.crop ?? null, ...(await probeDims(raw)), { width, height, fps: render.fps }) : null; // The blur on the picture alone (a short's is the whole frame: no header). - const base = shortPicture + const base0 = shortPicture ? [...shortPicture, ...(await blurPicture(width, height))].join(",") : clipBaseFilters({ render, VW, VH, HH, hasHeader, attribPath, channelPath, picture: await blurPicture(VW, VH) }).join(","); + // The gap mark at the picture's top left (the header stands above it, the captions at its foot, the code at a + // bottom corner -- never on the code's corner), off its hidden regions; a short's at its frame's. + const pbox = shortPicture ? { x: 0, y: 0, w: width, h: height } : { x: 0, y: HH, w: VW, h: VH }; + const pdims = media.hasVideo && gapMarks.length && !shortPicture ? await probeDims(raw) : null; + const ppic = pdims ? centredIn(pbox, fittedSize(pdims[0], pdims[1], pbox.w, pbox.h)) : pbox; + const pmark = await markChain({ + box: ppic, prefer: "tl", avoid: pdims ? censorAvoid(pdims[0], pdims[1], ppic) : [], + busy: !render.rail && cornerQrOf(entry, render) ? [cornerQrOf(entry, render).corner] : [], + }); + const base = pmark ? `${base0},${pmark}` : base0; // A manifest with a RAIL draws the code in the rail's foot instead, as one // more strip: bottom-right of the frame, bordered, one per clip. It used to @@ -7669,6 +7762,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...censorProblems({ entries: present.map((i) => entries[i]), records, render, provenance }), ]; if (problems.length) throw new Error(`${what}: ${problems.join("; ")}`); + // The gap mark is in a clip's segment (gap-mark.mjs), which this pass does not rebuild: a mark changed since + // (turned on or off, its label, a gap's reason or corner) is laid as it was built -- said, never silently. + present.forEach((i, k) => { + const e = entries[i]; + if (e?.type !== "clip" || !records[k]) return; + const drift = gapMarkDrift({ render, entry: e, record: records[k] }); + if (drift) { + EMIT("note", { message: `${e.id}: its gap mark changed since its segment was built (${drift}) — ${what} rebuilds no clip segment: build without it (or --only ${e.id}) to draw it` }); + } + }); } for (const i of missing) { const e = entries[i]; diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -38,7 +38,7 @@ import { fileURLToPath } from "node:url"; import { - claimsLayout, cueTime, cueTimeAfter, PIP_PITCH_DEFAULT, stampsOnFrames, deckChoreography, deckLayout, deckMarkers, MARKER_DEFAULT_COLOR, MARKER_LABEL_SIZE, MARKER_ROW, MARKER_SUB_LABEL_SIZE, pageDuration, pipSegments, pipXs, railSections, resolveDeck, + claimsLayout, cueTime, cueTimeAfter, PIP_PITCH_DEFAULT, stampsOnFrames, deckChoreography, deckLayout, deckMarkers, MARKER_DEFAULT_COLOR, MARKER_LABEL_SIZE, MARKER_ROW, MARKER_SUB_LABEL_SIZE, pageDuration, pipSegments, pipXs, railOffStyle, railSections, resolveDeck, resolveSectionTitle, } from "./deck.mjs"; import { contrast } from "./chrome-intro.mjs"; @@ -1143,7 +1143,7 @@ export function deckHtml(schedule, render, opts = {}) { <div class="ground"></div> ${panel && qr ? `<div class="plate"></div>` : ""} ${panel ? `<div class="edge"></div><div class="sheen"></div>` : ""} - <div class="track"> + <div class="track"${railOffStyle(pips.length)}> <div class="rail"></div> ${secColors && sections.fuses.length ? sections.fuses.map((f) => `<div class="fuse fz" data-k="${f.k}" style="left:${f.x0}px; width:${r4(f.x1 - f.x0)}px; background:${secColors[f.section]}"></div>`).join("") diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs @@ -22,7 +22,7 @@ // in place. Either way the page fades out through the dissolve after the run. // // The timeline is cues, each stating its from (chrome-deck.mjs says why). -import { cueTime, cueTimeAfter, finaleRail, pageDuration, resolveDeck } from "./deck.mjs"; +import { cueTime, cueTimeAfter, finaleRail, pageDuration, railDrawn, railOffStyle, resolveDeck } from "./deck.mjs"; import { finaleClaimsMarkup } from "./chrome-claims.mjs"; import { mix, rgba, scheduleHasStatus, shapeCss, statusFitScript, statusPartCss, subtitleMarkup, subtitlePartsCss, subtitleTokens } from "./chrome-deck.mjs"; import { resolveFactcheck, tallyCells, tallyFinals, tallyOf } from "./factcheck.mjs"; @@ -361,6 +361,9 @@ export function finaleHtml(schedule, render, window, opts = {}) { `<div class="vframe" data-k="frame" style="left:${L.box.x}px; top:${L.box.y}px; width:${L.box.width}px; height:${L.box.height}px"></div>` : `<div class="ground" data-k="ground"></div>`; + // Under RAIL_MIN_PIPS (deck.mjs): the large rail -- its track, fuse, spans, marks, pips, leaders and labels -- is + // there but not drawn; at or over it, the markup it always was. + const railOnly = (html) => (railDrawn(L.pips.length) || !html ? html : `<div style="display:none">${html}</div>`); const pipHtml = L.pips .map((p, k) => { const half = p.size / 2; @@ -606,10 +609,10 @@ export function finaleHtml(schedule, render, window, opts = {}) { ${hole} ${deckCopy} <div class="panel" data-k="panel"></div> - <div class="track" data-k="track"></div> - ${L.pips.length > 1 ? `<div class="fuse" data-k="fuse"></div>` : ""} - ${spans}${markHtml}${pipHtml}${fq ? fq.html : ""} - ${leaderHtml}${labelHtml} + <div class="track" data-k="track"${railOffStyle(L.pips.length)}></div> + ${L.pips.length > 1 ? `<div class="fuse" data-k="fuse"${railOffStyle(L.pips.length)}></div>` : ""} + ${railOnly(`${spans}${markHtml}${pipHtml}`)}${fq ? fq.html : ""} + ${railOnly(`${leaderHtml}${labelHtml}`)} ${totalsHtml} ${statsHtml} ${captionHtml} diff --git a/umtool/report-to-video/chrome-vdeck.mjs b/umtool/report-to-video/chrome-vdeck.mjs @@ -18,7 +18,7 @@ // shown over exactly its span, so a frame whose words did not move keys as the // frame before it). -import { deckChoreography, pipSegments, resolveDeck, resolveSectionTitle, stackedCounterOn } from "./deck.mjs"; +import { deckChoreography, pipSegments, railOffStyle, resolveDeck, resolveSectionTitle, stackedCounterOn } from "./deck.mjs"; import { mix, rgba } from "./chrome-deck.mjs"; import { resolveCounter } from "./counter.mjs"; import { tallyLabelOf, tallyOf, tallySteps } from "./factcheck.mjs"; @@ -341,8 +341,8 @@ export function stackedDeckHtml(schedule, render, opts = {}) { .mark { position: absolute; left: ${g.wordmark.x}px; top: ${g.wordmark.y}px; font-family: ${display}; font-size: ${g.wordmark.size}px; letter-spacing: 0.12em; color: ${mix(pal.bg, pal.fg, 0.24)}; white-space: nowrap; }`; const body = `<div id="rt" data-k="rt"> - <div class="rail" data-k="rail">${railLabels("r", "rlab")}${counts}<div class="bars">${railBars("r")}</div></div> - <div class="top2" data-k="top2">${tops.join("")}<div class="bars">${railBars("t")}</div>${railLabels("t", "tlab2")}</div> + <div class="rail" data-k="rail"${railOffStyle(pipped.length)}>${railLabels("r", "rlab")}${counts}<div class="bars">${railBars("r")}</div></div> + <div class="top2" data-k="top2">${tops.join("")}<div class="bars"${railOffStyle(pipped.length)}>${railBars("t")}</div>${railLabels("t", "tlab2")}</div> ${blocks.join("")} ${strips.join("")} ${smallQrs.join("")} diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -2351,6 +2351,19 @@ export function pipSegments(schedule) { return schedule.segments.filter((s) => !s.hideDeck && !s.noPip); } +/** + * The fewest pips a rail is drawn with (operator, 20 Nov: "the fact there's a one item timeline looks bad. Don't do + * that." -- his standing rule: never a rail of one or two items). Under it -- a cut of one or two clips, or a window + * take over one or two -- the deck's pip track (its line, fuse, pips, marker and markers' flags), the stacked deck's + * rail and the finale's large rail are not drawn; everything else stands where it did (nothing reflows into the + * room). No setting draws a rail under it. + */ +export const RAIL_MIN_PIPS = 3; +/** Is a rail of `n` pips drawn (RAIL_MIN_PIPS)? */ +export const railDrawn = (n) => n >= RAIL_MIN_PIPS; +/** The style a rail's element takes when it is not drawn: hidden, its place kept; nothing at all when it is. */ +export const railOffStyle = (n) => (railDrawn(n) ? "" : ' style="display:none"'); + // --------------------------------------------------------------------------- // Posts: written statements (a Bluesky or X post) drawn as cards over the // footage. A post is not a segment -- it has no footage of its own -- so it diff --git a/umtool/report-to-video/gap-mark.mjs b/umtool/report-to-video/gap-mark.mjs @@ -0,0 +1,341 @@ +// THE GAP MARK, drawn (lane gap-cue, slice 1): "» 27 s" at the join a clip's +// gap leaves, in the clip's own segment -- after its hidden regions and its +// blur, so the mark is chrome over the footage and never blurred -- by one +// drawtext per mark over its seconds, as a blurred clip's caption is drawn +// (clip-blur.mjs). The settings, the label and the timing are common +// lib/report/gapCue.mjs's, which umtool's pages read too; this file is where +// the mark stands in a frame and the ffmpeg that draws it. +// +// WHERE. In a box the layout names -- the footage as it plays (the deck's +// footage box, the plain cut's picture, a vertical cut's picture or crop one +// inside its safe area) -- at a corner `inset` in from its edges: the +// layout's own free corner (`auto`: the deck's stamp stands top-left and its +// posts top-right, so bottom-left; the plain cut's captions sit at its foot +// and its code at the bottom right, so top-left; a vertical split's captions +// at its picture's foot, so top-right), or the one `corner` says. A hidden +// region up while the mark is, or a code, under that corner moves it to the +// next free one (tl, tr, bl, br); none free, it stays where it was asked. A +// mark too wide for its box is drawn smaller, then cut ("…"): never off it. +// +// THE LOOK is common gapCue.mjs's GAP_CUE_LOOK (umtool's pages draw it from the +// same numbers): IBM Plex Mono Bold (the vendored face: the same mark whatever +// the brand), 3 % of the frame's short side (32 px at 1080), light text on a +// near-opaque dark box inside a light 2 px border (operator, 20 Nov: "more +// visible and readable with a border"), faded in and out by `alpha` +// (GAP_CUE_MOTION), which fades the box and its border with the text. The +// border is a second drawtext under the first: the same text, unseen, its box +// the border's colour and wider by the stroke. No sound. +// +// PURE: no fs, no ffmpeg run. The build writes each mark's text file. +import { GAP_CUE_LOOK, GAP_CUE_MOTION, clipGapCueOf, gapCueText, gapCueWanted, gapCues, gapMarkOn, gapOwnSays } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; +import { MONO_BOLD_FONT_FILE } from "./brand.mjs"; +import { offsetIn, renderGaps } from "./gaps.mjs"; + +/** Plex Mono's advance, in ems: every glyph the same width. */ +const ADVANCE = 0.6; + +const EPS = 1e-6; +const f3 = (n) => Number(n.toFixed(3)).toString(); + +/** + * The mark's sizes for a `W` × `H` frame (GAP_CUE_LOOK): its font size, the + * box round the text (`border`, drawtext's boxborderw), the border's stroke, + * and the inset from the box it stands in. `look` overrides GAP_CUE_LOOK's + * numbers (the operator's stills of the variants). + */ +export function gapMarkSize(W, H, look = GAP_CUE_LOOK) { + const L = { ...GAP_CUE_LOOK, ...look }; + const s = Math.min(W, H); + const fontSize = Math.max(12, Math.round(s * L.font)); + return { + fontSize, + border: Math.round(fontSize * L.pad), + stroke: L.stroke > 0 ? Math.max(L.strokeMin, Math.round(s * L.stroke)) : 0, + inset: Math.max(8, Math.round(s * L.inset)), + }; +} + +/** The rect a text of `chars` characters takes with its box and border, at `size` (gapMarkSize). */ +export function gapMarkRect(chars, size) { + const edge = size.border + (size.stroke ?? 0); + return { w: Math.ceil(chars * ADVANCE * size.fontSize) + 2 * edge, h: Math.ceil(size.fontSize * 1.2) + 2 * edge }; +} + +/** + * A segment's JOINS on its own clock, from the gaps it really left out: + * `segGaps` (gaps.mjs gapsOnSegment, seconds from its first frame, before + * the gaps are taken out) and the clip's gaps as the render applies them + * (`clipGaps`, source seconds -- with their own `mark` -- on the clock + * `segStart` is on). `toReal` maps that clock to the recording's (a clip cut + * from its pieces), so the seconds a join says are the recording's. + * + * @param {{ segGaps: Array<{ from: number, to: number }>, clipGaps: Array<{ from: number, to: number, mark?: boolean }>, + * segStart: number, cue: { mark: boolean }, toReal?: (t: number) => number }} o + * Each join says its reason (gapWhyWord: the clip's gaps it is agreeing, else + * none) and its own corner (the first of them that names one), only when it + * has them. + * + * @returns {Array<{ at: number, seconds: number, mark: boolean, why?: string, corner?: string }>} + */ +export function segmentGapJoins({ segGaps, clipGaps, segStart, cue, toReal = (t) => t }) { + let removed = 0; + return (segGaps ?? []).map((g) => { + const a = segStart + g.from; + const b = segStart + g.to; + // The clip's gaps this one is (gapsOnSegment may have joined two that touch on the frame grid). + const own = (clipGaps ?? []).filter((c) => c.to > a - 0.05 && c.from < b + 0.05); + const join = { at: g.from - removed, seconds: toReal(b) - toReal(a), mark: own.length ? own.some((c) => gapMarkOn(cue, c)) : cue.mark, ...gapOwnSays(own) }; + removed += g.to - g.from; + return join; + }); +} + +/** + * The marks one segment draws: its joins (segmentGapJoins) under the clip's + * settings (clipGapCueOf: `min`, and `label` for the text). [] when nothing + * is marked -- the segment's graph is then the one it always was. + * + * @param {{ render: any, entry: any, joins: Array<{ at: number, seconds: number, mark: boolean }>, seconds: number }} o + * @returns {Array<{ at: number, until: number, seconds: number, count: number, text: string }>} + */ +export function segmentGapMarks({ render, entry, joins, seconds }) { + const cue = clipGapCueOf(render, entry); + return gapCues(joins, { min: cue.min, seconds }).map((c) => ({ ...c, text: gapCueText(c.seconds, cue.label, c.why) })); +} + +/** + * The marks a segment built with cut record `record` (its `start`, `end` and `gaps`: the recording's seconds, + * every second left out -- between a clip's pieces too) draws under the settings NOW (`render`, the clip's `entry`): + * its joins from the record, as the build takes them for a clip cut from its pieces. [] when nothing is marked. + * + * @param {{ render: any, entry: any, record: { start?: number, end?: number, gaps?: Array<{ from: number, to: number }> } | null }} o + */ +export function recordGapMarks({ render, entry, record }) { + const gaps = Array.isArray(record?.gaps) ? record.gaps : []; + const start = Number(record?.start); + const end = Number(record?.end); + if (!gaps.length || !Number.isFinite(start) || !Number.isFinite(end) || !gapCueWanted(render, entry)) return []; + const seconds = end - start - gaps.reduce((n, g) => n + (g.to - g.from), 0); + return segmentGapMarks({ + render, entry, seconds, + joins: segmentGapJoins({ segGaps: gaps.map((g) => ({ from: g.from - start, to: g.to - start })), clipGaps: renderGaps(entry, render), segStart: start, cue: clipGapCueOf(render, entry) }), + }); +} + +/** + * What the corner a mark ASKS for is (its gap's own, else the clip's; "auto" none): what a record keeps beside + * the corner it stood at, so a change of it is seen. + * + * @param {{ corner?: string }} mark @param {string} want the clip's (clipGapCueOf) + */ +export const gapMarkAsked = (mark, want) => (typeof mark.corner === "string" && mark.corner ? mark.corner : want && want !== "auto" ? want : null); + +/** + * Do a segment's recorded marks (its cut record's `gapMarks`: each `{at, until, seconds, text, corner, asked?}`) + * still say what the settings now draw (recordGapMarks)? null when they do, else what changed, in words -- for a + * pass that rebuilds no segment (`--chrome-only`), which would otherwise lay the old marks (or none) without a word. + * A recorded text cut to fit ("…") agrees with the text it was cut from. + * + * @param {{ render: any, entry: any, record: any }} o + * @returns {string | null} + */ +export function gapMarkDrift({ render, entry, record }) { + const now = recordGapMarks({ render, entry, record }); + const was = Array.isArray(record?.gapMarks) ? record.gapMarks : []; + if (!now.length && !was.length) return null; + if (!was.length) return `${now.length} mark${now.length === 1 ? "" : "s"} to draw, none drawn`; + if (!now.length) return `its ${was.length} mark${was.length === 1 ? "" : "s"} no longer wanted`; + if (now.length !== was.length) return `${was.length} mark${was.length === 1 ? "" : "s"} drawn, ${now.length} now`; + const want = clipGapCueOf(render, entry).corner; + const sameText = (drawn, says) => drawn === says || (typeof drawn === "string" && drawn.endsWith("…") && says.startsWith(drawn.slice(0, -1).trimEnd())); + for (const [k, m] of now.entries()) { + const w = was[k]; + if (Math.abs(m.at - Number(w?.at)) > 0.01 || Math.abs(m.until - Number(w?.until)) > 0.01) return `the mark at ${m.at} s moved`; + if (!sameText(w?.text, m.text)) return `"${w?.text}" now says "${m.text}"`; + if ((w?.asked ?? null) !== gapMarkAsked(m, want)) return `the mark at ${m.at} s asks for another corner`; + } + return null; +} + +const CORNERS = ["tl", "tr", "bl", "br"]; + +/** + * A rect on `box`'s corner `c`, `inset` in. + * + * @param {{ x: number, y: number, w: number, h: number }} box + * @param {string} c + * @param {{ w: number, h: number }} r + * @param {number} inset + */ +function cornerRect(box, c, r, inset) { + const x = c.endsWith("l") ? box.x + inset : box.x + box.w - inset - r.w; + const y = c.startsWith("t") ? box.y + inset : box.y + box.h - inset - r.h; + // Never out of its box: a mark wider (or taller) than the box less its insets stands at the box's own edge. + const cx = Math.max(box.x, Math.min(x, box.x + box.w - r.w)); + const cy = Math.max(box.y, Math.min(y, box.y + box.h - r.h)); + return { x: Math.round(cx), y: Math.round(cy), w: r.w, h: r.h }; +} + +/** The smallest a mark's face is shrunk to, to fit its box (of its size): past it, its text is cut. */ +export const GAP_MARK_FIT_MIN = 0.75; + +/** + * A mark's text and size to fit `maxW` px (its box less its insets): as it is when it fits; else its face shrunk, + * to GAP_MARK_FIT_MIN of its size at most (the box and border with it); still too wide, cut to what fits, ending + * "…". A long label and a long reason on a 1080-wide vertical frame (64 characters, about 1230 px at 32 px). + * + * @param {string} text + * @param {ReturnType<typeof gapMarkSize>} size + * @param {number} maxW + * @returns {{ text: string, size: ReturnType<typeof gapMarkSize> }} + */ +export function gapMarkFit(text, size, maxW) { + const chars = [...text]; + if (gapMarkRect(chars.length, size).w <= maxW) return { text, size }; + const pad = size.fontSize > 0 ? size.border / size.fontSize : 0; + const at = (fontSize) => ({ ...size, fontSize, border: Math.round(fontSize * pad) }); + const floor = Math.max(12, Math.ceil(size.fontSize * GAP_MARK_FIT_MIN)); + for (let f = size.fontSize - 1; f >= floor; f -= 1) { + if (gapMarkRect(chars.length, at(f)).w <= maxW) return { text, size: at(f) }; + } + const s = at(Math.min(floor, size.fontSize)); + const edge = s.border + (s.stroke ?? 0); + const n = Math.max(1, Math.floor((maxW - 2 * edge) / (ADVANCE * s.fontSize))); + return { text: n >= chars.length ? text : `${chars.slice(0, Math.max(0, n - 1)).join("").trimEnd()}…`, size: s }; +} + +const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; + +/** + * The corner each mark stands at: `want` (the clip's `corner`; `auto` is the + * layout's `prefer`), else -- when something to keep clear of (`avoid`: rects + * in the frame, each over `from`–`to` segment seconds, or always) is under + * it while the mark is up -- the next free one in tl, tr, bl, br; none free, + * `want`'s. A corner in `busy` (a code the layout draws there) is never free. + * + * @param {{ marks: Array<{ at: number, until: number, text: string, corner?: string }>, box: { x: number, y: number, w: number, h: number }, + * want: string, prefer: string, size: ReturnType<typeof gapMarkSize>, + * avoid?: Array<{ x: number, y: number, w: number, h: number, from?: number | null, to?: number | null }>, busy?: string[] }} o + * Each place carries the mark's `text` and `size` as fitted to the box + * (gapMarkFit): what is drawn, and what the record says. + * + * @returns {Array<{ corner: string, rect: { x: number, y: number, w: number, h: number }, text: string, size: ReturnType<typeof gapMarkSize> }>} + */ +export function gapMarkPlaces({ marks, box, want, prefer, size, avoid = [], busy = [] }) { + return marks.map((m) => { + // A mark's own corner (its gap's `corner`) over the clip's. + const asked = typeof m.corner === "string" && CORNERS.includes(m.corner) ? m.corner : want; + const first = asked === "auto" || !CORNERS.includes(asked) ? prefer : asked; + const order = [first, ...CORNERS.filter((c) => c !== first)]; + // Fitted to its box (gapMarkFit): never wider than the box less its insets. + const fit = gapMarkFit(m.text, size, box.w - 2 * size.inset); + const r = gapMarkRect([...fit.text].length, fit.size); + const up = avoid.filter((a) => (a.from ?? -Infinity) < m.until - EPS && (a.to ?? Infinity) > m.at + EPS); + for (const c of order) { + if (busy.includes(c)) continue; + const rect = cornerRect(box, c, r, size.inset); + if (!up.some((a) => overlaps(rect, a))) return { corner: c, rect, text: fit.text, size: fit.size }; + } + return { corner: first, rect: cornerRect(box, first, r, size.inset), text: fit.text, size: fit.size }; + }); +} + +/** + * A picture's hidden regions (clip-censor.mjs censorRegionsOf: fractions of + * the SOURCE picture, source seconds) as rects in the frame to keep the mark + * off, over their seconds on the segment's clock: the source picture `sw` × + * `sh`, its part `region` (source px; the whole of it when fitted) shown in + * `dest` (frame px). `from` / `gaps` / `seconds` as censorParts reads them. + */ +export function censorAvoidRects(regions, { sw, sh, region = null, dest, from = 0, gaps = [], seconds = Infinity }) { + const src = region ?? { x: 0, y: 0, w: sw, h: sh }; + return (regions ?? []).map((g) => { + const [bx, by, bw, bh] = g.box; + const x0 = dest.x + ((bx * sw - src.x) / src.w) * dest.w; + const y0 = dest.y + ((by * sh - src.y) / src.h) * dest.h; + const x1 = dest.x + (((bx + bw) * sw - src.x) / src.w) * dest.w; + const y1 = dest.y + (((by + bh) * sh - src.y) / src.h) * dest.h; + return { + x: Math.floor(x0), y: Math.floor(y0), w: Math.ceil(x1 - x0), h: Math.ceil(y1 - y0), + from: g.from === null || g.from === undefined ? null : Math.max(0, offsetIn(g.from, from, gaps)), + to: g.to === null || g.to === undefined ? null : Math.min(seconds, offsetIn(g.to, from, gaps)), + }; + }); +} + +/** The part of rect `a` inside rect `b` (each `{x, y, w, h}`): a mark's box kept inside a safe area. Empty: `b`. */ +export function insideRect(a, b) { + const x0 = Math.max(a.x, b.x); + const y0 = Math.max(a.y, b.y); + const x1 = Math.min(a.x + a.w, b.x + b.w); + const y1 = Math.min(a.y + a.h, b.y + b.h); + return x1 > x0 && y1 > y0 ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : { ...b }; +} + +const rectOf = (b) => ({ x: b.x, y: b.y, w: b.w ?? b.width, h: b.h ?? b.height }); +const safeRect = (a) => ({ x: a.x0, y: a.y0, w: a.x1 - a.x0, h: a.y1 - a.y0 }); + +/** + * Where a vertical clip's mark stands (vertical.mjs clipGeometry / desktopGeometry `geo`, its safe area `safe` + * `{x0, y0, x1, y1}`): always inside the safe area -- the platform draws its own buttons and bands outside it. A + * framed or quote layout's picture's top left (a framed picture's hook stands above it; a quote has no tag); a + * split's picture's top right (its tag is top left, its captions at the picture's foot, the side post under it); + * a full-bleed (full, overlay) or desktop clip's safe area's top right (the tag and the hook are at its left). + * + * @param {{ layout: string, video: { x: number, y: number, w?: number, h?: number, width?: number, height?: number } }} geo + * @param {{ x0: number, y0: number, x1: number, y1: number }} safe + * @returns {{ box: { x: number, y: number, w: number, h: number }, prefer: "tl" | "tr" }} + */ +export function verticalMarkBox(geo, safe) { + const fullBleed = !["framed", "quote", "split"].includes(geo.layout); + return { box: fullBleed ? safeRect(safe) : insideRect(rectOf(geo.video), safeRect(safe)), prefer: fullBleed || geo.layout === "split" ? "tr" : "tl" }; +} + +/** + * Where a twocrop clip's mark stands in the stacked deck (vertical-deck.mjs stackedGeometry `g`): crop one's top + * right, inside the safe area (the source line and the rail stand above crop one, the strip under it). + * + * @param {{ safe: { x0: number, y0: number, x1: number, y1: number }, twocrop: { crop1: { x: number, y: number, width: number, height: number } } }} g + */ +export const twoCropMarkBox = (g) => ({ box: insideRect(rectOf(g.twocrop.crop1), safeRect(g.safe)), prefer: /** @type {const} */ ("tr") }); + +/** A fitted picture's rect in a box (force_original_aspect_ratio=decrease, centred): `fitted` is its size. */ +export const centredIn = (box, fitted) => ({ x: box.x + Math.floor((box.w - fitted.w) / 2), y: box.y + Math.floor((box.h - fitted.h) / 2), w: fitted.w, h: fitted.h }); + +/** + * The drawtext filters for the marks (`marks` with their `places`), each text + * read from `files[k]` (written by the caller -- `places[k].text`, the mark's + * text as fitted: textfile=, so nothing needs filter escaping, and + * expansion=none, so nothing in it is expanded) at its place's `size` -- one + * comma-joined chain, or "" for none. + * + * @param {{ marks: Array<{ at: number, until: number }>, places: Array<{ rect: { x: number, y: number }, size?: ReturnType<typeof gapMarkSize> }>, + * files: string[], size: ReturnType<typeof gapMarkSize>, look?: Partial<typeof GAP_CUE_LOOK>, font?: string }} o + */ +export function gapMarkFilters({ marks, places, files, size, look = GAP_CUE_LOOK, font = MONO_BOLD_FONT_FILE }) { + const M = GAP_CUE_MOTION; + const L = { ...GAP_CUE_LOOK, ...look }; + const hex = (c) => String(c).replace(/^#/, "0x"); + return marks + .flatMap((m, k) => { + const a = f3(m.at); + const b = f3(m.until); + // gapCueAlpha (common gapCue.mjs), for ffmpeg: up over `in`, down over `out`, `peak` between. + const alpha = `${M.peak}*clip(min((t-${a})/${M.in},(${b}-t)/${M.out}),0,1)`; + const { x, y } = places[k].rect; + // A mark fitted to its box (gapMarkPlaces: a smaller face) draws at its own size. + const sz = places[k].size ?? size; + const stroke = sz.stroke ?? 0; + const at = [`x=${x + stroke + sz.border}`, `y=${y + stroke + sz.border}`, `alpha='${alpha}'`, `enable='between(t,${a},${b})'`]; + const text = (fontcolor, boxcolor, boxborderw) => + // expansion=none: the text is drawn as written -- a `%` or a `\` in a reason or a label is words, never + // drawtext's %{…} expansion (a stray % stops ffmpeg at the mark's first frame; a backslash would vanish). + [`drawtext=textfile='${files[k]}'`, "expansion=none", `fontfile='${font}'`, `fontsize=${sz.fontSize}`, `fontcolor=${fontcolor}`, "box=1", `boxcolor=${boxcolor}`, `boxborderw=${boxborderw}`, ...at].join(":"); + return [ + // The border: the same text, unseen, its box the stroke's colour and wider by the stroke. + ...(stroke > 0 ? [text(`${hex(L.fg)}@0`, `${hex(L.strokeColor)}@${L.strokeAlpha}`, sz.border + stroke)] : []), + text(hex(L.fg), `${hex(L.box)}@${L.boxAlpha}`, sz.border), + ]; + }) + .join(","); +} diff --git a/umtool/report-to-video/gap-mark.test.mjs b/umtool/report-to-video/gap-mark.test.mjs @@ -0,0 +1,209 @@ +// gap-mark.mjs (lane gap-cue, slice 1): where a segment's joins are, which are +// marked, where each mark stands, and the drawtext that draws it. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { GAP_CUE_LIFE } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; +import { + GAP_MARK_FIT_MIN, censorAvoidRects, centredIn, gapMarkDrift, gapMarkFilters, gapMarkFit, gapMarkPlaces, gapMarkRect, gapMarkSize, insideRect, + recordGapMarks, segmentGapJoins, segmentGapMarks, twoCropMarkBox, verticalMarkBox, +} from "./gap-mark.mjs"; +import { clipGeometry, desktopGeometry, desktopSafeArea, safeArea } from "./vertical.mjs"; +import { stackedGeometry } from "./vertical-deck.mjs"; +import { verticalRender } from "./vertical.mjs"; + +test("the joins: each gap's on the segment's clock (the seconds before it that play), its length, its mark", () => { + // A segment from source 100 s: gaps at 110–137 (27 s) and 150–153 (3 s), on its own clock 10–37 and 50–53. + const joins = segmentGapJoins({ + segGaps: [{ from: 10, to: 37 }, { from: 50, to: 53 }], + clipGaps: [{ from: 110, to: 137 }, { from: 150, to: 153, mark: false }], + segStart: 100, + cue: { mark: true }, + }); + assert.deepEqual(joins, [{ at: 10, seconds: 27, mark: true }, { at: 23, seconds: 3, mark: false }]); + // A clip cut from its pieces: the seconds a join says are the recording's (toReal). + const pieced = segmentGapJoins({ segGaps: [{ from: 4, to: 4.5 }], clipGaps: [{ from: 5, to: 5.5 }], segStart: 1, cue: { mark: true }, toReal: (t) => (t >= 5.5 ? t + 184.5 : t) }); + assert.deepEqual(pieced, [{ at: 4, seconds: 185, mark: true }]); +}); + +test("the marks: the clip's settings over the project's; under min none; the label's text", () => { + const joins = [{ at: 2, seconds: 27, mark: true }, { at: 8, seconds: 1.5, mark: true }, { at: 12, seconds: 75, mark: true }]; + const marks = segmentGapMarks({ render: { gapCue: { mark: true } }, entry: { type: "clip", gapCue: { label: "{s} later" } }, joins, seconds: 20 }); + assert.deepEqual(marks.map((m) => [m.at, m.text]), [[2, "27 s later"], [12, "1:15 later"]]); + assert.equal(marks[0].until, Number((2 + GAP_CUE_LIFE).toFixed(4))); +}); + +test("the place: the layout's corner, inset; off a hidden region while it is up; never a busy corner", () => { + const size = gapMarkSize(1920, 1080); + // GAP_CUE_LOOK (operator, 20 Nov: bigger, a border): 3 % of 1080, the box 0.38 em round it, a 2 px stroke. + assert.deepEqual(size, { fontSize: 32, border: 12, stroke: 2, inset: 28 }); + const box = { x: 100, y: 50, w: 1600, h: 900 }; + const marks = [{ at: 2, until: 3.1, text: "» 27 s" }, { at: 9, until: 10.1, text: "» 27 s" }]; + const r = gapMarkRect(6, size); + assert.deepEqual(r, { w: 116 + 28, h: 39 + 28 }, "six Plex Mono glyphs at 32 px, the box and the stroke round them"); + const bl = gapMarkPlaces({ marks, box, want: "auto", prefer: "bl", size }); + assert.deepEqual(bl.map((p) => p.corner), ["bl", "bl"]); + assert.deepEqual(bl[0].rect, { x: 128, y: 50 + 900 - 28 - r.h, w: r.w, h: r.h }); + // A box over the bottom left from 1.5 to 4 s: the first mark moves to the top left, the second stays. + const avoid = [{ x: 100, y: 800, w: 400, h: 150, from: 1.5, to: 4 }]; + assert.deepEqual(gapMarkPlaces({ marks, box, want: "auto", prefer: "bl", size, avoid }).map((p) => p.corner), ["tl", "bl"]); + // An asked corner wins unless something is under it; a busy corner is skipped. + assert.deepEqual(gapMarkPlaces({ marks, box, want: "br", prefer: "bl", size }).map((p) => p.corner), ["br", "br"]); + assert.deepEqual(gapMarkPlaces({ marks, box, want: "auto", prefer: "tl", size, busy: ["tl"] }).map((p) => p.corner), ["tr", "tr"]); + // A mark's own corner (its gap's, operator 20 Nov: a stream's layout can change inside one clip) over the clip's. + assert.deepEqual(gapMarkPlaces({ marks: [{ ...marks[0], corner: "tr" }, marks[1]], box, want: "br", prefer: "bl", size }).map((p) => p.corner), ["tr", "br"]); +}); + +test("the reason and the corner a join's own gaps give: the reason when they all say the same, the first corner", () => { + const joins = segmentGapJoins({ + segGaps: [{ from: 10, to: 37 }, { from: 50, to: 53 }], + clipGaps: [{ from: 110, to: 137, why: "dead-air", corner: "tr" }, { from: 150, to: 153, why: "other" }], + segStart: 100, + cue: { mark: true }, + }); + assert.deepEqual(joins, [{ at: 10, seconds: 27, mark: true, why: "dead air", corner: "tr" }, { at: 23, seconds: 3, mark: true }]); + const marks = segmentGapMarks({ render: { gapCue: { mark: true } }, entry: { type: "clip" }, joins, seconds: 40 }); + assert.deepEqual(marks.map((m) => [m.text, m.corner ?? null]), [["» 27 s · dead air", "tr"], ["» 3 s", null]]); +}); + +test("a hidden region in the frame: its source fractions through the fit, its seconds on the segment's clock", () => { + // A 1280×720 source fitted into a 1600×900 box at (100, 50); a region on its left half over source 120–130 s. + const dest = centredIn({ x: 100, y: 50, w: 1600, h: 900 }, { w: 1600, h: 900 }); + const [a] = censorAvoidRects([{ box: [0, 0.5, 0.5, 0.5], from: 120, to: 130 }], { sw: 1280, sh: 720, dest, from: 100, gaps: [{ from: 105, to: 110 }], seconds: 60 }); + assert.deepEqual(a, { x: 100, y: 500, w: 800, h: 450, from: 15, to: 25 }); + // A 9:16 crop shown full: the region through the crop. + const [b] = censorAvoidRects([{ box: [0.25, 0, 0.25, 1], from: null, to: null }], { sw: 1920, sh: 1080, region: { x: 480, y: 0, w: 608, h: 1080 }, dest: { x: 0, y: 0, w: 1080, h: 1920 } }); + assert.deepEqual([b.x, b.w, b.from, b.to], [0, 853, null, null]); +}); + +test("the filters: per mark its border (the text unseen, a wider box) then its text on its box, faded by alpha over its seconds", () => { + const size = gapMarkSize(1920, 1080); + const f = gapMarkFilters({ + marks: [{ at: 2, until: 3.1 }], + places: [{ rect: { x: 128, y: 970 } }], + files: ["/out/segments/c1.gapmark-0.txt"], + size, font: "/fonts/Mono.ttf", + }); + const at = "x=142:y=984:alpha='0.9*clip(min((t-2)/0.15,(3.1-t)/0.35),0,1)':enable='between(t,2,3.1)'"; + assert.equal( + f, + `drawtext=textfile='/out/segments/c1.gapmark-0.txt':expansion=none:fontfile='/fonts/Mono.ttf':fontsize=32:fontcolor=0xffffff@0:box=1:boxcolor=0xffffff@0.9:boxborderw=14:${at},` + + `drawtext=textfile='/out/segments/c1.gapmark-0.txt':expansion=none:fontfile='/fonts/Mono.ttf':fontsize=32:fontcolor=0xffffff:box=1:boxcolor=0x101010@0.86:boxborderw=12:${at}`, + ); + assert.equal(gapMarkFilters({ marks: [], places: [], files: [], size }), ""); +}); + +test("every drawtext draws its text as written: expansion=none, so a % or a backslash in a reason is words (review 1, 1)", () => { + const size = gapMarkSize(1920, 1080); + const marks = [{ at: 2, until: 3.1 }, { at: 6, until: 7.1 }]; + const f = gapMarkFilters({ marks, places: [{ rect: { x: 0, y: 0 } }, { rect: { x: 0, y: 0 } }], files: ["/a.txt", "/b.txt"], size }); + const each = f.split(/,(?=drawtext=)/); + assert.equal(each.length, 4, "a border and a text per mark"); + for (const d of each) assert.match(d, /^drawtext=textfile='[^']+':expansion=none:/); +}); + +test("a mark too wide for its box is drawn smaller, then cut, and never stands off the box (review 1, 9)", () => { + // A 1080-wide vertical frame: 32 px, inset 28. A 40-character label with a 24-character reason: 64 characters. + const size = gapMarkSize(1080, 1920); + const box = { x: 0, y: 0, w: 1080, h: 1920 }; + const text = `» 1:02:03 later and later and later · ${"r".repeat(24)}`; + const full = gapMarkRect([...text].length, size); + assert.ok(full.w > box.w, `as it is it would run off (${full.w} px)`); + const fit = gapMarkFit(text, size, box.w - 2 * size.inset); + assert.ok(fit.size.fontSize >= Math.ceil(size.fontSize * GAP_MARK_FIT_MIN) && fit.size.fontSize < size.fontSize, `shrunk to its floor at most (${fit.size.fontSize})`); + assert.ok(gapMarkRect([...fit.text].length, fit.size).w <= box.w - 2 * size.inset, "it fits"); + assert.equal(fit.text, text, "at a smaller face every word is kept"); + // Narrower still (a 720-wide box): at the floor and cut, ending "…". + const cut = gapMarkFit(text, size, 720 - 2 * size.inset); + assert.equal(cut.size.fontSize, Math.ceil(size.fontSize * GAP_MARK_FIT_MIN)); + assert.ok(gapMarkRect([...cut.text].length, cut.size).w <= 720 - 2 * size.inset, "it fits"); + assert.ok(cut.text.endsWith("…") && text.startsWith(cut.text.slice(0, -1)), `cut, ending … (${cut.text})`); + // Placed: every corner's rect inside the box; the record's text is the drawn one. + for (const want of ["tl", "tr", "bl", "br"]) { + for (const [b, f] of [[box, fit], [{ x: 0, y: 0, w: 720, h: 1280 }, cut]]) { + const [p] = gapMarkPlaces({ marks: [{ at: 1, until: 2.1, text }], box: b, want, prefer: "tl", size }); + assert.ok(p.rect.x >= b.x && p.rect.x + p.rect.w <= b.x + b.w && p.rect.y >= b.y, `${want}: inside (${JSON.stringify(p.rect)})`); + assert.equal(p.text, f.text); + assert.equal(p.size.fontSize, f.size.fontSize); + } + } + // Only a little too wide: a smaller face, every word kept. + const near = gapMarkFit("» 27 s · dead air", size, gapMarkRect(17, size).w - 10); + assert.equal(near.text, "» 27 s · dead air"); + assert.ok(near.size.fontSize < size.fontSize); + // One that fits is as it was; the filters draw a fitted one at its own size. + assert.deepEqual(gapMarkFit("» 27 s", size, 1000), { text: "» 27 s", size }); + const f = gapMarkFilters({ marks: [{ at: 1, until: 2.1 }], places: [{ rect: { x: 0, y: 0 }, size: near.size }], files: ["/a.txt"], size }); + assert.match(f, new RegExp(`fontsize=${near.size.fontSize}:`)); + // A box narrower than any mark: at the box's own edge, never left of it. + const [tiny] = gapMarkPlaces({ marks: [{ at: 1, until: 2.1, text: "» 27 s" }], box: { x: 100, y: 0, w: 60, h: 400 }, want: "tr", prefer: "tl", size }); + assert.equal(tiny.rect.x, 100); + assert.deepEqual(insideRect({ x: 0, y: 0, w: 1080, h: 960 }, { x: 60, y: 192, w: 960, h: 1536 }), { x: 60, y: 192, w: 960, h: 768 }); +}); + +test("a clip cut from its pieces with no pad: the join between pieces is marked, from the recording's seconds (review 1, 8)", () => { + // Pieces 1–5 and 190–200 joined end to end: on the joined file's clock the gap is nothing; in the record it is 185 s. + const render = { gapCue: { mark: true } }; + const entry = { type: "clip", id: "j1", start: 1, end: 200, gaps: [{ from: 5, to: 190, why: "idle" }] }; + const record = { start: 1, end: 200, gaps: [{ from: 5, to: 190 }] }; + const marks = recordGapMarks({ render, entry, record }); + assert.deepEqual(marks.map((m) => [m.at, m.seconds, m.text]), [[4, 185, "» 3:05 · idle"]]); + // The same as the joins the build takes for it (segmentGapJoins over the recording's seconds). + const joins = segmentGapJoins({ segGaps: [{ from: 4, to: 189 }], clipGaps: entry.gaps, segStart: 1, cue: { mark: true } }); + assert.deepEqual(segmentGapMarks({ render, entry, joins, seconds: 14 }), marks); + // The joined file's own clock (what gapsOnSegment saw) has no gap: there the build used to draw nothing. + assert.deepEqual(segmentGapJoins({ segGaps: [], clipGaps: [{ from: 4, to: 4 }], segStart: 0, cue: { mark: true } }), []); +}); + +test("gapMarkDrift: a segment's recorded marks against what the settings draw now (--chrome-only's note, review 1, 13)", () => { + const entry = { type: "clip", id: "c1", gaps: [{ from: 13, to: 40 }] }; + const record = { start: 10, end: 60, gaps: [{ from: 13, to: 40 }] }; + const on = { gapCue: { mark: true } }; + const drawn = recordGapMarks({ render: on, entry, record }).map((m) => ({ at: m.at, until: m.until, seconds: m.seconds, text: m.text, corner: "bl" })); + assert.equal(gapMarkDrift({ render: on, entry, record: { ...record, gapMarks: drawn } }), null, "as built"); + assert.equal(gapMarkDrift({ render: {}, entry, record }), null, "off, none drawn"); + assert.equal(gapMarkDrift({ render: on, entry, record }), "1 mark to draw, none drawn"); + assert.equal(gapMarkDrift({ render: {}, entry, record: { ...record, gapMarks: drawn } }), "its 1 mark no longer wanted"); + assert.match(gapMarkDrift({ render: { gapCue: { mark: true, label: "{s} later" } }, entry, record: { ...record, gapMarks: drawn } }) ?? "", /"» 27 s" now says "27 s later"/); + assert.match(gapMarkDrift({ render: on, entry: { ...entry, gapCue: { corner: "tr" } }, record: { ...record, gapMarks: drawn } }) ?? "", /another corner/); + // A text cut to fit agrees with the text it was cut from. + assert.equal(gapMarkDrift({ render: on, entry, record: { ...record, gapMarks: [{ ...drawn[0], text: "» 2…" }] } }), null); +}); + +test("a vertical clip's mark stands inside the safe area in every layout; a split's at its picture's top right, off its captions (review 1, 3 and 4)", () => { + const render = { format: "vertical" }; + const [W, H] = [1080, 1920]; + const a = safeArea(render, W, H); + const size = gapMarkSize(W, H); + const inside = (r, b) => r.x >= b.x && r.y >= b.y && r.x + r.w <= b.x + b.w && r.y + r.h <= b.y + b.h; + const safe = { x: a.x0, y: a.y0, w: a.x1 - a.x0, h: a.y1 - a.y0 }; + const want = { framed: "tl", quote: "tl", split: "tr", full: "tr", overlay: "tr" }; + for (const layout of Object.keys(want)) { + const geo = clipGeometry(layout, render, W, H); + const { box, prefer } = verticalMarkBox(geo, a); + assert.equal(prefer, want[layout], layout); + assert.ok(inside(box, safe), `${layout}: its box inside the safe area (${JSON.stringify(box)})`); + for (const corner of ["tl", "tr", "bl", "br"]) { + const [p] = gapMarkPlaces({ marks: [{ at: 1, until: 2.1, text: "» 27 s · dead air" }], box, want: corner, prefer, size }); + assert.ok(inside(p.rect, safe), `${layout} ${corner}: the mark inside the safe area (${JSON.stringify(p.rect)})`); + } + } + // The split: its captions stand at its picture's foot (align 2, marginV from the frame's bottom): the mark at the top. + const split = clipGeometry("split", render, W, H); + const [sp] = gapMarkPlaces({ marks: [{ at: 1, until: 2.1, text: "» 27 s" }], ...verticalMarkBox(split, a), want: "auto", size }); + const captionsTop = H - split.captions.marginV - split.size * 3; + assert.equal(sp.corner, "tr"); + assert.ok(sp.rect.y + sp.rect.h < captionsTop, `above the captions (${sp.rect.y + sp.rect.h} < ${captionsTop})`); + // A desktop clip: its own safe area. + const d = desktopGeometry({}, 1920, 1080, { qr: null }); + const ds = desktopSafeArea({}, 1920, 1080); + assert.ok(inside(verticalMarkBox(d, ds).box, { x: ds.x0, y: ds.y0, w: ds.x1 - ds.x0, h: ds.y1 - ds.y0 })); + // Twocrop: crop one's top right, inside the safe area. + const g = stackedGeometry(verticalRender({ width: 1920, height: 1080, fps: 30, format: "vertical", chrome: { engine: "hyperframes", layout: "deck", deck: {} } })); + const t = twoCropMarkBox(g); + assert.equal(t.prefer, "tr"); + assert.ok(inside(t.box, { x: g.safe.x0, y: g.safe.y0, w: g.safe.x1 - g.safe.x0, h: g.safe.y1 - g.safe.y0 })); + assert.ok(t.box.y >= g.twocrop.crop1.y && t.box.y + t.box.h <= g.twocrop.crop1.y + g.twocrop.crop1.height, "within crop one"); +}); diff --git a/umtool/report-to-video/gaps-render.test.mjs b/umtool/report-to-video/gaps-render.test.mjs @@ -149,6 +149,186 @@ test("render: a gap is taken out of ONE segment -- the kept seconds long, no bla } }); +// ---- the mark at a gap's join (gap-mark.mjs; common gapCue.mjs) ------------------- + +/** Each frame's mean luma over a `w` × `h` crop at (x, y). */ +function cropLumas(file, x, y, w, h) { + const st = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `crop=${w}:${h}:${x}:${y},signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); + return st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[1])); +} +const setManifest = async (p, fn) => { + const m = JSON.parse(await readFile(p.manifestPath, "utf8")); + fn(m); + await writeFile(p.manifestPath, JSON.stringify(m)); +}; +const reusedIds = (events) => events.filter((e) => e.ev === "note" && / segment unchanged /.test(e.message)).map((e) => e.message.split(":")[0]); + +test("the gap mark OFF -- nothing set, mark false, a gap's why, a marked gap under min -- is the segment it was: reused, the same key, nothing new in its record", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ gaps: [{ from: 3, to: 4 }] }); + try { + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + const was = await record(p, "c1"); + const bytes = md5(p.seg("c1")); + const offs = [ + (m) => { m.render.gapCue = { mark: false }; }, + (m) => { m.timeline[0].gaps[0].why = "dead-air"; m.timeline[0].gapCue = { corner: "br" }; }, + // On, but the gap is 1 s: under the default 2 s minimum it draws nothing. + (m) => { m.render.gapCue = { mark: true }; }, + ]; + for (const off of offs) { + await setManifest(p, off); + const events = []; + setProgressMode((e) => events.push(e)); + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + assert.ok(reusedIds(events).includes("c1"), `c1 reused (${JSON.stringify(reusedIds(events))})`); + const now = await record(p, "c1"); + assert.equal(now.segKey, was.segKey, "the same key: the same argv, inputs and record"); + assert.equal(now.gapMarks, undefined); + assert.equal(md5(p.seg("c1")), bytes); + } + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("the gap mark ON draws '» 1 s' at the join over its life, in the record; only that segment re-renders; off again it is the plain segment's bytes", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ gaps: [{ from: 3, to: 4 }] }); + const plain = await project({ gaps: [{ from: 3, to: 4 }] }); + try { + await buildVideo({ manifestPath: plain.manifestPath, opts: { noNetwork: true } }); + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + const c2 = md5(p.seg("c2")); + await setManifest(p, (m) => { m.render.gapCue = { mark: true, min: 0.5 }; }); + const events = []; + setProgressMode((e) => events.push(e)); + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + assert.ok(!reusedIds(events).includes("c1") && reusedIds(events).includes("c2"), `c1 rebuilt, c2 reused (${JSON.stringify(reusedIds(events))})`); + assert.equal(md5(p.seg("c2")), c2); + const rec = await record(p, "c1"); + // The join: 2 s into c1 (1–3 plays, 3–4 is out). Up 1.1 s, at the plain cut's top left. + assert.deepEqual(rec.gapMarks.map(({ rect, ...m }) => m), [{ at: 2, until: 3.1, seconds: 1, text: "» 1 s", corner: "tl" }]); + assert.deepEqual([rec.gapMarks[0].rect.x, rec.gapMarks[0].rect.y], [8, 8], "the record says where it was drawn: the picture's top left, inset"); + near(await probeDuration(p.seg("c1"), FPS), 4, 1 / FPS + 1e-6, "the mark adds no time"); + // Its box at 320×180 (GAP_CUE_LOOK): inset 8, a 2 px light border, then the dark box (5 px above a 12 px face): + // the box's top inside the border is darker than the grey while it is up. + const y = cropLumas(p.seg("c1"), 11, 10, 30, 4); + const yPlain = cropLumas(plain.seg("c1"), 11, 10, 30, 4); + const at = (arr, t) => arr[Math.floor(t * FPS)]; + near(at(y, 1.5), at(yPlain, 1.5), 1, "before the join: as plain"); + assert.ok(at(yPlain, 2.5) - at(y, 2.5) > 20, `up at 2.5 s (${at(y, 2.5)} vs ${at(yPlain, 2.5)})`); + near(at(y, 3.5), at(yPlain, 3.5), 1, "gone after its life"); + // Off again: the plain segment, byte for byte. + await setManifest(p, (m) => { delete m.render.gapCue; }); + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + assert.equal(md5(p.seg("c1")), md5(plain.seg("c1"))); + assert.equal((await record(p, "c1")).gapMarks, undefined); + } finally { + await rm(p.root, { recursive: true, force: true }); + await rm(plain.root, { recursive: true, force: true }); + } +}); + +test("the gap mark draws a reason as written: a % and a backslash are words, the build never stops on them (review 1, 1)", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const { clipGapCueOf } = await import("yt-dlp-transcript-common/lib/report/gapCue.mjs"); + const { clipGapMarks } = await import("../lib/report/gapCueView.mjs"); + for (const reason of ["100% idle", "a\\b c", "50% %d"]) { + const p = await project({ gaps: [{ from: 3, to: 4, reason }] }); + try { + await setManifest(p, (m) => { m.render.gapCue = { mark: true, min: 0.5, label: "{s} (90%)[ · {why}]" }; }); + const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + assert.equal(r.failures.length, 0, `${JSON.stringify(reason)}: ${JSON.stringify(r.failures)}`); + const rec = await record(p, "c1"); + // The text the page draws (gapCueView, the same rule) is the text the build drew, byte for byte. + const m = JSON.parse(await readFile(p.manifestPath, "utf8")); + const page = clipGapMarks({ cue: clipGapCueOf(m.render, m.timeline[0]), gaps: m.timeline[0].gaps, from: 1, to: 6 }); + assert.equal(rec.gapMarks[0].text, `1 s (90%) · ${reason}`); + assert.equal(rec.gapMarks[0].text, page[0].text); + assert.equal(await readFile(path.join(p.root, "out", "sourced", "segments", "c1.gapmark-0.txt"), "utf8"), page[0].text, "what drawtext reads"); + near(await probeDuration(p.seg("c1"), FPS), 4, 1 / FPS + 1e-6, "the segment is whole"); + } finally { + await rm(p.root, { recursive: true, force: true }); + } + } +}); + +// ---- the mark off is the segment it was, in every layout that draws one -------------- +// The deck (its footage framed for the chrome), a bare vertical cut (full), and the stacked vertical deck's +// twocrop: each built with a gap, then with render.gapCue mark false (and a clip's gapCue saying nothing new), +// then with the mark on and off again -- off, the same key and the same bytes as with nothing set. + +const { verticalRender } = await import("./vertical.mjs"); +const LAYOUTS = { + deck: { render: { ...RENDER, width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }, clip: {} }, + vertical: { render: { ...RENDER, format: "vertical" }, clip: {} }, + twocrop: { + render: { ...RENDER, format: "vertical", chrome: { engine: "hyperframes", layout: "deck", deck: {} } }, + clip: { vertical: { layout: "twocrop", crops: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1]] } }, + }, +}; +for (const [name, L] of Object.entries(LAYOUTS)) { + test(`the gap mark OFF in the ${name} layout is the segment it was (the same key, the same bytes); ON it is drawn there`, { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ gaps: [{ from: 2.5, to: 5.5 }], ...L.clip }); + const events = []; + try { + await setManifest(p, (m) => { m.render = L.render; }); + const segOf = async () => { + const dir = path.join(p.root, "out"); + const { readdir } = await import("node:fs/promises"); + for (const sub of await readdir(dir)) { + const f = path.join(dir, sub, "segments", "c1.mp4"); + if (spawnSync("test", ["-f", f]).status === 0) return f; + } + throw new Error("no c1 segment"); + }; + const build = async () => { + events.length = 0; + setProgressMode((e) => events.push(e)); + const r = await buildVideo({ manifestPath: p.manifestPath, only: "c1", opts: { noNetwork: true } }); + assert.equal(r.failures.length, 0, JSON.stringify(r.failures)); + const seg = await segOf(); + return { seg, rec: JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")), md5: md5(seg), reused: reusedIds(events).includes("c1") }; + }; + const plain = await build(); + assert.equal(plain.rec.gapMarks, undefined); + for (const off of [(m) => { m.render.gapCue = { mark: false }; }, (m) => { m.timeline[0].gapCue = { corner: "br" }; m.timeline[0].gaps[0].why = "idle"; }]) { + await setManifest(p, off); + const b = await build(); + assert.ok(b.reused, `${name}: reused with the mark off`); + assert.equal(b.rec.segKey, plain.rec.segKey, `${name}: the same key`); + assert.equal(b.rec.gapMarks, undefined); + assert.equal(b.md5, plain.md5); + } + await setManifest(p, (m) => { m.render.gapCue = { mark: true }; delete m.timeline[0].gapCue; }); + const on = await build(); + assert.ok(!on.reused, `${name}: rebuilt with the mark on`); + assert.notEqual(on.rec.segKey, plain.rec.segKey); + assert.equal(on.rec.gapMarks?.length, 1); + assert.equal(on.rec.gapMarks[0].text, "» 3 s · idle"); + // Drawn by that layout's path, where it puts it (gap-mark.mjs verticalMarkBox, twoCropMarkBox). + const { rect, corner } = on.rec.gapMarks[0]; + if (name === "deck") assert.equal(corner, "bl"); + else { + assert.equal(on.rec.vertical?.layout, name === "twocrop" ? "twocrop" : "full"); + assert.equal(corner, "tr"); + const { safeArea } = await import("./vertical.mjs"); + const a = safeArea(verticalRender(L.render), 1080, 1920); + assert.ok(rect.x >= a.x0 && rect.y >= a.y0 && rect.x + rect.w <= a.x1 && rect.y + rect.h <= a.y1, `inside the safe area (${JSON.stringify(rect)})`); + } + await setManifest(p, (m) => { delete m.render.gapCue; }); + const back = await build(); + assert.equal(back.rec.segKey, plain.rec.segKey, `${name}: off again, the plain key`); + assert.equal(back.md5, plain.md5, `${name}: off again, the plain bytes`); + } finally { + quiet(); + await rm(p.root, { recursive: true, force: true }); + } + }); +} + // ---- a gap-joined clip cut from its pieces ----------------------------------------- // Two moments of one recording joined by a gap: 1–5 s and 190–200 s. Only the // two pieces are on disk (two windows, the second WHITE with a higher tone), @@ -207,7 +387,15 @@ test("render: a gap-joined clip whose pieces are minutes apart is cut from its t await buildVideo({ manifestPath, opts: { noNetwork: true } }); assert.equal(md5(seg), before); assert.ok(events.some((e) => e.ev === "note" && / segment unchanged /.test(e.message) && e.message.split(":")[0] === "j1"), "the segment is reused"); - // Padded pieces (fetchPad 3): the pad between them is a gap on the joined clock; the same cut. + // The mark on, no pad: the join between the pieces is no gap on the joined file's clock, but it is the + // recording's 185 s -- marked, as Play and the bench mark it (review 1, 8). + const marked = JSON.parse(await readFile(manifestPath, "utf8")); + marked.render = { ...marked.render, gapCue: { mark: true } }; + await writeFile(manifestPath, JSON.stringify(marked)); + await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const mrec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); + assert.deepEqual(mrec.gapMarks?.map((g) => [g.at, g.seconds, g.text]), [[4, 185, "» 3:05"]]); + // Padded pieces (fetchPad 3): the pad between them is a gap on the joined clock; the same cut, the same mark. const m = JSON.parse(await readFile(manifestPath, "utf8")); m.render = { ...m.render, fetchPad: 3 }; await writeFile(manifestPath, JSON.stringify(m)); @@ -217,6 +405,7 @@ test("render: a gap-joined clip whose pieces are minutes apart is cut from its t near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "padded: the kept seconds still"); const padded = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8")); assert.deepEqual([padded.start, padded.end, padded.gaps], [1, 200, [{ from: 5, to: 190 }]]); + assert.deepEqual(padded.gapMarks?.map((g) => [g.at, g.seconds, g.text]), [[4, 185, "» 3:05"]]); } finally { quiet(); await rm(root, { recursive: true, force: true }); diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -25,10 +25,19 @@ // join, where the gap was), `sourceAtOffset` maps back (the join shows the // material after the gap). // -// Dependency-free, so a client bundle (Play the cut, the clip editor, the live -// preview) takes it alone; the writer (umtool lib/report/manifest.mjs), the -// build's validators (lint.mjs, build-video.mjs) and `umtool check` share -// `validateGaps`. +// A gap may also carry settings of its own -- whether its join is MARKED +// (`mark`: true | false, over its clip's and the project's `gapCue`), what it +// was cut for (`why`: "dead-air" | "idle" | "other"), a few words its mark +// says (`reason`) and the corner its mark stands at (`corner`) -- common +// lib/report/gapCue.mjs is that rule, and the one list of their values. They +// ride along with the gap through every list here and change none of its +// seconds; a gap grown over others (editGaps `add`) keeps what they agree on. +// +// Dependency-free but for common gapCue.mjs (itself dependency-free), so a +// client bundle (Play the cut, the clip editor, the live preview) takes it +// alone; the writer (umtool lib/report/manifest.mjs), the build's validators +// (lint.mjs, build-video.mjs) and `umtool check` share `validateGaps`. +import { GAP_OWN_CORNERS, GAP_REASON_MAX, GAP_REASON_RULE, GAP_WHY, gapReasonOk } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; /** The rules a clip's gaps keep: seconds (min, keep) and a count (max). */ export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 40, keep: 0.5 }); @@ -37,6 +46,26 @@ export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 40, keep: 0.5 }); export const GAP_FADE = 0.025; const fin = (v) => typeof v === "number" && Number.isFinite(v); +/** What a gap was cut for (common gapCue.mjs GAP_WHY, the one list). */ +export const GAP_WHY_VALUES = GAP_WHY; +/** A gap's own reason, its longest (common gapCue.mjs). */ +export { GAP_REASON_MAX }; +/** The corners a gap's own mark may stand at (common gapCue.mjs GAP_OWN_CORNERS). */ +export const GAP_CORNER_VALUES = GAP_OWN_CORNERS; +/** Is `v` a gap's reason (common gapCue.mjs gapReasonOk: one line of words, no control character, no `[ ] { }`). */ +const reasonOk = gapReasonOk; +/** + * A gap's own keys beyond its seconds, kept as they are: `mark` (a boolean), `why` (GAP_WHY_VALUES), `reason` + * (a few words its mark says, reasonOk) and `corner` (GAP_CORNER_VALUES: where its mark stands). + */ +export const gapOwnKeys = (x) => ({ + ...(typeof x?.mark === "boolean" ? { mark: x.mark } : {}), + ...(GAP_WHY_VALUES.includes(x?.why) ? { why: x.why } : {}), + ...(reasonOk(x?.reason) ? { reason: x.reason.trim() } : {}), + ...(GAP_CORNER_VALUES.includes(x?.corner) ? { corner: x.corner } : {}), +}); +/** The sentence for a reason that is not one. */ +const REASON_RULE = GAP_REASON_RULE; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const EPS = 1e-6; /** The writer's tolerance for a stored 2 dp edge (manifest.mjs WIN_EPS). */ @@ -67,7 +96,7 @@ export function gapsOf(entry) { if (!Array.isArray(g) || !g.length) return []; return g .filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from) - .map((x) => ({ from: x.from, to: x.to })) + .map((x) => ({ from: x.from, to: x.to, ...gapOwnKeys(x) })) .sort((a, b) => a.from - b.from); } @@ -128,6 +157,10 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}` errors.push(`${where}.gaps[${k}] ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); return; } + if (g.mark !== undefined && typeof g.mark !== "boolean") errors.push(`${where}.gaps[${k}].mark is true (mark its join) or false, not ${JSON.stringify(g.mark)}`); + if (g.why !== undefined && !GAP_WHY_VALUES.includes(g.why)) errors.push(`${where}.gaps[${k}].why is one of ${GAP_WHY_VALUES.join(", ")}, not ${JSON.stringify(g.why)}`); + if (g.reason !== undefined && !reasonOk(g.reason)) errors.push(`${where}.gaps[${k}].reason is ${REASON_RULE}, not ${JSON.stringify(g.reason)}`); + if (g.corner !== undefined && !GAP_CORNER_VALUES.includes(g.corner)) errors.push(`${where}.gaps[${k}].corner is one of ${GAP_CORNER_VALUES.join(", ")}, not ${JSON.stringify(g.corner)}`); ok.push({ ...g, k }); }); if (errors.length) return errors; @@ -291,7 +324,7 @@ export function validateGapEntries(manifest) { export function normalizeGaps(list) { const r2 = (n) => Number(Number(n).toFixed(2)); return (list ?? []) - .map((g) => ({ from: r2(g.from), to: r2(g.to) })) + .map((g) => ({ from: r2(g.from), to: r2(g.to), ...gapOwnKeys(g) })) .sort((a, b) => a.from - b.from || a.to - b.to); } @@ -506,13 +539,17 @@ export function recordGaps(record) { /** * Edit a clip's gaps list, as the CLI and the clip editor ask: `add` a span - * (merged with any gap it touches or overlaps), `remove` the gap holding a + * (merged with any gap it touches or overlaps, keeping what those say of + * themselves: mergedOwnKeys), `remove` the gap holding a * source second (or starting nearest it, within `tolerance`), or `set` the - * whole list (`[]` clears it). Returns the new list, normalized; the caller - * validates it on the entry. + * whole list (`[]` clears it), or `edit` the gap holding a source second + * (`{ at, mark?, why?, reason?, corner? }`: each set, or null to drop it -- its seconds never + * move). Returns the new list, normalized; the caller validates it on the + * entry. * * @param {Array<{ from: number, to: number }>} gaps the clip's now - * @param {{ add?: { from: number, to: number }, remove?: number, set?: Array<{ from: number, to: number }> }} op + * @param {{ add?: { from: number, to: number }, remove?: number, set?: Array<{ from: number, to: number }>, + * edit?: { at: number, mark?: boolean | null, why?: string | null, reason?: string | null, corner?: string | null } }} op * @param {{ tolerance?: number }} [opts] */ export function editGaps(gaps, op, { tolerance = 0.05 } = {}) { @@ -521,15 +558,18 @@ export function editGaps(gaps, op, { tolerance = 0.05 } = {}) { if (op.add) { let { from, to } = op.add; if (!(fin(from) && fin(to)) || to <= from) throw new Error(`a gap needs from < to in source seconds (got ${from}–${to})`); - // A span that touches or overlaps a gap grows it: two gaps a hair apart are one cut. + // A span that touches or overlaps a gap grows it: two gaps a hair apart are one cut -- keeping what the gaps + // it took in say of themselves (mergedOwnKeys), so a gap grown on the bench keeps its mark, why and corner. const keepList = []; + const absorbed = []; for (const g of list) { if (g.to >= from - EPS && g.from <= to + EPS) { from = Math.min(from, g.from); to = Math.max(to, g.to); + absorbed.push(g); } else keepList.push(g); } - list = [...keepList, { from, to }]; + list = [...keepList, { from, to, ...mergedOwnKeys(absorbed) }]; } if (op.remove !== undefined) { const t = Number(op.remove); @@ -538,9 +578,43 @@ export function editGaps(gaps, op, { tolerance = 0.05 } = {}) { if (k < 0) throw new Error(`no gap at ${t}${list.length ? ` (gaps: ${list.map((g) => `${g.from}–${g.to}`).join(", ")})` : " — the clip has none"}`); list = list.filter((_, i) => i !== k); } + if (op.edit !== undefined) { + const t = Number(op.edit?.at); + if (!fin(t)) throw new Error(`which gap? a source second inside it (got ${op.edit?.at})`); + const k = list.findIndex((g) => t >= g.from - tolerance && t <= g.to + tolerance); + if (k < 0) throw new Error(`no gap at ${t}${list.length ? ` (gaps: ${list.map((g) => `${g.from}–${g.to}`).join(", ")})` : " — the clip has none"}`); + const next = { ...list[k] }; + for (const key of ["mark", "why", "reason", "corner"]) { + if (!(key in op.edit)) continue; + const v = op.edit[key]; + if (v === null || v === undefined || (key === "reason" && typeof v === "string" && !v.trim())) delete next[key]; + else if (key === "mark" && typeof v !== "boolean") throw new Error(`a gap's mark is on, off or default (got ${JSON.stringify(v)})`); + else if (key === "why" && !GAP_WHY_VALUES.includes(v)) throw new Error(`a gap's why is ${GAP_WHY_VALUES.join(", ")} or default (got ${JSON.stringify(v)})`); + else if (key === "reason" && !reasonOk(v)) throw new Error(`a gap's reason is ${REASON_RULE} (got ${JSON.stringify(v)})`); + else if (key === "corner" && !GAP_CORNER_VALUES.includes(v)) throw new Error(`a gap's corner is ${GAP_CORNER_VALUES.join(", ")} or default (got ${JSON.stringify(v)})`); + else next[key] = key === "reason" ? v.trim() : v; + } + list = list.map((g, i) => (i === k ? next : g)); + } return normalizeGaps(list); } +/** + * What gaps merged into one keep of their own settings (gapOwnKeys), by the rule a mark that joins them says + * (common gapCue.mjs gapOwnSays): `why` and `reason` only when every one of them gives the same, `corner` the first + * (in source order) that names one, `mark` on when any is on -- off only when every one is off. None merged: none. + * + * @param {Array<Record<string, any>>} gaps + */ +export function mergedOwnKeys(gaps) { + const own = [...(gaps ?? [])].sort((a, b) => a.from - b.from).map((g) => gapOwnKeys(g)); + if (!own.length) return {}; + const same = (k) => (own.every((o) => o[k] !== undefined && o[k] === own[0][k]) ? { [k]: own[0][k] } : {}); + const corner = own.map((o) => o.corner).find((c) => c !== undefined); + const mark = own.some((o) => o.mark === true) ? { mark: true } : own.every((o) => o.mark === false) ? { mark: false } : {}; + return { ...mark, ...same("why"), ...same("reason"), ...(corner !== undefined ? { corner } : {}) }; +} + /** `12.3-15.1` (or `12.3–15.1`, `12.3..15.1`) as a gap; null when it is not one. */ export function parseGapSpec(text) { const m = String(text ?? "").trim().match(/^(\d+(?:\.\d+)?)\s*(?:-|–|\.\.)\s*(\d+(?:\.\d+)?)$/); diff --git a/umtool/report-to-video/gaps.test.mjs b/umtool/report-to-video/gaps.test.mjs @@ -13,7 +13,7 @@ import path from "node:path"; import test from "node:test"; import { - GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapWalls, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin, + GAP_FADE, GAP_LIMITS, editGaps, mergedOwnKeys, gapFilterParts, gapWalls, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin, inGap, keptSpans, normalizeGaps, offsetIn, parseGapSpec, recordGaps, renderGaps, sourceAtOffset, validateGapEntries, validateGaps, } from "./gaps.mjs"; @@ -142,6 +142,47 @@ test("editGaps: add (merging what it touches), remove by a second inside, set; p assert.equal(GAP_LIMITS.min, 0.2); }); +test("a gap's own mark and why (common gapCue.mjs) ride along: kept, checked, edited, never moving its seconds", () => { + const own = [{ from: 105, to: 107, mark: false, why: "dead-air" }, { from: 110, to: 110.5 }]; + assert.deepEqual(gapsOf({ ...CLIP, gaps: own }), own); + assert.deepEqual(gapsOf({ ...CLIP, gaps: [{ from: 105, to: 107, mark: "no", why: "boring", label: "x" }] }), [{ from: 105, to: 107 }], "ill-formed ones are not read"); + assert.deepEqual(normalizeGaps([{ from: 105.004, to: 107, why: "other" }]), [{ from: 105, to: 107, why: "other" }]); + assert.deepEqual(validateGaps({ ...CLIP, gaps: own }), []); + const errs = validateGaps({ ...CLIP, gaps: [{ from: 105, to: 107, mark: "no" }, { from: 110, to: 110.5, why: "boring" }] }, "c1"); + assert.deepEqual(errs, ['c1.gaps[0].mark is true (mark its join) or false, not "no"', 'c1.gaps[1].why is one of dead-air, idle, other, not "boring"']); + assert.deepEqual(editGaps(own, { edit: { at: 106, mark: true } }), [{ from: 105, to: 107, mark: true, why: "dead-air" }, { from: 110, to: 110.5 }]); + assert.deepEqual(editGaps(own, { edit: { at: 106, mark: null, why: null } }), [{ from: 105, to: 107 }, { from: 110, to: 110.5 }]); + assert.deepEqual(editGaps(own, { edit: { at: 110.2, why: "other" } })[1], { from: 110, to: 110.5, why: "other" }); + assert.throws(() => editGaps(own, { edit: { at: 108, mark: true } }), /no gap at 108/); + assert.throws(() => editGaps(own, { edit: { at: 106, why: "boring" } }), /why is dead-air, idle, other or default/); + // Its reason (a few words its mark says) and its corner (where its mark stands), lane gap-cue rulings 20 Nov. + assert.deepEqual(editGaps(own, { edit: { at: 106, reason: " ad break ", corner: "tr" } })[0], { from: 105, to: 107, mark: false, why: "dead-air", reason: "ad break", corner: "tr" }); + assert.deepEqual(editGaps([{ from: 105, to: 107, reason: "x" }], { edit: { at: 106, reason: "" } })[0], { from: 105, to: 107 }, "empty words drop it"); + assert.throws(() => editGaps(own, { edit: { at: 106, reason: "a reason far too long for one small mark" } }), /at most 24 characters/); + assert.throws(() => editGaps(own, { edit: { at: 106, corner: "middle" } }), /corner is tl, tr, bl, br or default/); + assert.match(validateGaps({ ...CLIP, gaps: [{ from: 105, to: 107, reason: "[x]" }] }, "c1").join(), /reason is a few words/); + // One line, drawn as written: a tab or other control character is refused (review 1, 1); a % is words. + for (const bad of ["a\tb", "a\u2028b", "a\u0000"]) assert.match(validateGaps({ ...CLIP, gaps: [{ from: 105, to: 107, reason: bad }] }, "c1").join(), /no tab or other control character/); + assert.deepEqual(validateGaps({ ...CLIP, gaps: [{ from: 105, to: 107, reason: "100% idle" }] }), []); + // Adding a gap elsewhere keeps the others' own keys. + assert.deepEqual(editGaps(own, { add: { from: 114, to: 115 } })[0], own[0]); +}); + +test("a gap grown over others keeps what they say of themselves: why and reason when all agree, the first corner, mark on if any (review 1, 2)", () => { + // One gap grown: all its own settings kept. + const one = [{ from: 105, to: 107, mark: true, why: "dead-air", reason: "walks off", corner: "tr" }]; + assert.deepEqual(editGaps(one, { add: { from: 106.5, to: 108 } }), [{ from: 105, to: 108, mark: true, why: "dead-air", reason: "walks off", corner: "tr" }]); + // Two joined by a span over both: the why they share, no reason (they differ), the first corner, mark on (one is). + const two = [{ from: 105, to: 106, mark: false, why: "idle", reason: "a", corner: "bl" }, { from: 107, to: 108, mark: true, why: "idle", reason: "b", corner: "tr" }]; + assert.deepEqual(editGaps(two, { add: { from: 105.5, to: 107.5 } }), [{ from: 105, to: 108, mark: true, why: "idle", corner: "bl" }]); + // Off only when every one is off; a why one of them lacks is not kept. + assert.deepEqual(mergedOwnKeys([{ from: 1, to: 2, mark: false, why: "idle" }, { from: 3, to: 4, mark: false }]), { mark: false }); + assert.deepEqual(mergedOwnKeys([{ from: 1, to: 2, mark: false }, { from: 3, to: 4 }]), {}); + assert.deepEqual(mergedOwnKeys([]), {}); + // A span touching nothing is a plain gap, as ever. + assert.deepEqual(editGaps(one, { add: { from: 110, to: 111 } })[1], { from: 110, to: 111 }); +}); + // ---- the filtergraph ------------------------------------------------------------ test("gapFilterParts: nothing without gaps; trim + concat with a fade at each join with", () => { diff --git a/umtool/report-to-video/modules/config-loader.test.mjs b/umtool/report-to-video/modules/config-loader.test.mjs @@ -173,3 +173,19 @@ test("the panel: a module's fields from its descriptor, a save as the writers ta assert.throws(() => panelWrite(m, "qr", { enabled: false }), /not switched on and off/); assert.deepEqual(setPath({ a: { b: 1 } }, "a.b", null), {}); }); + +test("the panel: the gap mark (an input module, a look key the writer merges) is listed, and a field cleared is sent as null", async () => { + const { applyLookPatch } = await import("yt-dlp-transcript-common/lib/report/look.mjs"); + const m = { ...manifest(), render: { ...manifest().render, gapCue: { mark: true, min: 4 } } }; + const row = panelState(m, m, {}).find((r) => r.id === "gap-cue"); + assert.ok(row, "the gap mark is in the panel"); + assert.equal(row.base, "render.gapCue"); + assert.deepEqual(row.fields, { mark: true, min: 4 }); + assert.deepEqual(row.ui.map((f) => f.key), ["mark", "min", "corner", "label"]); + // min cleared, the label set: min goes as null, so the merging writer drops it. + const w = panelWrite(m, "gap-cue", { fields: { min: null, label: "{s} later" } }); + assert.deepEqual(w.render, { gapCue: { min: null, mark: true, label: "{s} later" } }); + assert.deepEqual(applyLookPatch(m, w.render).render.gapCue, { mark: true, label: "{s} later" }); + // Every field cleared: the block goes. + assert.deepEqual(panelWrite(m, "gap-cue", { fields: { mark: null, min: null } }).render, { gapCue: null }); +}); diff --git a/umtool/report-to-video/modules/gap-cue.mjs b/umtool/report-to-video/modules/gap-cue.mjs @@ -0,0 +1,40 @@ +// THE GAP MARK (module `gap-cue`, an input): "» 27 s" at the join a clip's gap +// leaves, drawn into the clip's segment over its seconds (report-to-video +// gap-mark.mjs; the settings, the label and the timing: common +// lib/report/gapCue.mjs, which umtool's pages read too). It draws on the +// footage at its encode, so it has no page and no region. +import { GAP_CUE_CORNERS, GAP_CUE_DEFAULTS, GAP_CUE_LABEL_MAX, GAP_CUE_MIN, GAP_REASON_MAX, validateGapCue } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; +import { defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "gap-cue", + version: 1, + z: 3, + kind: "input", + slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs): drawn in the segment, as the blur is. + vertical: { slot: "input" }, + title: "Gap mark", + summary: "A small mark at each join a clip's gap leaves, saying how much was skipped.", + configKey: "render.gapCue", + defaults: { ...GAP_CUE_DEFAULTS }, + validate: (_value, { manifest }) => validateGapCue(manifest), + ui: [ + { key: "mark", type: "boolean", label: "Mark the gaps' joins", default: GAP_CUE_DEFAULTS.mark }, + { key: "min", type: "number", min: GAP_CUE_MIN.min, max: GAP_CUE_MIN.max, step: 0.5, label: "Shortest gap marked (s)", default: GAP_CUE_DEFAULTS.min }, + { key: "corner", type: "enum", options: [...GAP_CUE_CORNERS], label: "Corner", default: GAP_CUE_DEFAULTS.corner }, + { key: "label", type: "text", label: "Label ({s} the time skipped, {why} the reason, [ ] only with one)", default: GAP_CUE_DEFAULTS.label }, + ], + docs: { + heading: "Gap mark", + intro: "The full reference is [Gaps inside a clip](#gaps-inside-a-clip) (the mark at the join).", + rows: [ + ["`render.gapCue.mark`", "`true` · `false` · default `false` (off: every cut renders as it did)", "`umtool look <p> gapCue='{\"mark\":true}'` · a take: `--set render.gapCue.mark=true`"], + ["`render.gapCue.min`", `${GAP_CUE_MIN.min}–${GAP_CUE_MIN.max} s · default ${GAP_CUE_DEFAULTS.min} (a shorter gap draws nothing)`, "`umtool look <p> gapCue='{\"min\":4}'`"], + ["`render.gapCue.corner`", "`auto` (the layout's free corner) · `tl` · `tr` · `bl` · `br` · default `auto`", "`umtool look <p> gapCue='{\"corner\":\"br\"}'`"], + ["`render.gapCue.label`", `text holding \`{s}\` (the time skipped: \`27 s\`, from a minute \`1:12\`) and maybe \`{why}\` (the gap's reason); a part in \`[ ]\` is drawn only when the gap has one; at most ${GAP_CUE_LABEL_MAX} characters · default \`${GAP_CUE_DEFAULTS.label}\` (\`» 27 s\`, \`» 26 s · dead air\`)`, "`umtool look <p> gapCue='{\"label\":\"{s} later\"}'`"], + ["a clip's `gapCue`", "the same keys, over the project's", "`umtool set <p> <clip> gapCue.mark=false gapCue.corner=tr` (`gapCue=` clears them)"], + ["a gap's `mark`, `why`, `reason`, `corner`", `\`mark\` \`true\` · \`false\` (over the clip's and the project's); \`why\` \`dead-air\` · \`idle\` · \`other\` (the mark says "dead air", "idle", nothing); \`reason\` its own words, 1-${GAP_REASON_MAX} characters, said instead; \`corner\` \`tl\` · \`tr\` · \`bl\` · \`br\` (its mark there, over the clip's)`, "`umtool set <p> <clip> gap.mark=12.3:off gap.why=12.3:dead-air gap.reason=12.3:walks off gap.corner=12.3:tr` (`…:default`, `gap.reason=12.3:` drop one) · the bench: click the gap's band"], + ], + }, +}); diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -33,6 +33,7 @@ import counter from "./counter.mjs"; import claims from "./claims.mjs"; import intro from "./intro.mjs"; import blur from "./blur.mjs"; +import gapCue from "./gap-cue.mjs"; import pair from "./pair.mjs"; import chapter from "./chapter.mjs"; import status from "./status.mjs"; @@ -54,7 +55,7 @@ export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, RE /** Every module, by z (stack order), then id. */ export const MODULES = Object.freeze( - [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, analysis, intro, blur, pair, chapter, status, chat, shelf, diet, peak, goals, promise, streak, dial, odometer, trail, dialFinale, runsFinale] + [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, analysis, intro, blur, gapCue, pair, chapter, status, chat, shelf, diet, peak, goals, promise, streak, dial, odometer, trail, dialFinale, runsFinale] .sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)), ); diff --git a/umtool/report-to-video/modules/panel.mjs b/umtool/report-to-video/modules/panel.mjs @@ -18,6 +18,8 @@ import { MODULES } from "./index.mjs"; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +/** Look keys whose writer merges a patch into what it holds (common look.mjs applyLookPatch): the gap mark's. */ +const MERGED_LOOK_KEYS = new Set(["gapCue"]); /** Where a module's ui keys are rooted. */ export function uiBase(m) { @@ -159,7 +161,14 @@ export function panelWrite(manifest, id, { fields = {}, enabled } = {}) { const patch = {}; for (const k of new Set([...Object.keys(render), ...Object.keys(next)])) { if (k === "chrome") continue; - if (JSON.stringify(render[k]) !== JSON.stringify(next[k])) patch[k] = next[k] === undefined ? null : next[k]; + if (JSON.stringify(render[k]) === JSON.stringify(next[k])) continue; + if (next[k] === undefined) patch[k] = null; + else if (MERGED_LOOK_KEYS.has(k) && isObj(next[k])) { + // A look key the writer MERGES (applyLookPatch: each key over what it holds, null drops one): a field + // cleared here is sent as null, or it would stay. + const was = isObj(render[k]) ? render[k] : {}; + patch[k] = { ...Object.fromEntries(Object.keys(was).filter((x) => !(x in next[k])).map((x) => [x, null])), ...next[k] }; + } else patch[k] = next[k]; } return { render: patch }; } diff --git a/umtool/report-to-video/modules/rail.mjs b/umtool/report-to-video/modules/rail.mjs @@ -74,6 +74,7 @@ export default defineModule({ ["`deck.pip.sectionColor0`", "the section before the first marker, with `color: \"section\"`: a `#hex` or a palette key (`fg`, `muted`, `accent`, `amber`, `dim`) · default the accent", "`umtool look <p> deck.pip='{\"color\":\"section\",\"sectionColor0\":\"#5fa8d3\"}'`"], ["`deck.markers[].label`", "optional: a marker with none (or `\"\"`) draws a tick at its boundary, no words, and takes no band over the track", "`umtool look <p> deck.markers='[{\"after\":\"c04\",\"color\":\"#e07a9a\"}]'`"], ["`deck.markers[].level`", "`1` (a section, the default) · `2` (a subsection of the section before it: a shorter flag or a half-height tick, its label smaller and quieter, and in sections no colour of its own -- its pips, fuse and ring keep its section's; to every edit a section like any other; the cut's first marker must be a section) · at most 32 markers in all; past a dozen labelled, a label too crowded to say anything is drawn as a tick", "`umtool look <p> deck.markers='[{\"after\":\"c04\",\"label\":\"Early days\",\"level\":2}]'`"], + ["a rail of one or two pips", "never drawn (deck.mjs `RAIL_MIN_PIPS`, 3): a cut -- or a window take, which lays only the clips it covers -- of one or two clips draws no pip track, no fuse, no marker and no flags; the stacked deck no rail and no count; the finale no large rail. Nothing moves into the room. No setting draws one under three", "—"], ["`deck.rail.labels`", "`false` draws every marker as a tick, no words, and no band over the track (the current section's name can stand under the rail instead: [Section title](#section-title)) · default `true`","`umtool look <p> deck.rail='{\"labels\":false}'`"], ], }, diff --git a/umtool/report-to-video/rail-min.test.mjs b/umtool/report-to-video/rail-min.test.mjs @@ -0,0 +1,67 @@ +// No rail of one or two items (operator, 20 Nov: "the fact there's a one item timeline looks bad. Don't do that."): +// the deck's pip track, the stacked deck's rail and the finale's large rail are not drawn under RAIL_MIN_PIPS -- +// their markup there, hidden, nothing else moved -- and at or over it the page is the one it always was. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { finaleRegions } from "./build-video.mjs"; +import { deckHtml } from "./chrome-deck.mjs"; +import { finaleHtml } from "./chrome-finale.mjs"; +import { stackedDeckHtml } from "./chrome-vdeck.mjs"; +import { deckSchedule, RAIL_MIN_PIPS, railDrawn, railOffStyle } from "./deck.mjs"; +import { verticalRender } from "./vertical.mjs"; + +const PALETTE = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" }; +const render = (deck = {}) => ({ width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, chrome: { engine: "hyperframes", layout: "deck", deck } }); +const clips = (n, extra = {}) => Array.from({ length: n }, (_, i) => ({ id: `c${i}`, type: "clip", video: `v${i}`, start: 100, end: 130, title: `T${i}`, ...(extra[i] ?? {}) })); +const sched = (n, r) => deckSchedule({ entries: clips(n), durs: Array(n).fill(30), D: 0.5, render: r, provenance: {}, metas: Array(n).fill(null) }); + +test("the rule: three pips or more draw a rail; one or two none", () => { + assert.equal(RAIL_MIN_PIPS, 3); + assert.deepEqual([1, 2, 3, 4].map(railDrawn), [false, false, true, true]); + assert.equal(railOffStyle(3), "", "drawn: no attribute at all, the markup as it was"); + assert.equal(railOffStyle(2), ' style="display:none"'); +}); + +test("the deck: 1 and 2 pips, its track hidden (pips, marker, fuse, flags with it); 3, the track as it always was", () => { + const r = render(); + for (const n of [1, 2]) assert.match(deckHtml(sched(n, r), r), /<div class="track" style="display:none">\s*<div class="rail"><\/div>/, `${n} pip(s)`); + const three = deckHtml(sched(3, r), r); + assert.match(three, /<div class="track">\s*<div class="rail"><\/div>/); + assert.ok(!three.includes('style="display:none"'), "nothing hidden at three"); + // Nothing else moves: the 2-pip page with its track shown is the markup a drawn rail would have. + const two = deckHtml(sched(2, r), r); + assert.equal(two.replace('<div class="track" style="display:none">', '<div class="track">').includes('<div class="track">'), true); + assert.equal(two.split('style="display:none"').length - 1, 1, "only the track"); +}); + +test("the stacked deck: its rail and a twocrop strip's bars hidden under three; at three as it was", () => { + const v = verticalRender({ ...render(), format: "vertical" }); + for (const n of [1, 2]) { + const html = stackedDeckHtml(sched(n, v), v, {}); + assert.match(html, /<div class="rail" data-k="rail" style="display:none">/, `${n}`); + assert.match(html, /<div class="top2" data-k="top2">(?:(?!<div class="bars).)*<div class="bars" style="display:none">/s); + } + const three = stackedDeckHtml(sched(3, v), v, {}); + assert.match(three, /<div class="rail" data-k="rail">/); + assert.ok(!three.includes('style="display:none"')); +}); + +test("the finale's large rail: hidden whole under three pips; at three as it was", () => { + const fr = render({ finale: {} }); + const page = (n) => { + const s = deckSchedule({ entries: clips(n + 1, { [n]: { layout: "finale" } }), durs: Array(n + 1).fill(30), D: 0.5, render: fr, provenance: {} }); + return finaleHtml(s, fr, finaleRegions(fr, "/tmp/x", s)[0].window, {}); + }; + const one = page(1); + assert.match(one, /<div class="track" data-k="track" style="display:none"><\/div>/); + // Its spans, marks and pips in one hidden wrapper, its leaders and labels in another. + const wraps = one.split('<div style="display:none">'); + assert.equal(wraps.length - 1, 2); + assert.ok(wraps[1].includes('data-k="p0"'), "the pips are inside the hidden rail"); + const three = page(3); + assert.match(three, /<div class="track" data-k="track"><\/div>/); + assert.ok(!three.includes('style="display:none"')); +});