commit decf277138ebfadc6b49d7489579089857c5228a
parent ad7172453bff969e01c3a848be10eec5db48c53a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 20 Nov 2026 15:21:02 -0500
umtool: the gap mark draws its text as written, fits its place, and keeps a gap's settings (review 1)
- drawtext expansion=none on both of the mark's drawtexts: a % in a reason or
a label no longer stops ffmpeg at the mark's first frame, and a backslash is
drawn. A label or a reason refuses a tab and every other control character
(common gapCue.mjs gapReasonOk, the one rule gaps.mjs now imports).
- A gap grown over others (editGaps add) keeps what they said of themselves:
why and reason when they all agree, the first corner, the mark on if any
was (gaps.mjs mergedOwnKeys); the bench's note says what it kept.
- Every vertical mark stands inside the safe area: a split's at its
picture's top right (its captions are at the foot), a quote's inside the
safe area, a twocrop's at crop one's top right (verticalMarkBox,
twoCropMarkBox).
- A mark wider than its box is drawn smaller, then cut with an ellipsis, and
is clamped into the box (gapMarkFit); the record keeps the drawn text, its
rect and the corner it asked for.
- A clip cut from its pieces with no pad marks the join between them (the
recording's seconds, as Play and the bench do).
- A merged mark's corner is the first of its joins that names one.
- --chrome-only says, per clip, when a mark changed since its segment was
built (gapMarkDrift). A gapCue write that changes nothing takes no undo
point.
- The bench keeps one video element whatever is drawn over it.
- take --at: no gaps subtracted under render.montage.
- Tests: deck, vertical and twocrop segments are byte for byte the plain ones
with the mark off; the e2e undo count is strict.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
23 files changed, 693 insertions(+), 147 deletions(-)
diff --git a/common/lib/report/gapCue.d.mts b/common/lib/report/gapCue.d.mts
@@ -18,6 +18,8 @@ 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;
diff --git a/common/lib/report/gapCue.mjs b/common/lib/report/gapCue.mjs
@@ -64,6 +64,18 @@ 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
@@ -99,7 +111,7 @@ export function gapCueErrors(v, where = "render.gapCue") {
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 (v.label.length > GAP_CUE_LABEL_MAX || /[\n\r]/.test(v.label)) errors.push(`${where}.label is one line of at most ${GAP_CUE_LABEL_MAX} characters`);
+ 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;
@@ -147,7 +159,7 @@ function own(v) {
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}") && v.label.length <= GAP_CUE_LABEL_MAX && labelPartsOk(v.label)) out.label = v.label;
+ if (typeof v.label === "string" && v.label.includes("{s}") && labelLineOk(v.label) && labelPartsOk(v.label)) out.label = v.label;
return out;
}
@@ -252,7 +264,7 @@ export function gapCueText(seconds, label = GAP_CUE_DEFAULTS.label, why = "") {
* 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's. A mark never outlives
+ * 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.
*
@@ -274,6 +286,8 @@ export function gapCues(joins, { min = GAP_CUE_DEFAULTS.min, seconds = Infinity,
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 : "" };
diff --git a/common/lib/report/gapCue.test.ts b/common/lib/report/gapCue.test.ts
@@ -14,6 +14,7 @@ import {
gapCueWanted,
gapCues,
gapMarkOn,
+ gapReasonOk,
gapWhyWord,
validateGapCue,
} from "./gapCue.mjs";
@@ -85,6 +86,29 @@ test("the marks: under min nothing, marked only, joins within a life are one mar
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);
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -6,13 +6,19 @@
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 is an undo point.
- The project's settings are in the Media tab's Modules panel (Gap mark). A field cleared there now clears.
+ - 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 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
@@ -22,14 +28,17 @@
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 the safe area's top right in a 9:16 full-bleed clip. When a hidden
- region or a code is in that corner while the mark is up, the mark moves to the next free corner.
+ 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 may also record `why` (`dead-air` or `other`). Nothing draws it yet.
+ 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
@@ -38,7 +47,7 @@
- **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.
+ that play, as the build and Play the cut do. Under `render.montage`, which applies no gaps, it counts the whole cut.
- **A fetch the platform refused for one video now records why.**
- The chat replay pass (`fetch-chat`, the chat backlog, find-clips) and `refresh-metadata` used to drop a refusal
such as "Join this channel to get access to members-only content". A stream backfilled "public" while it was
diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts
@@ -83,7 +83,7 @@ export async function PUT(request: Request) {
"gaps",
"gapAdd",
"gapRemove",
- // One gap's own settings, its seconds as they are (`gapEdit`: {at, mark?, why?}, a key null drops it),
+ // 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",
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -1475,6 +1475,8 @@ export default function ClipBench({
() => 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 });
@@ -2979,17 +2981,26 @@ export default function ClipBench({
>
{placeBar}
<div className="flex md:contents">
- {cached && ((data.hidden?.length ?? 0) > 0 || benchMarks.length > 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
@@ -2997,32 +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}
/>
- {(data.hidden?.length ?? 0) > 0 && <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
diff --git a/umtool/components/projects/bench/BenchWave.tsx b/umtool/components/projects/bench/BenchWave.tsx
@@ -118,7 +118,7 @@ export function BenchWaveBox({
silences={silences}
words={words}
busy={busy}
- onRemove={gap.band}
+ onBand={gap.band}
onSelect={gap.select}
picked={gap.picked}
pickable={gap.settings}
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,7 +200,7 @@ export function GapLayer({
silences,
words,
busy,
- onRemove,
+ onBand,
onSelect,
live = null,
walls = null,
@@ -227,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);
@@ -304,7 +307,7 @@ export function GapLayer({
: `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)}
+ 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)]",
diff --git a/umtool/components/projects/bench/useGapEditor.ts b/umtool/components/projects/bench/useGapEditor.ts
@@ -33,6 +33,16 @@ export type GapEdit = {
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
* (lane/clip-fixes, operator 6 Nov: "the gap tool gets blocked at random
@@ -130,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);
@@ -198,12 +212,12 @@ export function useGapEditor({
(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(() => {
diff --git a/umtool/components/projects/review/GapMarkChip.tsx b/umtool/components/projects/review/GapMarkChip.tsx
@@ -77,6 +77,10 @@ export default function GapMarkChip({
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}
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -218,8 +218,11 @@ seconds (`report-to-video/gaps.mjs` is the rule and both clocks).
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 reel beat's band keeps its old click
- (it puts the gap back): a beat's gap has no settings.
+ 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.
@@ -233,8 +236,14 @@ seconds (`report-to-video/gaps.mjs` is the rule and both clocks).
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 foot (split) or the safe area's top right (full bleed, desktop); a hidden
- region up while the mark is, or a code, under that corner moves it to the next free one. **The automatic corner
+ 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
@@ -246,8 +255,17 @@ seconds (`report-to-video/gaps.mjs` is the rule and both clocks).
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. The pages do not move it off a hidden region or a code as the build does, and a vertical cut's page
- uses the deck's or the plain cut's corner. The record says where each was drawn (`gapMarks` in `segments/<id>.cut.json`).
+ 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.
diff --git a/umtool/e2e/gap-cue.spec.ts b/umtool/e2e/gap-cue.spec.ts
@@ -73,11 +73,19 @@ test("the bench: a gap's band picks it; its mark, why, words and corner, and the
// 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.
+ // 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");
@@ -108,7 +116,7 @@ test("the bench: a gap's band picks it; its mark, why, words and corner, and the
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()).toBeGreaterThanOrEqual(before2);
+ expect(undoPoints()).toBeGreaterThan(before2);
await page.locator("[data-gap-cue-corner]").selectOption("");
await expect.poll(() => clipOf().gapCue?.corner).toBeUndefined();
diff --git a/umtool/lib/report/gaps-writer.test.mjs b/umtool/lib/report/gaps-writer.test.mjs
@@ -115,6 +115,11 @@ test("the bench's mark settings leave an undo point, as a gap write does: a clip
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 () => {
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -295,12 +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).
- // The mark at its gaps' joins (`gapCue`, lane gap-cue) is the gaps' too: the bench writes it as it writes a gap.
- const gaps = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) || patch.gapCue !== 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);
@@ -714,7 +717,7 @@ 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`);
- // A gap's own mark and why (common gapCue.mjs) ride along, checked as they are.
+ // 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.
@@ -736,10 +739,14 @@ 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? }` (or a list): one gap's own settings, its seconds as they are.
+ // `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?: dead-air|other|null }");
+ 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 });
}
}
@@ -1946,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 ?? [] }));
@@ -1955,8 +1963,9 @@ 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.
- const snapshot = "gapCue" in patch ? await autoSnapshot(dir, "gaps") : null;
+ // 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, ...(snapshot ? { snapshot } : {}) };
});
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -50,7 +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, gapsOf } from "umtool-report-to-video/gaps";
+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";
@@ -249,16 +249,20 @@ export async function loadMontageStyles({ file = montageStylesFile() } = {}) {
/**
* 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.
+ * 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) {
+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 gappedLength(a, b, gapsOf(e));
+ 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;
@@ -280,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]));
@@ -299,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;
});
@@ -687,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));
@@ -697,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
@@ -129,6 +129,9 @@ test("windowEntries: by the manifest's own lengths, or by the deck's schedule wh
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,7 +183,9 @@ 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, gapMarkFilters, gapMarkPlaces, gapMarkSize, segmentGapJoins, segmentGapMarks } from "./gap-mark.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";
@@ -1684,6 +1686,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
@@ -1696,11 +1704,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)) })) }
: {}),
@@ -1835,10 +1839,19 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// 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.
- const gapMarks = segGaps.length && gapCueWanted(render, clipE)
+ // 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: segmentGapJoins({ segGaps, clipGaps, segStart: fetchStart + segA, cue: clipGapCueOf(render, clipE), toReal }),
+ 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 }),
})
: [];
/**
@@ -1849,14 +1862,23 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const markChain = async ({ box, prefer, avoid = [], busy = [] }) => {
if (!gapMarks.length) return "";
const size = gapMarkSize(width, height);
- const places = gapMarkPlaces({ marks: gapMarks, box, want: clipGapCueOf(render, clipE).corner, prefer, size, avoid, busy });
+ 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, m] of gapMarks.entries()) {
+ for (const k of gapMarks.keys()) {
const file = path.join(outDir, "segments", `${entry.id}.gapmark-${k}.txt`);
- await replaceFile(file, m.text);
+ await replaceFile(file, places[k].text);
files.push(file);
}
- cutRecord.gapMarks = gapMarks.map((m, k) => ({ at: m.at, until: m.until, seconds: m.seconds, ...(m.count > 1 ? { count: m.count } : {}), text: m.text, corner: places[k].corner }));
+ // `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`. */
@@ -1949,18 +1971,17 @@ 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: a framed or quote layout's on its picture (top-left: the hook stands above it), a split's at the
- // picture's foot (its tag is at the top), 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.
+ // 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 vsafe = geo.safe ?? safeArea(render, width, height);
- const fullBleed = !["framed", "quote", "split"].includes(geo.layout);
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({
- box: fullBleed ? { x: vsafe.x0, y: vsafe.y0, w: vsafe.x1 - vsafe.x0, h: vsafe.y1 - vsafe.y0 } : vbox,
- prefer: geo.layout === "split" ? "bl" : fullBleed ? "tr" : "tl",
+ ...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
@@ -2025,8 +2046,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 the frame's top right (two crops: their hidden regions are under the crops, not mapped here).
- const tmark = await markChain({ box: { x: 0, y: 0, w: width, h: height }, prefer: "tr" });
+ // 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: [
@@ -7732,6 +7754,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/gap-mark.mjs b/umtool/report-to-video/gap-mark.mjs
@@ -7,13 +7,15 @@
// 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 video or 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), 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.
+// 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
@@ -25,9 +27,9 @@
// 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, gapCues, gapMarkOn, gapOwnSays } from "yt-dlp-transcript-common/lib/report/gapCue.mjs";
+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 } from "./gaps.mjs";
+import { offsetIn, renderGaps } from "./gaps.mjs";
/** Plex Mono's advance, in ems: every glyph the same width. */
const ADVANCE = 0.6;
@@ -101,6 +103,60 @@ export function segmentGapMarks({ render, entry, joins, seconds }) {
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"];
/**
@@ -114,7 +170,38 @@ const CORNERS = ["tl", "tr", "bl", "br"];
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;
- return { x: Math.round(x), y: Math.round(y), w: r.w, h: 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;
@@ -129,7 +216,10 @@ const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h
* @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
- * @returns {Array<{ corner: string, rect: { x: number, y: number, w: number, h: number } }>}
+ * 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) => {
@@ -137,14 +227,16 @@ export function gapMarkPlaces({ marks, box, want, prefer, size, avoid = [], busy
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)];
- const r = gapMarkRect([...m.text].length, size);
+ // 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 };
+ 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) };
+ return { corner: first, rect: cornerRect(box, first, r, size.inset), text: fit.text, size: fit.size };
});
}
@@ -171,22 +263,59 @@ export function censorAvoidRects(regions, { sw, sh, region = null, dest, from =
});
}
+/** 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: textfile=, so nothing needs
- * filter escaping) -- one comma-joined chain, or "" for none.
+ * 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 } }>,
+ * @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");
- const stroke = size.stroke ?? 0;
return marks
.flatMap((m, k) => {
const a = f3(m.at);
@@ -194,13 +323,18 @@ export function gapMarkFilters({ marks, places, files, size, look = GAP_CUE_LOOK
// 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;
- const at = [`x=${x + stroke + size.border}`, `y=${y + stroke + size.border}`, `alpha='${alpha}'`, `enable='between(t,${a},${b})'`];
+ // 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) =>
- [`drawtext=textfile='${files[k]}'`, `fontfile='${font}'`, `fontsize=${size.fontSize}`, `fontcolor=${fontcolor}`, "box=1", `boxcolor=${boxcolor}`, `boxborderw=${boxborderw}`, ...at].join(":");
+ // 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}`, size.border + stroke)] : []),
- text(hex(L.fg), `${hex(L.box)}@${L.boxAlpha}`, size.border),
+ ...(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
@@ -7,8 +7,12 @@ import test from "node:test";
import { GAP_CUE_LIFE } from "yt-dlp-transcript-common/lib/report/gapCue.mjs";
import {
- censorAvoidRects, centredIn, gapMarkFilters, gapMarkPlaces, gapMarkRect, gapMarkSize, segmentGapJoins, segmentGapMarks,
+ 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.
@@ -85,8 +89,121 @@ test("the filters: per mark its border (the text unseen, a wider box) then its t
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':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':fontfile='/fonts/Mono.ttf':fontsize=32:fontcolor=0xffffff:box=1:boxcolor=0x101010@0.86:boxborderw=12:${at}`,
+ `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
@@ -208,7 +208,8 @@ test("the gap mark ON draws '» 1 s' at the join over its life, in the record; o
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, [{ at: 2, until: 3.1, seconds: 1, text: "» 1 s", corner: "tl" }]);
+ 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.
@@ -229,6 +230,105 @@ test("the gap mark ON draws '» 1 s' at the join over its life, in the record; o
}
});
+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),
@@ -287,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));
@@ -297,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,15 +25,19 @@
// join, where the gap was), `sourceAtOffset` maps back (the join shows the
// material after the gap).
//
-// A gap may also say whether its join is MARKED (`mark`: true | false, over its
-// clip's and the project's `gapCue`) and what it was cut for (`why`: "dead-air"
-// | "other") -- common lib/report/gapCue.mjs is that rule. Both ride along
-// with the gap through every list here and change none of its seconds.
+// 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, 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`.
+// 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 });
@@ -42,14 +46,14 @@ 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: kept here too, this module imports nothing). */
-export const GAP_WHY_VALUES = Object.freeze(["dead-air", "idle", "other"]);
-/** A gap's own reason, its longest (common gapCue.mjs GAP_REASON_MAX). */
-export const GAP_REASON_MAX = 24;
+/** 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 = Object.freeze(["tl", "tr", "bl", "br"]);
-/** Is `v` a gap's reason: one line of words, 1 to GAP_REASON_MAX characters once trimmed. */
-const reasonOk = (v) => typeof v === "string" && v.trim().length > 0 && v.trim().length <= GAP_REASON_MAX && !/[\n\r[\]{}]/.test(v);
+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).
@@ -61,7 +65,7 @@ export const gapOwnKeys = (x) => ({
...(GAP_CORNER_VALUES.includes(x?.corner) ? { corner: x.corner } : {}),
});
/** The sentence for a reason that is not one. */
-const REASON_RULE = `a few words, at most ${GAP_REASON_MAX} characters on one line (no [ ] { })`;
+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). */
@@ -535,7 +539,8 @@ 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), or `edit` the gap holding a source second
* (`{ at, mark?, why?, reason?, corner? }`: each set, or null to drop it -- its seconds never
@@ -553,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);
@@ -591,6 +599,22 @@ export function editGaps(gaps, op, { tolerance = 0.05 } = {}) {
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";
@@ -161,10 +161,28 @@ test("a gap's own mark and why (common gapCue.mjs) ride along: kept, checked, ed
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", () => {