// GAPS INSIDE A CLIP: seconds taken out of the middle of one clip, which then // plays as ONE segment of jump cuts -- one header, one pip, one subtitle card -- // rather than as two clips with a crossfade between them. // // timeline entry: "gaps": [{ "from": 32988.4, "to": 32990.1 }, ...] // // SOURCE seconds, like `start`/`end`/`cutStart`/`cutEnd`. Each gap lies inside // the clip's CUT (its `cutStart`–`cutEnd`, else its extent), at least // GAP_LIMITS.min long, at most GAP_LIMITS.max of them (40: a long clip cut down // to its sentences; nothing downstream counts them -- gapFilterParts splits into // as many pieces as there are), sorted, apart, and with // at least GAP_LIMITS.keep seconds of material before the first, between any // two and after the last: a sliver of picture between two jumps reads as a // glitch, not a cut. A `muteFrom` or a claim mark's `at` strictly INSIDE a gap // is refused: it names a second the cut never plays, and moving it to the // join would move a decision somebody made by ear (an `at`, or the mark, on // a gap's edge is fine -- it lands at the join). // // Absent (or empty), every number below is the one a clip without gaps always // had: `offsetIn(src, from, [])` is `src - from`, byte for byte. // // THE CLOCKS. A segment's picture starts at source second `from` (its cut // record's `start`); the gapped clock counts only the seconds that PLAY. // `offsetIn` maps a source second onto it (a second inside a gap lands on the // join, where the gap was), `sourceAtOffset` maps back (the join shows the // material after the gap). // // A gap may also carry settings of its own -- whether its join is MARKED // (`mark`: true | false, over its clip's and the project's `gapCue`), what it // was cut for (`why`: "dead-air" | "idle" | "other"), a few words its mark // says (`reason`) and the corner its mark stands at (`corner`) -- common // lib/report/gapCue.mjs is that rule, and the one list of their values. They // ride along with the gap through every list here and change none of its // seconds; a gap grown over others (editGaps `add`) keeps what they agree on. // // Dependency-free but for common gapCue.mjs (itself dependency-free), so a // client bundle (Play the cut, the clip editor, the live preview) takes it // alone; the writer (umtool lib/report/manifest.mjs), the build's validators // (lint.mjs, build-video.mjs) and `umtool check` share `validateGaps`. import { GAP_OWN_CORNERS, GAP_REASON_MAX, GAP_REASON_RULE, GAP_WHY, gapReasonOk } from "yt-dlp-transcript-common/lib/report/gapCue.mjs"; /** The rules a clip's gaps keep: seconds (min, keep) and a count (max). */ export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 40, keep: 0.5 }); /** Each join's fade, in seconds: out over the end of the piece before, in over the start of the piece after -- short enough to keep a word, long enough not to click. */ export const GAP_FADE = 0.025; const fin = (v) => typeof v === "number" && Number.isFinite(v); /** What a gap was cut for (common gapCue.mjs GAP_WHY, the one list). */ export const GAP_WHY_VALUES = GAP_WHY; /** A gap's own reason, its longest (common gapCue.mjs). */ export { GAP_REASON_MAX }; /** The corners a gap's own mark may stand at (common gapCue.mjs GAP_OWN_CORNERS). */ export const GAP_CORNER_VALUES = GAP_OWN_CORNERS; /** Is `v` a gap's reason (common gapCue.mjs gapReasonOk: one line of words, no control character, no `[ ] { }`). */ const reasonOk = gapReasonOk; /** * A gap's own keys beyond its seconds, kept as they are: `mark` (a boolean), `why` (GAP_WHY_VALUES), `reason` * (a few words its mark says, reasonOk) and `corner` (GAP_CORNER_VALUES: where its mark stands). */ export const gapOwnKeys = (x) => ({ ...(typeof x?.mark === "boolean" ? { mark: x.mark } : {}), ...(GAP_WHY_VALUES.includes(x?.why) ? { why: x.why } : {}), ...(reasonOk(x?.reason) ? { reason: x.reason.trim() } : {}), ...(GAP_CORNER_VALUES.includes(x?.corner) ? { corner: x.corner } : {}), }); /** The sentence for a reason that is not one. */ const REASON_RULE = GAP_REASON_RULE; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const EPS = 1e-6; /** The writer's tolerance for a stored 2 dp edge (manifest.mjs WIN_EPS). */ const WIN_EPS = 0.02; /** * The span a clip's gaps must lie in: its cut when it has both fields, else * its extent. * * @param {Record} entry * @returns {{ from: number, to: number }} */ export function gapSpan(entry) { const hasCut = fin(entry?.cutStart) && fin(entry?.cutEnd); return { from: hasCut ? entry.cutStart : entry?.start, to: hasCut ? entry.cutEnd : entry?.end }; } /** * A clip's gaps as the arithmetic reads them: the well-formed ones, sorted. * [] for none -- and for anything that is not a list (validateGaps says why; * the build refuses it before it gets here). * * @param {Record | null | undefined} entry * @returns {Array<{ from: number, to: number }>} */ export function gapsOf(entry) { const g = entry?.gaps; if (!Array.isArray(g) || !g.length) return []; return g .filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from) .map((x) => ({ from: x.from, to: x.to, ...gapOwnKeys(x) })) .sort((a, b) => a.from - b.from); } /** Does this clip carry any gap? */ export const hasGaps = (entry) => gapsOf(entry).length > 0; /** * The gaps a render of this block applies to a clip: its own, except in a * montage (render.montage), which cuts every clip to its phrase. * * @param {Record} entry * @param {Record} [render] */ export function renderGaps(entry, render = {}) { if (entry?.type !== "clip") return []; if (render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage)) return []; return gapsOf(entry); } /** * The marks a clip carries, raw (`claims`, else `claim`) -- what an `at` * inside a gap is looked for in. */ const marksAt = (entry) => (Array.isArray(entry?.claims) ? entry.claims : isObj(entry?.claim) ? [entry.claim] : []) .filter((m) => isObj(m) && fin(m.at)); /** The gap a source second lies strictly inside, or null. */ export function inGap(src, gaps) { if (!fin(src)) return null; for (const g of gaps ?? []) if (src > g.from + EPS && src < g.to - EPS) return g; return null; } /** * Every reason a clip's `gaps` cannot be built, as sentences naming `where` * (empty: it can). Absent or null is none; `[]` is none too (the writer * removes it). * * @param {Record} entry * @param {string} [where] * @returns {string[]} */ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}`) { const v = entry?.gaps; if (v === undefined || v === null) return []; if (entry.type !== "clip") return [`${where}.gaps: only a clip has seconds to take out`]; if (!Array.isArray(v)) return [`${where}.gaps must be a list of { from, to } in source seconds`]; if (!v.length) return []; const errors = []; if (v.length > GAP_LIMITS.max) errors.push(`${where}.gaps: at most ${GAP_LIMITS.max} gaps in one clip (it has ${v.length}) — split it into clips`); const ok = []; v.forEach((g, k) => { if (!isObj(g) || !fin(g.from) || !fin(g.to)) { errors.push(`${where}.gaps[${k}] must be { from, to } in source seconds`); return; } if (g.to - g.from < GAP_LIMITS.min - EPS) { errors.push(`${where}.gaps[${k}] ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); return; } if (g.mark !== undefined && typeof g.mark !== "boolean") errors.push(`${where}.gaps[${k}].mark is true (mark its join) or false, not ${JSON.stringify(g.mark)}`); if (g.why !== undefined && !GAP_WHY_VALUES.includes(g.why)) errors.push(`${where}.gaps[${k}].why is one of ${GAP_WHY_VALUES.join(", ")}, not ${JSON.stringify(g.why)}`); if (g.reason !== undefined && !reasonOk(g.reason)) errors.push(`${where}.gaps[${k}].reason is ${REASON_RULE}, not ${JSON.stringify(g.reason)}`); if (g.corner !== undefined && !GAP_CORNER_VALUES.includes(g.corner)) errors.push(`${where}.gaps[${k}].corner is one of ${GAP_CORNER_VALUES.join(", ")}, not ${JSON.stringify(g.corner)}`); ok.push({ ...g, k }); }); if (errors.length) return errors; for (let i = 1; i < ok.length; i += 1) { if (ok[i].from < ok[i - 1].from) { errors.push(`${where}.gaps must be in order (gaps[${ok[i].k}] ${ok[i].from} starts before gaps[${ok[i - 1].k}] ${ok[i - 1].from})`); return errors; } } const span = gapSpan(entry); const keep = GAP_LIMITS.keep; // The span is the cut when the clip has one, else its extent: say which. const whose = fin(entry.cutStart) && fin(entry.cutEnd) ? "cut" : "clip"; ok.forEach((g, i) => { if (fin(span.from) && fin(span.to) && (g.from < span.from - WIN_EPS || g.to > span.to + WIN_EPS)) { errors.push(`${where}.gaps[${g.k}] ${g.from}–${g.to} lies outside the clip's ${whose} ${span.from}–${span.to} — widen the ${whose}, or remove the gap`); return; } const before = i === 0 ? span.from : ok[i - 1].to; const what = i === 0 ? `the ${whose}'s start` : `gaps[${ok[i - 1].k}]`; if (fin(before) && g.from - before < keep - WIN_EPS) { errors.push( i > 0 && g.from < before ? `${where}.gaps[${g.k}] ${g.from}–${g.to} overlaps ${what} — merge them into one gap` : `${where}.gaps[${g.k}] ${g.from}–${g.to} leaves ${Math.max(0, g.from - before).toFixed(2)} s after ${what}; keep at least ${keep} s between cuts`, ); } }); const last = ok[ok.length - 1]; if (!errors.length && fin(span.to) && span.to - last.to < keep - WIN_EPS) { errors.push(`${where}.gaps[${last.k}] ${last.from}–${last.to} leaves ${Math.max(0, span.to - last.to).toFixed(2)} s before the ${whose}'s end; keep at least ${keep} s`); } if (errors.length) return errors; // A mark that names a second the cut never plays. if (fin(entry.muteFrom) && inGap(entry.muteFrom, ok)) { const g = inGap(entry.muteFrom, ok); errors.push(`${where}.muteFrom ${entry.muteFrom} lies inside the gap ${g.from}–${g.to}, which never plays — move the mark to the gap's edge, or remove the gap`); } for (const m of marksAt(entry)) { const g = inGap(m.at, ok); const name = typeof m.id === "string" && m.id ? `the mark ${m.id}'s second` : "the stamp's second"; if (g) errors.push(`${where}: ${name} (at ${m.at}) lies inside the gap ${g.from}–${g.to}, which never plays — move it, or remove the gap`); } return errors; } /** * WHERE A GAP CANNOT GO in a clip, and why -- validateGaps's rules as spans * and seconds a waveform can draw (lane/clip-fixes; operator, 6 Nov: "the gap * tool gets blocked at random invisible walls"). Every wall a gap dragged on * the bench stops at is one of these: * * span where gaps lie at all (gapSpan: the cut, else the extent); `whose` * says which, in the words validateGaps uses * zones inside the span, the seconds no gap may reach into: GAP_LIMITS.keep * after the span's start and before its end, and beside each gap * (a span reaching INTO a gap is not refused -- it grows it, * editGaps -- but one stopping short in its keep band is) * marks the seconds no gap may COVER (strictly inside): the mute mark, each * claim mark's or stamp's `at` * * A gap avoiding every zone's interior and covering no mark, at least * GAP_LIMITS.min long, apart from the rest and under GAP_LIMITS.max of them, is * one validateGaps accepts (gaps.test.mjs holds the two to each other). * * @param {Record} entry * @returns {{ span: { from: number, to: number }, whose: "cut" | "clip", * zones: Array<{ from: number, to: number, kind: "keep-start" | "keep-end" | "keep-gap", why: string }>, * marks: Array<{ at: number, kind: "mute" | "mark" | "stamp", id: string | null, why: string }> }} */ export function gapWalls(entry) { const span = gapSpan(entry); const whose = fin(entry?.cutStart) && fin(entry?.cutEnd) ? "cut" : "clip"; const keep = GAP_LIMITS.keep; const zones = []; if (fin(span.from) && fin(span.to)) { zones.push({ from: span.from, to: Math.min(span.to, span.from + keep), kind: "keep-start", why: `keep at least ${keep} s after the ${whose}'s start` }); zones.push({ from: Math.max(span.from, span.to - keep), to: span.to, kind: "keep-end", why: `keep at least ${keep} s before the ${whose}'s end` }); } for (const g of gapsOf(entry)) { const why = `keep at least ${keep} s between cuts — or drag into the gap ${g.from}–${g.to} to grow it`; zones.push({ from: g.from - keep, to: g.from, kind: "keep-gap", why }); zones.push({ from: g.to, to: g.to + keep, kind: "keep-gap", why }); } const marks = []; if (fin(entry?.muteFrom)) marks.push({ at: entry.muteFrom, kind: "mute", id: null, why: `the mute mark (${entry.muteFrom}): a gap can't cover it — the cut never plays a second inside a gap` }); for (const m of marksAt(entry)) { const id = typeof m.id === "string" && m.id ? m.id : null; marks.push({ at: m.at, kind: id ? "mark" : "stamp", id, why: `${id ? `the mark ${id}'s second` : "the stamp's second"} (${m.at}): a gap can't cover it — move it first, or cut around it`, }); } return { span, whose, zones, marks }; } /** * A clip beat's GAPS (lane/reel-bench): source seconds cut out of its middle, * so two moments of one clip play as one beat of jump cuts -- the same shape * and the same rule as a clip's gaps (gaps.mjs): each `{ from, to }` at least * GAP_LIMITS.min long, in order, inside the beat with at least GAP_LIMITS.keep * seconds kept before, between and after them, at most GAP_LIMITS.max. * Returned sorted, each edge at 2 dp; absent or [] is none. Dependency-free, * like the rest of this module: the reel's walk checks a gap with it before it * is sent, and trailer.mjs (beatGaps) refuses with it. * * @param {{ start: number, end: number, gaps?: unknown }} b * @param {string} where * @returns {Array<{ from: number, to: number }>} */ export function beatGapsOf(b, where = "beat") { const v = b?.gaps; if (v === undefined || v === null) return []; if (!Array.isArray(v)) throw new Error(`${where}: gaps is a list of { from, to } in source seconds`); if (v.length > GAP_LIMITS.max) throw new Error(`${where}: at most ${GAP_LIMITS.max} gaps in one beat (it has ${v.length})`); const r2 = (n) => Number(Number(n).toFixed(2)); const list = v.map((g, k) => { if (!g || typeof g !== "object" || !Number.isFinite(g.from) || !Number.isFinite(g.to)) throw new Error(`${where}: gaps[${k}] must be { from, to } in source seconds`); if (g.to - g.from < GAP_LIMITS.min - 1e-6) throw new Error(`${where}: the gap ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); return { from: r2(g.from), to: r2(g.to) }; }).sort((x, y) => x.from - y.from); let before = b.start; list.forEach((g, k) => { if (g.from - before < GAP_LIMITS.keep - WIN_EPS) { throw new Error( g.from < before ? `${where}: the gap ${g.from}–${g.to} ${k ? "overlaps the gap before it — merge them" : `starts before the beat (${b.start})`}` : `${where}: the gap ${g.from}–${g.to} leaves ${Math.max(0, g.from - before).toFixed(2)} s after ${k ? "the gap before it" : "the beat's start"}; keep at least ${GAP_LIMITS.keep} s`, ); } before = g.to; }); if (list.length && b.end - before < GAP_LIMITS.keep - WIN_EPS) { const g = list[list.length - 1]; throw new Error( g.to > b.end ? `${where}: the gap ${g.from}–${g.to} runs past the beat's end (${b.end})` : `${where}: the gap ${g.from}–${g.to} leaves ${Math.max(0, b.end - before).toFixed(2)} s before the beat's end; keep at least ${GAP_LIMITS.keep} s`, ); } return list; } /** Every clip's gaps in the timeline, checked: the build refuses with these before it fetches. */ export function validateGapEntries(manifest) { const errors = []; (manifest?.timeline ?? []).forEach((e, i) => { errors.push(...validateGaps(e, `timeline[${i}] (${e?.id ?? "?"})`)); }); return errors; } /** * A list of gaps as the writer stores it: each edge at 2 dp, sorted by its * start. Not validated (validateGaps on the entry is). * * @param {Array<{ from: number, to: number }>} list */ export function normalizeGaps(list) { const r2 = (n) => Number(Number(n).toFixed(2)); return (list ?? []) .map((g) => ({ from: r2(g.from), to: r2(g.to), ...gapOwnKeys(g) })) .sort((a, b) => a.from - b.from || a.to - b.to); } /** * The gaps that fall in [from, to], clipped to it: what a segment cut from * `from` to `to` actually leaves out. A gap the snapped edge has moved past * is dropped; one it cuts into is clipped. * * @param {Array<{ from: number, to: number }>} gaps * @param {number} from * @param {number} to */ export function gapsWithin(gaps, from, to) { const out = []; for (const g of gaps ?? []) { const a = Math.max(g.from, from); const b = Math.min(g.to, to); if (b - a > EPS) out.push({ from: a, to: b }); } return out; } /** How many seconds of [from, to] the gaps take out. */ export function gapSeconds(gaps, from = -Infinity, to = Infinity) { let s = 0; for (const g of gaps ?? []) { const a = Math.max(g.from, from); const b = Math.min(g.to, to); if (b > a) s += b - a; } return s; } /** The seconds [from, to] plays with its gaps taken out (`to - from` without any). */ export function gappedLength(from, to, gaps) { return gaps?.length ? Math.max(0, to - from - gapSeconds(gaps, from, to)) : to - from; } /** * Source second `src` on the gapped clock of a segment whose picture starts * at source second `from`: the seconds that PLAY between them. A second * inside a gap lands on the join. Without gaps, `src - from`. * * @param {number} src * @param {number} from * @param {Array<{ from: number, to: number }> | null | undefined} gaps */ export function offsetIn(src, from, gaps) { if (!gaps?.length) return src - from; return src - from - gapSeconds(gaps, from, Math.max(from, src)); } /** * The inverse: the source second that plays `off` seconds into a segment * whose picture starts at source second `from`. A join shows the material * after its gap. Without gaps, `from + off`. * * @param {number} off * @param {number} from * @param {Array<{ from: number, to: number }> | null | undefined} gaps */ export function sourceAtOffset(off, from, gaps) { if (!gaps?.length) return from + off; let s = from + off; for (const g of gaps) { if (g.to <= from) continue; const a = Math.max(g.from, from); if (s >= a - EPS) s += g.to - a; else break; } return s; } /** * The pieces of [from, to] that play, in order (the whole span without gaps). * * @param {number} from * @param {number} to * @param {Array<{ from: number, to: number }> | null | undefined} gaps * @returns {Array<{ from: number, to: number }>} */ export function keptSpans(from, to, gaps) { if (!gaps?.length) return [{ from, to }]; const out = []; let at = from; for (const g of gapsWithin(gaps, from, to)) { if (g.from - at > EPS) out.push({ from: at, to: g.from }); at = Math.max(at, g.to); } if (to - at > EPS) out.push({ from: at, to }); return out; } /** Padded pieces closer than this are fetched as one span: a minute more of one window is cheaper than another paced fetch. */ export const FETCH_JOIN_UNDER = 60; /** * The spans a clip's source is FETCHED over: each kept piece of [from, to] * (keptSpans) padded `before` / `after` at its own outer edges, and padded * pieces less than `joinUnder` seconds apart joined into one. A clip without * gaps -- or whose gaps are short -- is one span, its padded extent, as it * always was; a gap-joined clip spanning hours (two moments of one stream) * is one span per moment, never the hours between. * * @param {number} from * @param {number} to * @param {Array<{ from: number, to: number }> | null | undefined} gaps the gaps a render applies (renderGaps) * @param {{ before?: number, after?: number, joinUnder?: number }} [pad] * @returns {Array<{ from: number, to: number }>} */ export function fetchPieces(from, to, gaps, { before = 0, after = 0, joinUnder = FETCH_JOIN_UNDER } = {}) { const out = []; for (const p of keptSpans(from, to, gaps)) { const span = { from: Math.max(0, p.from - before), to: p.to + after }; const last = out[out.length - 1]; if (last && span.from - last.to < joinUnder) last.to = Math.max(last.to, span.to); else out.push(span); } return out; } /** * A segment's gaps on its OWN clock, for the encode: each gap's edges in * seconds from the segment's first frame (`segStart`, source seconds), put on * the render's frame grid -- so the picture's trim and the sound's cut the * same instants and every piece is whole frames -- and clipped into the * segment's `seconds`. A gap that rounds to nothing is dropped; two that * round to touching are one. (One that reaches a snapped edge -- the writer * keeps GAP_LIMITS.keep from the cut's, and no edge snaps across a gap -- * simply ends or starts the segment's footage there.) * * @param {Array<{ from: number, to: number }>} gaps source seconds * @param {number} segStart source second of the segment's first frame * @param {number} seconds the segment's length before the gaps * @param {number} fps * @returns {Array<{ from: number, to: number }>} */ export function gapsOnSegment(gaps, segStart, seconds, fps) { const f = fps > 0 ? fps : 30; const frame = (t) => Math.round(t * f) / f; const out = []; for (const g of gaps ?? []) { const a = frame(Math.max(0, g.from - segStart)); const b = frame(Math.min(seconds, g.to - segStart)); if (b - a < 1 / f - EPS) continue; const last = out[out.length - 1]; if (last && a - last.to < 1 / f - EPS) { last.to = Number(Math.max(last.to, b).toFixed(6)); continue; } out.push({ from: Number(a.toFixed(6)), to: Number(b.toFixed(6)) }); } // Nothing left to play is not a segment: the gaps do not apply. return gapSeconds(out) >= seconds - 1 / f + EPS ? [] : out; } const n3 = (v) => Number(v.toFixed(6)).toString(); /** * The filtergraph that takes a segment's gaps out (`gaps` on its own clock, * gapsOnSegment's): the picture trimmed into its kept pieces and joined with * hard cuts, the sound cut at the same instants with a GAP_FADE out and in at * each join, so nothing clicks. Picture and sound come out the same length -- * the kept seconds -- and every later filter reads `v` / `a` in place of the * input's streams. Either input may be null (a clip with no picture: the * poster stands in; no sound: none). Empty `parts` without gaps. * * @param {{ gaps: Array<{ from: number, to: number }>, seconds: number, vIn?: string | null, aIn?: string | null, * vOut?: string, aOut?: string, fade?: number, tag?: string }} o * `tag` goes into the filter's own labels, so two of them sit in one graph (a trailer's runs) * @returns {{ parts: string[], v: string | null, a: string | null }} */ export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vOut = "[gv]", aOut = "[ga]", fade = GAP_FADE, tag = "" }) { if (!gaps?.length) return { parts: [], v: vIn, a: aIn }; const pieces = keptSpans(0, seconds, gaps); const K = pieces.length; const parts = []; if (vIn) { const outs = pieces.map((_, k) => `[g${tag}vs${k}]`); parts.push(`${vIn}split=${K}${outs.join("")}`); pieces.forEach((p, k) => { parts.push(`${outs[k]}trim=start=${n3(p.from)}:end=${n3(p.to)},setpts=PTS-STARTPTS[g${tag}vp${k}]`); }); parts.push(`${pieces.map((_, k) => `[g${tag}vp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); } if (aIn) { const outs = pieces.map((_, k) => `[g${tag}as${k}]`); parts.push(`${aIn}asplit=${K}${outs.join("")}`); pieces.forEach((p, k) => { const len = p.to - p.from; const d = Math.min(fade, len / 2); const f = [`atrim=start=${n3(p.from)}:end=${n3(p.to)}`, "asetpts=PTS-STARTPTS"]; // Only at a join: the segment's own edges are the crossfade's and room's. if (k > 0) f.push(`afade=t=in:st=0:d=${n3(d)}`); if (k < K - 1) f.push(`afade=t=out:st=${n3(Math.max(0, len - d))}:d=${n3(d)}`); parts.push(`${outs[k]}${f.join(",")}[g${tag}ap${k}]`); }); parts.push(`${pieces.map((_, k) => `[g${tag}ap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); } return { parts, v: vIn ? vOut : null, a: aIn ? aOut : null }; } /** * The gaps of a clip that a cut record (`.cut.json`) says its segment * left out -- source seconds -- or [] (none, or a record from before gaps). */ export function recordGaps(record) { const g = record?.gaps; if (!Array.isArray(g)) return []; return g.filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from); } /** * 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, 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 * move). Returns the new list, normalized; the caller validates it on the * entry. * * @param {Array<{ from: number, to: number }>} gaps the clip's now * @param {{ add?: { from: number, to: number }, remove?: number, set?: Array<{ from: number, to: number }>, * edit?: { at: number, mark?: boolean | null, why?: string | null, reason?: string | null, corner?: string | null } }} op * @param {{ tolerance?: number }} [opts] */ export function editGaps(gaps, op, { tolerance = 0.05 } = {}) { if (op.set !== undefined) return normalizeGaps(op.set); let list = [...(gaps ?? [])].sort((a, b) => a.from - b.from); 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 -- 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, ...mergedOwnKeys(absorbed) }]; } if (op.remove !== undefined) { const t = Number(op.remove); if (!fin(t)) throw new Error(`which gap? a source second inside it (got ${op.remove})`); const k = list.findIndex((g) => t >= g.from - tolerance && t <= g.to + tolerance); if (k < 0) throw new Error(`no gap at ${t}${list.length ? ` (gaps: ${list.map((g) => `${g.from}–${g.to}`).join(", ")})` : " — the clip has none"}`); list = list.filter((_, i) => i !== k); } if (op.edit !== undefined) { const t = Number(op.edit?.at); if (!fin(t)) throw new Error(`which gap? a source second inside it (got ${op.edit?.at})`); const k = list.findIndex((g) => t >= g.from - tolerance && t <= g.to + tolerance); if (k < 0) throw new Error(`no gap at ${t}${list.length ? ` (gaps: ${list.map((g) => `${g.from}–${g.to}`).join(", ")})` : " — the clip has none"}`); const next = { ...list[k] }; for (const key of ["mark", "why", "reason", "corner"]) { if (!(key in op.edit)) continue; const v = op.edit[key]; if (v === null || v === undefined || (key === "reason" && typeof v === "string" && !v.trim())) delete next[key]; else if (key === "mark" && typeof v !== "boolean") throw new Error(`a gap's mark is on, off or default (got ${JSON.stringify(v)})`); else if (key === "why" && !GAP_WHY_VALUES.includes(v)) throw new Error(`a gap's why is ${GAP_WHY_VALUES.join(", ")} or default (got ${JSON.stringify(v)})`); else if (key === "reason" && !reasonOk(v)) throw new Error(`a gap's reason is ${REASON_RULE} (got ${JSON.stringify(v)})`); else if (key === "corner" && !GAP_CORNER_VALUES.includes(v)) throw new Error(`a gap's corner is ${GAP_CORNER_VALUES.join(", ")} or default (got ${JSON.stringify(v)})`); else next[key] = key === "reason" ? v.trim() : v; } list = list.map((g, i) => (i === k ? next : g)); } return normalizeGaps(list); } /** * What gaps merged into one keep of their own settings (gapOwnKeys), by the rule a mark that joins them says * (common gapCue.mjs gapOwnSays): `why` and `reason` only when every one of them gives the same, `corner` the first * (in source order) that names one, `mark` on when any is on -- off only when every one is off. None merged: none. * * @param {Array>} 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+)?)$/); if (!m) return null; const from = Number(m[1]); const to = Number(m[2]); return fin(from) && fin(to) && to > from ? { from, to } : null; } /** A clip's gaps in words, for a listing: `−12.30–15.10, −20.00–20.50` ("" without any). */ export function gapsText(entry) { return gapsOf(entry).map((g) => `−${g.from.toFixed(2)}–${g.to.toFixed(2)}`).join(", "); }