Archilyzer · Source

archilyzer

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

commit c07d665d3a3dcd99329b2439e4f6610157052700
parent 58eb2ff8cdc84df934f0e0aed7772696da5a4fb3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 00:54:59 -0500

Merge lane/umtool-debt: trailer beats end and start in pauses (report-to-video/pauses.mjs, clip-words.mjs; bounded by the master's crossfades and joins and 1 s, each move a note, --no-snap) with gap-aware source labels; YouTube chapters from the deck's top-level markers (youtube.mjs markerChapters, out/youtube.txt and export --format chapters [--first], replacing the hand script); variants --list's master is the build itself; the subtitle dedupe compares titles by titleKey

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/bin/umtool.mjs | 10+++++++---
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 5++++-
Mumtool/docs/report-video.md | 33++++++++++++++++++++++++++++++---
Mumtool/lib/report/benchZoom.mjs | 18++++++------------
Aumtool/lib/report/export-chapters.test.mjs | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/export.mjs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/knobs.test.mjs | 21+++++++++++++++++++++
Mumtool/lib/report/sentenceEdges.mjs | 8++++----
Mumtool/lib/report/trailerCli.mjs | 11++++++++---
Mumtool/lib/report/variantsView.mjs | 4+++-
Mumtool/report-to-video/build-video.mjs | 20++++++++++++++++++--
Aumtool/report-to-video/clip-words.mjs | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 20+++++++++++++++++---
Aumtool/report-to-video/fixtures/ember-draft-24-chapters.json | 23+++++++++++++++++++++++
Aumtool/report-to-video/fixtures/ember-draft-24-trailer.json | 881+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/pauses.mjs | 241+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/pauses.test.mjs | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/rail-sections.test.mjs | 18+++++++++++++++++-
Aumtool/report-to-video/trailer-snap.test.mjs | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/trailer.mjs | 153++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/youtube.mjs | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/youtube.test.mjs | 52+++++++++++++++++++++++++++++++++++++++++++++++++++-
24 files changed, 2176 insertions(+), 57 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -54,7 +54,7 @@ // move clips/ and every share-*/, then set the switch // umtool snapshot <project> [--label L] copy the manifest into revisions/ // umtool diff <project> <snapshot> what changed since that snapshot -// umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] +// umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE] // umtool export <project> <clip> [--raw] [--take T] [--open] [--json] one clip, clean, into // <project>/exports/: the cut's edges, gaps out, mute (--raw: the whole fetched window) // umtool check-sources [<project>…] prints the re-check chain @@ -698,10 +698,14 @@ async function cmdExport() { if (!format && positional[1]) return cmdExportClip(p, positional[1]); if (!format) die(`--format is one of ${EXPORT_FORMATS.join(", ")} — or name a clip: umtool export ${p.id} <clip> [--raw] [--open]`); try { - const r = await exportProject(p.dir, format, val("--variant") ? { variant: val("--variant") } : {}); + const r = await exportProject(p.dir, format, { + ...(val("--variant") ? { variant: val("--variant") } : {}), + ...(val("--first") ? { first: val("--first") } : {}), + }); if (json) return out(r); process.stdout.write(r.text); if (r.offsets.note) console.error(`# ${r.offsets.note}`); + for (const n of r.notes ?? []) console.error(`# ${n}`); } catch (e) { die(e?.message ?? String(e)); } @@ -852,7 +856,7 @@ function usage() { " out/ to the media root (UMTOOL_MEDIA_DIR) and back; run when nothing is building", " umtool snapshot <project> [--label L] copy the manifest into revisions/", " umtool diff <project> <snapshot> what changed since that snapshot", - " umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V]", + " umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]", " umtool export <project> <clip> [--raw] [--take T] [--open] one clip, clean, into <project>/exports/:", " the cut's edges, its gaps out, its mute; --raw the whole fetched window; --open shows it", " umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)", diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -44,7 +44,7 @@ Inbox cannot disagree about what is wrong with one. | `storage deliverables <project> --to media\|local [--dry-run] [--json]` | `clips/` and every `share-*/` to the media root and back, then `storage.deliverables` in the manifest; refused while a build step, a cut or a share batch (by `--project` id, name or directory, as the app starts them) or the report's own scripts run in the project — a hand-run command that is none of these is not seen; **exit 1** on any failure (the switch is then left as it was) | | `snapshot <project> [--label L]` | copy the manifest into `revisions/` | | `diff <project> <snapshot>` | added / removed / moved / window / retyped, by entry id | -| `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V]` | the posting artifacts, from the build's chapter offsets | +| `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V] [--first TITLE]` | the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00 | | `check-sources [<project>…]` | **prints** the re-check chain; with no args, the never-checked and >30 d projects | | `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass | | `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) | @@ -57,7 +57,7 @@ Inbox cannot disagree about what is wrong with one. | `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | | `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) | | `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-delete)) | -| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) | +| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) | | `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off` · `candidates [--add]` | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips ([knobs.md](knobs.md#the-trailers-beats)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -536,7 +536,10 @@ default; Instagram 1:30, a Short 3:00, TikTok 10:00, or seconds) with the traile longer in the cut, and whether the beats are in the cut's order. A beat is `{id, start, end, label?}` (source seconds of a clip) or `{at, dur}` (master seconds), numbered from 1 as `umtool trailer` numbers them. The file keeps its shape (an array, until a setting makes it `{limit, xfade, intro, beats}`, which `--beats` reads too) and its -indent; one that does not parse is never written over; a write over a newer file is a 409. +indent; one that does not parse is never written over; a write over a newer file is a 409. The lengths are the beats as +written: `umtool trailer` then moves each clip beat's edges into the nearest pauses (up to 1 s each way, said per +edge; `--no-snap` keeps them), so a trailer can come out a few tenths of a second per beat longer than the running +length here ([report-video.md](report-video.md#trailer-from-the-master)). | | In umtool | From a terminal | Route | |---|---|---|---| diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1309,7 +1309,7 @@ its log says so, rather than refused as emptied. ### Trailer from the master `umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) [--intro] [--finale S] -[--xfade 0.3] [--out NAME] [--dry-run] [--json]` cuts a trailer out of a finished take's master +[--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` cuts a trailer out of a finished take's master (`takes/<t>/out/<slug>.mp4`). The trailer is the master's own frames, so the deck's rail, dates, pips and running tallies show the whole video's timeline, and a viewer can see the full version has more. Nothing is rendered again: it is one ffmpeg pass over the finished file. @@ -1327,12 +1327,30 @@ A beat is either: A clip beat is mapped with the take's build records. `out/sourced/schedule.json` gives the segment's start in the cut. `out/sourced/segments/<id>.cut.json` gives the source second the segment really starts at (snapped to a silence, room included). Source second *s* plays at master -second `segment.start + (s − cut.start)`. `--intro` opens on the master's brand intro. +second `segment.start + (s − cut.start)`, less the clip's gaps before it; the source seconds the +plan and the record print count the gaps too (`gaps.mjs` sourceAtOffset). `--intro` opens on the master's brand intro. `--finale S` closes on the master's last *S* seconds, where the finale's timeline is. - **The master's own crossfades.** Each join of the master is a `render.transition`-second dissolve. If a beat's edge falls inside one, the edge is moved in, but only until the trailer's own crossfade hides what is left. Each moved edge is printed as a note. +- **Edges into pauses.** The trailer's crossfade overlaps a beat's last `--xfade` seconds with + the next beat's first, so an edge just after a word starts fades the word out, and one before a + sentence's last word cuts it. Each clip beat's END moves forward into the next pause, far enough + that the fade is in the quiet (`pause.from + xfade`, or the pause's end when it is shorter, never + past the next word's start). When the recording's words are known and a sentence ends (. ? !) + within 1 s of the edge, the end goes through that sentence first. Each START moves back into + the pause before it (`pause.to − xfade`). A hard cut (`--xfade 0`, or the trailer's first start + and last end) wants 0.1 s of quiet. The pauses are the master's silences over the segment (the + build's `detectSilence`, the take's `render.silenceMinDur`/`silenceRelDb`) and the gaps between + timed words. The words come from `clip-words.mjs`: the corpus's `words.json`, else a whisper + `transcript.json`, else the caption track's `<c>` word starts; never a cue spread by its + characters. An edge never moves more than 1 s (`SNAP_MAX_SHIFT`, `pauses.mjs`), past the + master's crossfades, the cut record's end, a gap's join, or into the piece next to it in the + master. Each move is a note naming the word, e.g. `beat 8 tr3: end 3011.20 → 3012.09 (pause + after "type.", the sentence's end)`. So is an edge left where it was because its pause is too + far. `--no-snap` keeps the edges as written. A raw beat, the intro and the finale are never + moved. The record keeps each move (`snapped`) and whether snapping was on (`snap`). - **Seamless runs.** If a piece starts inside the piece before it, or where it ends, the two are one run of the master with no crossfade, and no frame plays twice. This happens with the intro and a first beat in the first clip, and with a last beat and the finale. @@ -2199,7 +2217,16 @@ variant with anything on disk). All derived from the manifest plus the build's offsets — `out/<variant>/chapters.ffmeta` when present, else `segmentOffsets()` over the segments, else a refusal with the reason. `toc-bbcode` reproduces the hand-made `toc.bbcode.txt` shape; `description` adds the source list; `chapters` -is YouTube's form and includes cards. Cite URLs follow the QR's rule. A cut +is YouTube's form and includes cards. **A cut whose deck has markers** gets its +SECTIONS as chapters instead, in `chapters` and in the build's `out/youtube.txt` +alike (youtube.mjs `markerChapters`): each top-level marker (a `level: 2` +subsection is left out) at the second the segment after its clip starts in +the master (the deck's `schedule.json`), the opening titled +`deck.sectionTitle.first` (or `--first TITLE`; with neither, the first section +takes 0:00), then YouTube's rules — 0:00 first, each at least 10 s, at least +three — with what had to be merged printed on stderr (`# …`). A cut that opens +on the brand intro reads the build's folded intro chapter back (the intro and +the clip after it both at 0). Cite URLs follow the QR's rule. A cut with a narrated card (`narration`, below) ends its `description` and `chapters` with the editor's disclosure line, `Narration: synthetic voice (Kokoro-82M · af_heart)`. diff --git a/umtool/lib/report/benchZoom.mjs b/umtool/lib/report/benchZoom.mjs @@ -10,6 +10,8 @@ // cached window (what the waveform shows at fit -- today's view); `vis` the // stretch of it shown now. +import { pausePoints } from "umtool-report-to-video/pauses"; + /** The closest the waveform zooms: a quarter of a second across its width. */ export const MIN_ZOOM_SPAN = 0.25; /** One step of + / − (and of a wheel notch, scaled by its delta). */ @@ -99,22 +101,14 @@ export function tickLabel(t, step) { /** * The gaps between words, as places an edge or a gap's edge can go: for each * pause between consecutive words (or cues), its middle; and every measured - * silence's middle. Sorted, deduplicated within 20 ms. In [from, to]. + * silence's middle. Sorted, deduplicated within 20 ms. In [from, to]. The + * pause arithmetic is report-to-video/pauses.mjs's (pausePoints), the one the + * trailer lands its crossfades by. * * @param {{ words?: Array<{ start: number, end: number }> | null, silences?: Array<{ from: number, to: number }> | null }} o * @param {number} from * @param {number} to */ export function quietPoints({ words = null, silences = null }, from, to) { - const pts = []; - const ws = (words ?? []).filter((w) => fin(w.start) && fin(w.end)).sort((a, b) => a.start - b.start); - for (let i = 1; i < ws.length; i += 1) { - if (ws[i].start >= ws[i - 1].end) pts.push((ws[i - 1].end + ws[i].start) / 2); - } - for (const s of silences ?? []) if (fin(s.from) && fin(s.to)) pts.push((s.from + s.to) / 2); - const out = []; - for (const p of pts.filter((x) => x >= from && x <= to).sort((a, b) => a - b)) { - if (!out.length || p - out[out.length - 1] > 0.02) out.push(round4(p)); - } - return out; + return pausePoints({ words, silences }, from, to); } diff --git a/umtool/lib/report/export-chapters.test.mjs b/umtool/lib/report/export-chapters.test.mjs @@ -0,0 +1,87 @@ +// `umtool export --format chapters` on a cut whose deck has markers: its +// top-level sections at the second each one's first segment starts (the deck +// schedule's), YouTube's rules kept, what was merged said -- the hand +// script's rows for Ember draft-24 (report-to-video/fixtures). A deck without +// markers lists every entry, as it always did. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { exportProject } from "./export.mjs"; + +const EMBER = JSON.parse(readFileSync(new URL("../../report-to-video/fixtures/ember-draft-24-chapters.json", import.meta.url), "utf8")); + +const FFMETA = (n) => + [";FFMETADATA1", "", ...Array.from({ length: n }, (_, i) => ["[CHAPTER]", "TIMEBASE=1/1000", `START=${i * 5000}`, `END=${(i + 1) * 5000}`, `title=Entry ${i + 1}`, ""]).flat()].join("\n"); + +/** A built cut: the fixture's segments as its timeline (the brand intro is the schedule's own), its deck's markers. */ +function project(root, deck) { + const dir = path.join(root, `p-${Math.random().toString(36).slice(2)}`); + mkdirSync(path.join(dir, "out", "sourced"), { recursive: true }); + const timeline = EMBER.segments.slice(1).map(([id], i) => ({ id, type: "clip", video: `v${i}`, start: 0, end: 5 })); + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({ + slug: "s", title: "A cut", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { fps: 30, transition: EMBER.transition, chrome: { engine: "hyperframes", layout: "deck", deck } }, timeline, + })); + writeFileSync(path.join(dir, "out", "sourced", "chapters.ffmeta"), FFMETA(timeline.length)); + writeFileSync(path.join(dir, "out", "sourced", "schedule.json"), JSON.stringify({ + version: 1, kind: "deck", fps: 30, transition: EMBER.transition, total: EMBER.total, + segments: EMBER.segments.map(([id, start]) => ({ id, start })), + })); + return dir; +} + +test("chapters from the deck's markers: Ember draft-24's 13 rows, the opening titled by --first or deck.sectionTitle.first", async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "umtool-export-chapters-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const dir = project(root, { markers: EMBER.markers }); + const r = await exportProject(dir, "chapters", { first: EMBER.first }); + assert.deepEqual(r.text.trimEnd().split("\n"), EMBER.expected); + assert.deepEqual(r.notes, []); + // The deck's own first section's title does the same. + const titled = project(root, { markers: EMBER.markers, sectionTitle: { first: EMBER.first } }); + assert.deepEqual((await exportProject(titled, "chapters")).text.trimEnd().split("\n"), EMBER.expected); + // None: the first section takes 0:00, and the note says so. + const bare = await exportProject(dir, "chapters"); + assert.deepEqual(bare.text.trimEnd().split("\n"), ["0:00 Sex appeal", ...EMBER.expected.slice(2)]); + assert.match(bare.notes.join("\n"), /the opening has no title/); +}); + +test("chapters: subsections left out; a deck without markers lists every entry as before", async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "umtool-export-chapters-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const subs = project(root, { markers: [...EMBER.markers, { after: "tj1", label: "A subsection", level: 2 }] }); + const r = await exportProject(subs, "chapters", { first: EMBER.first }); + assert.deepEqual(r.text.trimEnd().split("\n"), EMBER.expected); + const plain = project(root, {}); + const lines = (await exportProject(plain, "chapters")).text.trimEnd().split("\n"); + assert.equal(lines.length, EMBER.segments.length - 1); + assert.match(lines[0], /^00:00 /); +}); + +test("a cut that opens on the brand intro: the build folded its chapter into the next, and the export reads it so (no 'different cut' refusal)", async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "umtool-export-chapters-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const dir = path.join(root, "intro"); + mkdirSync(path.join(dir, "out", "sourced"), { recursive: true }); + const timeline = [{ id: "brand-intro", type: "intro" }, ...[1, 2, 3].map((i) => ({ id: `c${i}`, type: "clip", video: `v${i}`, start: 0, end: 5 }))]; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "s", title: "A cut", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, render: { fps: 30 }, timeline })); + writeFileSync(path.join(dir, "out", "sourced", "chapters.ffmeta"), FFMETA(3)); // 0, 5, 10: c1 (with the intro), c2, c3 + const lines = (await exportProject(dir, "chapters")).text.trimEnd().split("\n"); + assert.deepEqual(lines.map((l) => l.slice(0, 5)), ["00:00", "00:00", "00:05", "00:10"]); + // One chapter short of the entries WITHOUT an intro is still another cut. + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "s", title: "A cut", render: { fps: 30 }, timeline: timeline.slice(1).concat({ id: "c4", type: "clip", video: "v4", start: 0, end: 5 }) })); + await assert.rejects(exportProject(dir, "chapters"), /describes a different cut/); +}); + +test("chapterMarkersOf: the deck's markers, and the opening's title only from a sectionTitle object", async () => { + const { chapterMarkersOf } = await import("umtool-report-to-video/build-video"); + const deck = (d) => ({ render: { chrome: { deck: d } } }); + assert.deepEqual(chapterMarkersOf(deck({ markers: EMBER.markers, sectionTitle: { first: "Open" } })), { markers: EMBER.markers, first: "Open" }); + assert.deepEqual(chapterMarkersOf(deck({ markers: EMBER.markers, sectionTitle: false })), { markers: EMBER.markers, first: null }); + assert.deepEqual(chapterMarkersOf({}), { markers: null, first: null }); +}); diff --git a/umtool/lib/report/export.mjs b/umtool/lib/report/export.mjs @@ -16,10 +16,11 @@ // Plain ESM, so `umtool export` runs from a terminal. import { readFile, readdir, stat } from "node:fs/promises"; import path from "node:path"; -import { DEFAULT_VARIANT, selectVariant, segmentOffsets } from "umtool-report-to-video/build-video"; +import { DEFAULT_VARIANT, chapterMarkersOf, selectVariant, segmentOffsets } from "umtool-report-to-video/build-video"; import { citeUrlFor, channelFor, readAvailability, readManifest } from "../projects/report.mjs"; import { teaserTitle } from "umtool-report-to-video/deck"; import { narrationDir, readCutDisclosure } from "umtool-report-to-video/narration-store"; +import { chapterLines, hasChapterMarkers, markerChapters } from "umtool-report-to-video/youtube"; import { outDirState } from "./storage.mjs"; export const EXPORT_FORMATS = ["toc-bbcode", "toc-markdown", "description", "chapters"]; @@ -69,7 +70,8 @@ const titleOf = (e, i) => /** * Deliverable-second offsets for every entry of the chosen variant. - * @returns {Promise<{ starts: number[], source: "ffmeta"|"schedule"|"segments", file: string, note?: string } | { error: string }>} + * `total` is the cut's length when the source says it. + * @returns {Promise<{ starts: number[], total?: number, source: "ffmeta"|"schedule"|"segments", file: string, note?: string } | { error: string }>} */ export async function chapterOffsets(dir, manifest, variant) { const entries = manifest.timeline ?? []; @@ -85,7 +87,13 @@ export async function chapterOffsets(dir, manifest, variant) { for (const file of ffmetaCandidates) { const text = await readFile(file, "utf8").catch(() => null); if (text === null) continue; - const chapters = parseFfmeta(text); + let chapters = parseFfmeta(text); + // The brand intro has no chapter of its own: the build folds it into the + // one after it (build-video foldIntroChapter), which starts at 0. It is + // read back the same way -- the intro and the entry after it both at 0. + if (entries[0]?.type === "intro" && entries.length > 1 && chapters.length === entries.length - 1) { + chapters = [{ start: 0, end: chapters[0]?.start ?? 0, title: "" }, ...chapters]; + } if (chapters.length !== entries.length) { return { error: @@ -93,7 +101,8 @@ export async function chapterOffsets(dir, manifest, variant) { "it describes a different cut; rebuild (a chapters-only build is enough)", }; } - return { starts: chapters.map((c) => c.start), source: "ffmeta", file }; + const end = chapters.at(-1)?.end; + return { starts: chapters.map((c) => c.start), ...(Number.isFinite(end) ? { total: end } : {}), source: "ffmeta", file }; } // No ffmeta, but a deck schedule for this cut: its starts are the cut's own, @@ -105,6 +114,7 @@ export async function chapterOffsets(dir, manifest, variant) { const D = sched.transition ?? 0; return { starts: sched.segments.map((x, i) => (i === 0 ? 0 : x.start + D)), + ...(Number.isFinite(sched.total) ? { total: sched.total } : {}), source: "schedule", file: path.join(outDir, variant, "schedule.json"), note: "no chapters.ffmeta; offsets from the deck's schedule.json", @@ -122,10 +132,11 @@ export async function chapterOffsets(dir, manifest, variant) { } const render = manifest.render ?? {}; const D = render.transition ?? 0.5; - const { starts } = await segmentOffsets(entries.map((e) => path.join(segDir, `${e.id}.mp4`)), D, render.fps); + const { starts, total } = await segmentOffsets(entries.map((e) => path.join(segDir, `${e.id}.mp4`)), D, render.fps); // Land just past the crossfade, as muxChapters does. return { starts: starts.map((s, i) => (i === 0 ? 0 : s + D)), + ...(Number.isFinite(total) ? { total } : {}), source: "segments", file: segDir, note: `no chapters.ffmeta; offsets computed from the segments assuming a ${D}s crossfade — a hard-cut build would be earlier by that much per entry`, @@ -137,10 +148,12 @@ export async function chapterOffsets(dir, manifest, variant) { /** * @param {string} dir * @param {string} format one of EXPORT_FORMATS - * @param {{ variant?: string }} [opts] - * @returns {Promise<{ text: string, format: string, variant: string, offsets: { source: string, file: string, note?: string } }>} + * `first` (chapters): the opening's title, over the deck's `sectionTitle.first`. + * + * @param {{ variant?: string, first?: string | null }} [opts] + * @returns {Promise<{ text: string, format: string, variant: string, offsets: { source: string, file: string, note?: string }, notes: string[] }>} */ -export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = {}) { +export async function exportProject(dir, format, { variant = DEFAULT_VARIANT, first = null } = {}) { if (!EXPORT_FORMATS.includes(format)) throw new Error(`format must be one of ${EXPORT_FORMATS.join(", ")}`); const whole = await readManifest(dir); if (!whole) throw new Error("no manifest"); @@ -162,7 +175,14 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = const disclosure = await readCutDisclosure(narrationDir(path.join(dir, "out")), m, "\n"); let text; - if (format === "toc-bbcode") { + /** @type {string[]} */ + const notes = []; + // A deck with markers: the chapters are its sections (youtube.mjs + // markerChapters), placed by the deck schedule's segment starts. + const chaptersFromMarkers = format === "chapters" ? await deckChapters(dir, m, variant, off, first, notes) : null; + if (chaptersFromMarkers) { + text = chapterLines(chaptersFromMarkers).join("\n") + "\n" + (disclosure ? `\n${disclosure}\n` : ""); + } else if (format === "toc-bbcode") { text = [ `[b]${m.title}${m.subtitle ? ` — ${m.subtitle}` : ""}[/b]`, "", @@ -207,7 +227,36 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = ...(disclosure ? [disclosure, ""] : []), ].join("\n"); } - return { text, format, variant, offsets: { source: off.source, file: off.file, ...(off.note ? { note: off.note } : {}) } }; + return { text, format, variant, offsets: { source: off.source, file: off.file, ...(off.note ? { note: off.note } : {}) }, notes }; +} + +/** + * The chapters a cut's deck markers make (youtube.mjs markerChapters), or + * null when the deck has none (the entries are listed as before) or too few + * survive YouTube's rules (said in `notes`). Placed by the deck's + * `out/<variant>/schedule.json` -- each section where its first segment + * starts, as the hand script placed them -- else by the export's offsets. + * + * @param {string} dir + * @param {any} m the variant's manifest + * @param {string} variant + * @param {{ starts: number[], total?: number }} off + * @param {string | null} first + * @param {string[]} notes + */ +async function deckChapters(dir, m, variant, off, first, notes) { + const { markers, first: deckFirst } = chapterMarkersOf(m); + if (!hasChapterMarkers(markers)) return null; + const sched = await readFile(path.join(dir, "out", variant, "schedule.json"), "utf8").then((t) => JSON.parse(t), () => null); + const fromSchedule = sched?.kind === "deck" && Array.isArray(sched.segments) && sched.segments.every((x) => typeof x?.id === "string" && Number.isFinite(x?.start)); + const segments = fromSchedule + ? sched.segments.map((x) => ({ id: x.id, start: x.start })) + : (m.timeline ?? []).map((e, i) => ({ id: e.id, start: off.starts[i] })); + const total = fromSchedule && Number.isFinite(sched.total) ? sched.total : off.total ?? null; + const r = markerChapters({ markers, segments, total, first: first ?? deckFirst }); + notes.push(...r.notes); + if (!r.chapters) notes.push("the deck's markers make no chapter list YouTube takes: every entry is listed instead"); + return r.chapters; } /** Which variants have anything on disk to export from, for the UI's row. */ diff --git a/umtool/lib/report/knobs.test.mjs b/umtool/lib/report/knobs.test.mjs @@ -245,6 +245,27 @@ test("variantsState: the build, the variants made, the sync report with the lags await assert.rejects(variantsState({ id: "p", dir }, await read(dir), "../x"), /not a take id/); }); +test("variantsState: the `master` item is the build itself (<slug>.mp4), never a <slug>.master.mp4", async () => { + const dir = await project(); + const out = path.join(dir, "out"); + await mkdir(out, { recursive: true }); + await writeFile(path.join(out, "t.mp4"), "m".repeat(120)); + await writeFile(path.join(out, "t.720p.mp4"), "x".repeat(40)); + await writeFile(path.join(out, "variants.json"), JSON.stringify({ + at: new Date(Date.now() + 5000).toISOString(), source: path.join(out, "t.mp4"), + items: [ + { name: "master", path: path.join(out, "t.mp4"), width: 1920, height: 1080, bytes: 120, kbps: 1919 }, + { name: "720p", path: path.join(out, "t.720p.mp4"), width: 1280, height: 720, bytes: 40, kbps: 899 }, + ], + })); + let s = await variantsState({ id: "p", dir }, await read(dir)); + assert.deepEqual(s.made.items.map((i) => [i.name, i.exists, i.bytes]), [["master", true, 120], ["720p", true, 40]]); + // The build gone: the master is gone with it. + await rm(path.join(out, "t.mp4")); + s = await variantsState({ id: "p", dir }, await read(dir)); + assert.deepEqual(s.made.items.map((i) => [i.name, i.exists]), [["master", false], ["720p", true]]); +}); + test("variantsState on a take: its out/<slug>.mp4, else its finished preview.mp4 (the encoder pointed at it)", async () => { const dir = await project(); const takeDir = path.join(dir, "takes", "final"); diff --git a/umtool/lib/report/sentenceEdges.mjs b/umtool/lib/report/sentenceEdges.mjs @@ -24,6 +24,8 @@ // // Pure: no DOM, no React. Absolute source seconds throughout, like the bench. +import { endsSentence as textEndsSentence } from "umtool-report-to-video/pauses"; + /** A pause this long between two cues is a sentence boundary, punctuation or not. */ export const SENTENCE_GAP = 1.5; @@ -33,11 +35,9 @@ export const SNAP_RADIUS = 0.6; /** Two boundaries closer than this are one (a cue's end and the next one's start). */ const SAME = 0.05; -const TERMINAL = /[.?!]["')\]”’]*\s*$/; - -/** Does this text close a sentence by its punctuation? */ +/** Does this text close a sentence by its punctuation? (report-to-video/pauses.mjs endsSentence: one rule.) */ export function endsWithTerminal(text) { - return TERMINAL.test(String(text ?? "")); + return textEndsSentence(text); } const fin = (v) => typeof v === "number" && Number.isFinite(v); diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -3,7 +3,7 @@ // report-to-video/trailer.mjs; this is the command line around it. // // umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) -// [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json] +// [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json] // umtool trailer <project> --candidates [--json] the walk's ★ clips as beats import { readFile } from "node:fs/promises"; import path from "node:path"; @@ -23,13 +23,16 @@ import { export const TRAILER_USAGE = [ "usage: umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON)", - ` [--intro] [--finale S] [--xfade ${TRAILER_XFADE_DEFAULT}] [--out NAME] [--dry-run] [--json]`, + ` [--intro] [--finale S] [--xfade ${TRAILER_XFADE_DEFAULT}] [--no-snap] [--out NAME] [--dry-run] [--json]`, "", "A trailer cut from the take's finished master (takes/<t>/out/<slug>.mp4): spans of the master's own", "frames, so the deck's rail, dates and tallies show the whole video's timeline. Nothing is rendered again.", "A beat is { \"id\": \"<clip>\", \"start\": <source s>, \"end\": <source s> } (mapped to the master by the", "take's build records) or { \"at\": <master s>, \"dur\": <s> }. --intro opens on the master's brand intro;", "--finale S closes on its last S seconds. Joined with S-second crossfades (--xfade 0: hard cuts),", + "each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s)", + "and its start back into the one before, so the crossfade lands in quiet -- the master's silences and the", + "recording's words; never past the segment's own clip, each move said (--no-snap: the edges as written).", "encoded with the take's render settings, in the heavy slot. Writes takes/<t>/out/<slug>.trailer.mp4", "(--out NAME: that name there; a path: exactly there) and <name>.trailer.json beside it, what was cut.", "--dry-run prints the mapping and writes nothing.", @@ -52,7 +55,7 @@ function parse(args) { if (valued.has(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); flags[a] = args[++i]; - } else if (["--intro", "--json", "--dry-run", "--help", "--candidates"].includes(a)) flags[a] = ""; + } else if (["--intro", "--json", "--dry-run", "--help", "--candidates", "--no-snap"].includes(a)) flags[a] = ""; else throw new CliError(`unknown flag ${a}`); } else positional.push(a); } @@ -150,6 +153,8 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c xfade: seconds(p, "--xfade", TRAILER_XFADE_DEFAULT), out: p.flags["--out"] ?? null, dryRun: p.has("--dry-run"), + snap: !p.has("--no-snap"), + ...(deps.measure ? { measure: deps.measure } : {}), ...(deps.run ? { run: deps.run } : {}), ...(deps.probe ? { probe: deps.probe } : {}), slot: (fn) => { diff --git a/umtool/lib/report/variantsView.mjs b/umtool/lib/report/variantsView.mjs @@ -107,7 +107,9 @@ export async function variantsState(project, manifest, take = null) { if (isObj(doc) && Array.isArray(doc.items)) { for (const it of doc.items) { if (!isObj(it) || typeof it.name !== "string" || !VARIANT_NAME_RE.test(it.name)) continue; - const f = await fileInfo(path.join(outDir, `${slug}.${it.name}.mp4`)); + // The `master` variant is the build itself (`<slug>.mp4`, or a take's + // preview), not a `<slug>.master.mp4`: it is there when the build is. + const f = it.name === "master" ? built : await fileInfo(path.join(outDir, `${slug}.${it.name}.mp4`)); items.push({ name: it.name, width: fin(it.width) ? it.width : null, diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -5672,7 +5672,9 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, const title = await chapterTitle(entries[i], i, provenance, { deck }); // `section`: the entry opens one of the cut's sections (a card) -- what // out/youtube.txt's Chapters keep (youtube.mjs youtubeChapters). - all.push({ start, end, title, section: entries[i]?.type === "card" }); + // `id` and `cutStart` (where its segment starts, before the crossfade): + // what the deck's markers place their chapters by (youtube.mjs markerChapters). + all.push({ start, end, title, section: entries[i]?.type === "card", id: entries[i]?.id, cutStart: starts[i] }); } const chapters = foldIntroChapter(all, entries); for (const c of chapters) { @@ -5738,7 +5740,9 @@ async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why await writeSocialText(manifest, outRoot); const youtube = manifest.publish?.youtube; if (!youtube?.title) return null; - const { chapters, note } = muxed ? youtubeChapters(muxed.chapters, muxed.total) : { chapters: null, note: `no chapters: ${why ?? "the cut is one segment"}` }; + const { chapters, note } = muxed + ? youtubeChapters(muxed.chapters, muxed.total, chapterMarkersOf(manifest)) + : { chapters: null, note: `no chapters: ${why ?? "the cut is one segment"}` }; const text = composeYoutubeText({ youtube, chapters, sources: youtubeSources(entries, manifest.provenance) }); const file = path.join(outRoot, youtubeTextName(variant)); await writeFile(file, text, "utf8"); @@ -5747,6 +5751,18 @@ async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why } /** + * What a cut's YouTube chapters are placed by when its deck has markers + * (youtube.mjs markerChapters): the markers, and the opening's title + * (`deck.sectionTitle.first`, when the section title is set as an object). + */ +export function chapterMarkersOf(manifest) { + const deck = manifest?.render?.chrome?.deck; + const st = deck?.sectionTitle; + const first = st && typeof st === "object" && typeof st.first === "string" ? st.first : null; + return { markers: Array.isArray(deck?.markers) ? deck.markers : null, first }; +} + +/** * The hard-cut concat's list, as written. Absolute: the concat demuxer resolves * a relative entry against the LIST's directory, so a relative `--out` named * every segment twice over and the hard-cut concat failed to open its first diff --git a/umtool/report-to-video/clip-words.mjs b/umtool/report-to-video/clip-words.mjs @@ -0,0 +1,114 @@ +// A CLIP'S WORDS, for where its edges may go (pauses.mjs; 2026-11-02). +// +// What the trailer (and the clip editor's pause snap) reads to know where a +// recording's words start and what they say, in SOURCE seconds, from the +// corpus beside the recording -- the first of: +// +// data/<id>/words.json the word-timings sidecar (common +// wordTimings-server.ts): timed words +// data/<id>/transcript.json a whisper transcript's tokens (montage.mjs +// whisperWords): timed words +// the English caption track YouTube's en-orig `<c>` word timings (the +// cue record's `vttFile`, else transcript.en-orig.vtt, +// else transcript.en.vtt): each word's START only +// +// Never a cue spread by its characters (fx.mjs fxWordsOf): those places are +// made up, and a pause read off them is not a pause. A clip from a file beside +// the manifest, a recording the corpus does not hold, or one with none of the +// three: null -- the caller goes by the silences alone. +// +// Reads only. Plain ESM. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { hasLocalMedia } from "./local-media.mjs"; +import { whisperWords } from "./montage.mjs"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** `hh:mm:ss.mmm` (or `mm:ss.mmm`) as seconds. */ +function clockSeconds(s) { + const parts = String(s).split(":").map(Number); + return parts.reduce((acc, n) => acc * 60 + n, 0); +} + +const ENTITIES = { "&nbsp;": " ", "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&#39;": "'", "&apos;": "'" }; +const decode = (s) => String(s).replace(/&(?:nbsp|amp|lt|gt|quot|apos|#39);/g, (m) => ENTITIES[m] ?? m); + +/** + * A word-timed caption track's words: `{ start, text }` for each word YouTube + * timed with `<hh:mm:ss.mmm><c> word</c>` (the first on a line at its cue's + * start). The rolling track repeats each line without its tags: those are + * skipped, as is a word timed twice. Empty for a track without word timing. + * + * @param {string} vtt + * @returns {Array<{ start: number, text: string }>} + */ +export function vttWordStarts(vtt) { + const seen = new Set(); + const out = []; + let cueStart = null; + const push = (start, text) => { + const t = decode(text).replace(/\s+/g, " ").trim(); + if (!t || !fin(start)) return; + const key = `${start.toFixed(3)}|${t}`; + if (seen.has(key)) return; + seen.add(key); + out.push({ start, text: t }); + }; + for (const line of String(vtt ?? "").split(/\r?\n/)) { + const head = line.match(/^((?:\d+:)?\d{2}:\d{2}\.\d{3})\s+-->\s+/); + if (head) { + cueStart = clockSeconds(head[1]); + continue; + } + if (!line.includes("<c>") || cueStart === null) continue; + push(cueStart, line.split("<")[0]); + for (const m of line.matchAll(/<((?:\d+:)?\d{2}:\d{2}\.\d{3})><c>([^<]*)<\/c>/g)) push(clockSeconds(m[1]), m[2]); + } + return out.sort((a, b) => a.start - b.start); +} + +/** + * The clip's recording's words in [from, to] (source seconds), and where they + * came from: `{ words, timed, from }`, or null (see the header). + * + * @param {{ channel?: string, video?: string, src?: string }} entry + * @param {{ channelSlug?: string } | null | undefined} provenance + * @param {number} from + * @param {number} to + * @param {{ channelsDir: string | null }} o + * @returns {Promise<{ words: Array<{ start: number, end?: number, text: string }>, timed: boolean, from: "words.json" | "transcript.json" | "captions" } | null>} + */ +export async function clipWords(entry, provenance, from, to, { channelsDir }) { + if (!channelsDir || !entry?.video || hasLocalMedia(entry)) return null; + const slug = entry.channel ?? provenance?.channelSlug; + if (!slug) return null; + const dir = await resolveVideoDir(channelsDir, slug, entry.video).catch(() => null); + if (!dir) return null; + const json = (name) => readFile(path.join(dir, name), "utf8").then((t) => JSON.parse(t), () => null); + const inSpan = (w) => w.start >= from && w.start <= to; + + const sidecar = await json("words.json"); + if (Array.isArray(sidecar?.words) && sidecar.words.length) { + const words = sidecar.words + .map((w) => ({ start: Number(w?.start), end: Number(w?.end), text: String(w?.w ?? w?.word ?? w?.text ?? "") })) + .filter((w) => fin(w.start) && fin(w.end) && inSpan(w)); + if (words.length) return { words, timed: true, from: "words.json" }; + } + const whisper = await json("transcript.json"); + const ww = whisper ? whisperWords(whisper, from, to) : null; + if (ww?.length) { + const words = ww.map((w) => ({ start: w.start, end: w.end, text: w.text })).filter(inSpan); + if (words.length) return { words, timed: true, from: "transcript.json" }; + } + const cues = await json("transcript.cues.json"); + const names = [...new Set([typeof cues?.vttFile === "string" ? path.basename(cues.vttFile) : null, "transcript.en-orig.vtt", "transcript.en.vtt"].filter(Boolean))]; + for (const name of names) { + const text = await readFile(path.join(dir, name), "utf8").catch(() => null); + if (!text) continue; + const words = vttWordStarts(text).filter(inSpan); + if (words.length) return { words, timed: false, from: "captions" }; + } + return null; +} diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -1005,8 +1005,22 @@ export function hidesDeck(entry, deck) { return deck.overCards === "hide" && CARD_TYPES.includes(entry.type); } -/** Two titles the same, but for case and the space around them. */ -const sameTitle = (a, b) => String(a ?? "").trim().toLowerCase() === String(b ?? "").trim().toLowerCase(); +/** + * A title as two titles are compared: punctuation, symbols (a "||", a "$"), + * quotes and emoji gone, space collapsed, case folded -- so "…SBI?!? || Gothic + * Therapy react" and the source's "…SBI? || Gothic Therapy react" are one title. + */ +export function titleKey(s) { + return String(s ?? "") + .normalize("NFKC") + .replace(/[\p{P}\p{S}\p{Extended_Pictographic}\u200d\ufe0e\ufe0f]/gu, " ") + .replace(/\s+/g, " ") + .trim() + .toLowerCase(); +} + +/** Two titles the same, but for case, punctuation, quotes, emoji and space (titleKey). */ +const sameTitle = (a, b) => titleKey(a) === titleKey(b); /** * The deck's title and subtitle for one entry. Pure: the caller resolves `meta`. @@ -1030,7 +1044,7 @@ export function deckText(entry, meta, provenance, deck, multiChannel) { // Two lines already name the source: an on-screen title that only // repeats it is not drawn again over them (the block takes the // title's band, as for a clip with none). A different one stands. - if (subtitleLines && title && sameTitle(title, parts.title) && subtitleLines.some((l) => l.includes(String(parts.title).trim()))) title = ""; + if (subtitleLines && title && sameTitle(title, parts.title) && titleKey(parts.title) && subtitleLines.some((l) => titleKey(l).includes(titleKey(parts.title)))) title = ""; } else if (entry.type === "teaser") { // The deck is never up over a teaser; its words are what a table of // the cut (umtool's On-screen rows, the schedule) names it by. diff --git a/umtool/report-to-video/fixtures/ember-draft-24-chapters.json b/umtool/report-to-video/fixtures/ember-draft-24-chapters.json @@ -0,0 +1,23 @@ +{ + "about": "The minimum of EmberParadox 'in her own words' take draft-24 that its chapters are made from: each deck marker's clip and the segment after it, where each starts in the master (out/sourced/schedule.json), the master's length, and the 13 rows the hand script (night1030 chapters.py) printed for it, its opening title as that script supplied it.", + "total": 1790, + "transition": 0.4, + "segments": [["brand-intro", 0], ["v01t", 163.333], ["ow2", 176.1], ["g01", 290], ["gn1", 299.333], ["d01", 312.833], ["rf1", 324.867], ["mk1", 360.567], ["tj1", 377.9], ["lj2", 562.9], ["n02", 588], ["p02", 681.9], ["ts1", 693.1], ["tr6", 860.233], ["fn4", 877.567], ["fn1", 925.7], ["r01", 935.967], ["u01", 1090.1], ["x01", 1109.733], ["ws1", 1258.633], ["sr1a", 1272.167], ["ks2", 1542.4], ["bk1", 1570.3], ["bk3", 1641.333], ["ho3", 1684.067]], + "markers": [{"after": "v01t", "label": "Sex appeal", "color": "#e070d0"}, {"after": "g01", "label": "Not a character", "color": "#f2a65a"}, {"after": "d01", "label": "Leaves it open", "color": "#ffc861"}, {"after": "mk1", "label": "Why does it matter?", "color": "#c4a1ff"}, {"after": "lj2", "label": "Why the voice changer", "color": "#6fc3ff"}, {"after": "p02", "label": "On trans issues", "color": "#7fdc9a"}, {"after": "tr6", "label": "On Finnster", "color": "#5fd1c9"}, {"after": "fn1", "label": "26–28 October", "color": "#ff7a59"}, {"after": "u01", "label": "After the reveal", "color": "#f78fb3"}, {"after": "ws1", "label": "Kirsche, Side Scrollers", "color": "#a3e635"}, {"after": "ks2", "label": "Her books", "color": "#e8d9b0"}, {"after": "bk3", "label": "The book, read aloud", "color": "#9fb3c8"}], + "first": "As an anime girl, as a woman", + "expected": [ + "0:00 As an anime girl, as a woman", + "2:56 Sex appeal", + "4:59 Not a character", + "5:24 Leaves it open", + "6:17 Why does it matter?", + "9:48 Why the voice changer", + "11:33 On trans issues", + "14:37 On Finnster", + "15:35 26–28 October", + "18:29 After the reveal", + "21:12 Kirsche, Side Scrollers", + "26:10 Her books", + "28:04 The book, read aloud" + ] +} diff --git a/umtool/report-to-video/fixtures/ember-draft-24-trailer.json b/umtool/report-to-video/fixtures/ember-draft-24-trailer.json @@ -0,0 +1,881 @@ +{ + "about": "The minimum of EmberParadox 'in her own words' take draft-24 that the trailer's edge snapping is tested on: the beats as they were before the operator's hand fix (night1101 trailer-beats.pre-words.json), each clip's segment in the master (out/sourced/schedule.json, transition 0.4, 30 fps), its cut record (segments/<id>.cut.json), the master's silences within 2.5 s of each beat edge (cut-points.mjs detectSilence with the take's render settings, master seconds), and the caption words near each edge (clip-words.mjs: YouTube's en-orig word starts, source seconds; none for a recording transcribed without them).", + "fps": 30, + "transition": 0.4, + "total": 1790, + "order": [ + "b01", + "c01", + "tr3", + "u01", + "kr1", + "bk3" + ], + "beats": [ + { + "id": "b01", + "start": 1816.29, + "end": 1818.65 + }, + { + "id": "c01", + "start": 216.6, + "end": 220.95 + }, + { + "id": "tr3", + "start": 2988.36, + "end": 3011.2 + }, + { + "id": "u01", + "start": 9476.7, + "end": 9484.95 + }, + { + "id": "kr1", + "start": 4814.95, + "end": 4818.1 + }, + { + "id": "bk3", + "start": 119, + "end": 123.3 + }, + { + "id": "tr3", + "start": 3011.95, + "end": 3017.63 + } + ], + "clips": { + "b01": { + "segment": { + "id": "b01", + "type": "clip", + "start": 25.9, + "end": 34.6 + }, + "record": { + "start": 1815.979, + "end": 1824.65 + }, + "silences": [ + { + "s": 25.9, + "e": 26.35 + }, + { + "s": 27.02, + "e": 27.166 + }, + { + "s": 27.465, + "e": 27.628 + }, + { + "s": 27.828, + "e": 27.933 + }, + { + "s": 28.07, + "e": 28.165 + }, + { + "s": 28.528, + "e": 28.631 + }, + { + "s": 28.755, + "e": 28.9 + }, + { + "s": 28.981, + "e": 29.102 + }, + { + "s": 29.326, + "e": 29.465 + }, + { + "s": 29.671, + "e": 30.091 + }, + { + "s": 30.968, + "e": 31.061 + } + ], + "words": [ + { + "start": 1816.48, + "text": "Men" + }, + { + "start": 1816.799, + "text": "only." + }, + { + "start": 1817.279, + "text": "Okay." + }, + { + "start": 1817.679, + "text": "Well," + }, + { + "start": 1817.919, + "text": "I'm" + }, + { + "start": 1818.24, + "text": "not" + }, + { + "start": 1818.399, + "text": "a" + }, + { + "start": 1818.559, + "text": "man." + }, + { + "start": 1818.72, + "text": "So," + }, + { + "start": 1818.96, + "text": "I'm" + }, + { + "start": 1819.12, + "text": "curious" + }, + { + "start": 1819.36, + "text": "what" + }, + { + "start": 1819.52, + "text": "the" + }, + { + "start": 1819.6, + "text": "question" + }, + { + "start": 1819.76, + "text": "is." + }, + { + "start": 1820.159, + "text": "How" + }, + { + "start": 1820.32, + "text": "much" + }, + { + "start": 1820.399, + "text": "of" + }, + { + "start": 1820.559, + "text": "the" + }, + { + "start": 1820.72, + "text": "domestic" + } + ], + "timed": false, + "wordsFrom": "captions" + }, + "c01": { + "segment": { + "id": "c01", + "type": "clip", + "start": 600.633, + "end": 607.4 + }, + "record": { + "start": 216.588, + "end": 223.329 + }, + "silences": [ + { + "s": 600.633, + "e": 600.793 + }, + { + "s": 601.287, + "e": 601.412 + }, + { + "s": 602.579, + "e": 602.843 + }, + { + "s": 602.909, + "e": 603.008 + }, + { + "s": 603.539, + "e": 603.644 + }, + { + "s": 604.047, + "e": 604.152 + }, + { + "s": 604.684, + "e": 604.801 + }, + { + "s": 604.919, + "e": 605.243 + }, + { + "s": 605.345, + "e": 605.452 + }, + { + "s": 606.136, + "e": 606.255 + }, + { + "s": 606.64, + "e": 606.733 + }, + { + "s": 606.824, + "e": 607.364 + } + ], + "words": [ + { + "start": 216.07999999999998, + "text": "It" + }, + { + "start": 216.4, + "text": "is." + }, + { + "start": 216.72, + "text": "And" + }, + { + "start": 216.959, + "text": "yes," + }, + { + "start": 217.28, + "text": "I" + }, + { + "start": 217.519, + "text": "use" + }, + { + "start": 217.76, + "text": "a" + }, + { + "start": 217.92000000000002, + "text": "voice" + }, + { + "start": 218.239, + "text": "changer." + }, + { + "start": 218.799, + "text": "If" + }, + { + "start": 218.959, + "text": "you" + }, + { + "start": 219.12, + "text": "don't" + }, + { + "start": 219.2, + "text": "like" + }, + { + "start": 219.36, + "text": "it," + }, + { + "start": 219.599, + "text": "you" + }, + { + "start": 219.68, + "text": "know" + }, + { + "start": 219.84, + "text": "where" + }, + { + "start": 220, + "text": "the" + }, + { + "start": 220.159, + "text": "[ __ ]" + }, + { + "start": 220.4, + "text": "door" + }, + { + "start": 220.64, + "text": "is." + }, + { + "start": 221.12, + "text": "Stop" + }, + { + "start": 221.36, + "text": "giving" + }, + { + "start": 221.519, + "text": "me" + }, + { + "start": 221.68, + "text": "[ __ ]" + }, + { + "start": 221.92000000000002, + "text": "about" + }, + { + "start": 222, + "text": "it," + }, + { + "start": 222.239, + "text": "please." + }, + { + "start": 222.56, + "text": "Thank" + }, + { + "start": 222.72, + "text": "you." + } + ], + "timed": false, + "wordsFrom": "captions" + }, + "kr1": { + "segment": { + "id": "kr1", + "type": "clip", + "start": 1409.567, + "end": 1423.133 + }, + "record": { + "start": 4814.643, + "end": 4828.15 + }, + "silences": [ + { + "s": 1409.567, + "e": 1410.017 + }, + { + "s": 1412.903, + "e": 1413.277 + }, + { + "s": 1414.047, + "e": 1414.167 + } + ], + "words": [ + { + "start": 4813.864, + "text": "This" + }, + { + "start": 4814.065, + "text": "is" + }, + { + "start": 4814.985, + "text": "This" + }, + { + "start": 4815.144, + "text": "is" + }, + { + "start": 4815.264, + "text": "a" + }, + { + "start": 4815.344, + "text": "man" + }, + { + "start": 4815.704, + "text": "who" + }, + { + "start": 4815.864, + "text": "lied" + }, + { + "start": 4816.184, + "text": "to" + }, + { + "start": 4816.304, + "text": "everyone" + }, + { + "start": 4816.864, + "text": "about" + }, + { + "start": 4817.184, + "text": "being" + }, + { + "start": 4817.425, + "text": "a" + }, + { + "start": 4817.505, + "text": "woman." + }, + { + "start": 4818.224, + "text": "When" + }, + { + "start": 4818.425, + "text": "he" + }, + { + "start": 4818.545, + "text": "was" + }, + { + "start": 4818.784, + "text": "asked" + }, + { + "start": 4819.144, + "text": "about" + }, + { + "start": 4819.344, + "text": "his" + }, + { + "start": 4819.505, + "text": "voice" + }, + { + "start": 4819.824, + "text": "changer," + }, + { + "start": 4820.224, + "text": "he" + }, + { + "start": 4820.344, + "text": "would" + }, + { + "start": 4820.505, + "text": "do" + } + ], + "timed": false, + "wordsFrom": "captions" + }, + "tr3": { + "segment": { + "id": "tr3", + "type": "clip", + "start": 742.567, + "end": 772.6 + }, + "record": { + "start": 2987.989, + "end": 3017.995 + }, + "silences": [ + { + "s": 742.567, + "e": 743.017 + }, + { + "s": 743.258, + "e": 743.544 + }, + { + "s": 743.687, + "e": 743.789 + }, + { + "s": 744.92, + "e": 745.346 + }, + { + "s": 763.326, + "e": 763.942 + }, + { + "s": 764.481, + "e": 764.859 + }, + { + "s": 765.482, + "e": 766.021 + }, + { + "s": 766.379, + "e": 766.84 + }, + { + "s": 767.624, + "e": 767.97 + }, + { + "s": 768.771, + "e": 768.963 + }, + { + "s": 769.732, + "e": 770.359 + }, + { + "s": 771.816, + "e": 771.925 + }, + { + "s": 772.022, + "e": 772.6 + } + ], + "words": [ + { + "start": 2988.36, + "text": "So," + }, + { + "start": 2988.84, + "text": "actual" + }, + { + "start": 2989.44, + "text": "trans" + }, + { + "start": 2989.88, + "text": "people," + }, + { + "start": 2990.64, + "text": "I've" + }, + { + "start": 3009.28, + "text": "every" + }, + { + "start": 3010.24, + "text": "[ __ ]" + }, + { + "start": 3011.4, + "text": "type." + }, + { + "start": 3012.16, + "text": "You" + }, + { + "start": 3012.32, + "text": "don't" + }, + { + "start": 3012.6, + "text": "like" + }, + { + "start": 3012.84, + "text": "it?" + }, + { + "start": 3013.44, + "text": "[ __ ]" + }, + { + "start": 3014.2, + "text": "deal" + }, + { + "start": 3015.68, + "text": "Autogynephiliac" + }, + { + "start": 3018.08, + "text": "[ __ ]" + } + ], + "timed": false, + "wordsFrom": "captions" + }, + "u01": { + "segment": { + "id": "u01", + "type": "clip", + "start": 1090.1, + "end": 1110.133 + }, + "record": { + "start": 9443.54, + "end": 9485.32, + "gaps": [ + { + "from": 9451.607, + "to": 9452.607 + }, + { + "from": 9455.94, + "to": 9476.707 + } + ] + }, + "silences": [ + { + "s": 1098.569, + "e": 1099.235 + }, + { + "s": 1099.868, + "e": 1099.999 + }, + { + "s": 1100.882, + "e": 1101.067 + }, + { + "s": 1101.12, + "e": 1101.218 + }, + { + "s": 1101.317, + "e": 1101.608 + }, + { + "s": 1103.302, + "e": 1103.411 + }, + { + "s": 1103.764, + "e": 1103.855 + }, + { + "s": 1107.3, + "e": 1107.877 + }, + { + "s": 1108.257, + "e": 1108.362 + }, + { + "s": 1109.068, + "e": 1109.189 + }, + { + "s": 1109.384, + "e": 1109.477 + }, + { + "s": 1109.563, + "e": 1110.133 + } + ] + }, + "bk3": { + "segment": { + "id": "bk3", + "type": "clip", + "start": 1641.333, + "end": 1684.467 + }, + "record": { + "start": 77.558, + "end": 123.97, + "gaps": [ + { + "from": 96.992, + "to": 100.258 + } + ] + }, + "silences": [ + { + "s": 1676.554, + "e": 1677.02 + }, + { + "s": 1677.379, + "e": 1677.582 + }, + { + "s": 1677.836, + "e": 1677.937 + }, + { + "s": 1678.442, + "e": 1678.547 + }, + { + "s": 1678.711, + "e": 1678.825 + }, + { + "s": 1678.998, + "e": 1679.476 + }, + { + "s": 1680.069, + "e": 1680.193 + }, + { + "s": 1680.377, + "e": 1680.485 + }, + { + "s": 1681.497, + "e": 1682.065 + }, + { + "s": 1682.713, + "e": 1682.827 + }, + { + "s": 1683.279, + "e": 1683.499 + }, + { + "s": 1683.919, + "e": 1684.132 + }, + { + "s": 1684.141, + "e": 1684.251 + } + ], + "words": [ + { + "start": 116.72, + "text": "it's" + }, + { + "start": 117.28, + "text": "supposed" + }, + { + "start": 117.6, + "text": "to" + }, + { + "start": 117.84, + "text": "be" + }, + { + "start": 118, + "text": "horrifying." + }, + { + "start": 119.03999999999999, + "text": "It's" + }, + { + "start": 119.439, + "text": "not" + }, + { + "start": 119.84, + "text": "supposed" + }, + { + "start": 120.159, + "text": "to" + }, + { + "start": 120.399, + "text": "be" + }, + { + "start": 120.64, + "text": "sexy." + }, + { + "start": 121.6, + "text": "It's" + }, + { + "start": 121.92, + "text": "not" + }, + { + "start": 122.159, + "text": "supposed" + }, + { + "start": 122.479, + "text": "to" + }, + { + "start": 122.64, + "text": "be" + }, + { + "start": 122.719, + "text": "a" + }, + { + "start": 122.96, + "text": "fetish." + }, + { + "start": 124, + "text": "It's" + }, + { + "start": 124.399, + "text": "not" + }, + { + "start": 124.64, + "text": "supposed" + }, + { + "start": 124.96, + "text": "to" + } + ], + "timed": false, + "wordsFrom": "captions" + } + } +} diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -56,6 +56,7 @@ "./narration-review": "./narration-review.mjs", "./narration-store": "./narration-store.mjs", "./package.json": "./package.json", + "./pauses": "./pauses.mjs", "./post-links": "./post-links.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.mjs", diff --git a/umtool/report-to-video/pauses.mjs b/umtool/report-to-video/pauses.mjs @@ -0,0 +1,241 @@ +// THE PAUSES IN A STRETCH OF SPEECH, and an edge moved into one (2026-11-02). +// +// A cut that lands on a word is heard as a cut-off sentence; a crossfade that +// lands on one fades it out. This is the one place that says where the quiet +// is and where an edge goes in it, for every caller that moves an edge to a +// pause: the trailer (trailer.mjs, each beat's crossfade landed in silence), +// the bench waveform's marks between words (lib/report/benchZoom.mjs +// quietPoints) and the clip editor's "snap edge to the nearest pause". +// +// A PAUSE is a span `{ from, to }` (seconds, any clock -- the caller's) where +// nobody speaks: a measured silence (cut-points.mjs detectSilence, `{ s, e }`, +// or `{ from, to }`), or the gap between two TIMED words (a words file, a +// whisper transcript) at least PAUSE_MIN_GAP long. Overlapping ones merge. +// +// WORDS `{ start, end?, text }`: a timed word has an `end`; a caption's word +// (YouTube's en-orig `<c>` timings) has only its `start`. Both say where a +// word starts and what it says -- what decides that an edge finishes a +// sentence, and names the word an edge was moved past. Only timed words add +// pauses: a start-only word list has no gaps to read. +// +// AN EDGE INTO A PAUSE (snapEdge). `room` is how much quiet the edge wants on +// its own side: a crossfade's length (its fade runs over the beat's last +// `room` seconds, or its first), or SNAP_HARD_ROOM for a hard cut. +// +// end forward, into the first pause after the words it should finish, +// at `pause.from + room` (the whole fade in the quiet) or the pause's +// end when it is shorter -- never past the next word's start. When +// the words are known, the words it finishes are the one in progress +// at the edge, or -- when a sentence ends within `maxShift` of the +// edge (. ? !) -- through that sentence's last word. +// start back, into the last pause that starts before it, at `pause.to − +// room` (the whole fade-in in the quiet) or the pause's start. +// nearest the middle of the pause nearest the edge. +// +// Bounded: never more than `maxShift` (SNAP_MAX_SHIFT), never past `lo`/`hi` +// (the caller's span: a segment's, a clip's). An edge already where it should +// be does not move. What moved and why comes back to be said. +// +// PURE: no fs, no ffmpeg, no DOM -- the browser imports it (benchZoom.mjs). + +/** A gap between two timed words this long is a pause (seconds): the build's silencedetect minimum. */ +export const PAUSE_MIN_GAP = 0.09; +/** The furthest an edge is moved to reach a pause (seconds). */ +export const SNAP_MAX_SHIFT = 1; +/** The quiet a hard cut (no crossfade) wants on its side of the edge (seconds). */ +export const SNAP_HARD_ROOM = 0.1; +/** A word sounds for at least this long after its start (seconds): a pause that starts sooner is the one before it. */ +export const MIN_WORD = 0.1; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const round4 = (v) => Math.round(v * 10000) / 10000; + +const TERMINAL = /[.?!]["')\]”’]*\s*$/; + +/** Does this text close a sentence by its punctuation (. ? !, closing quotes or brackets allowed after)? */ +export function endsSentence(text) { + return TERMINAL.test(String(text ?? "")); +} + +/** A word list as `{ start, end?, text }`, finite starts only, in order. Accepts `w` / `word` for the text. */ +export function normWords(words) { + return (words ?? []) + .map((w) => ({ + start: Number(w?.start), + ...(fin(Number(w?.end)) && w?.end !== null && w?.end !== undefined ? { end: Number(w.end) } : {}), + text: String(w?.text ?? w?.w ?? w?.word ?? ""), + })) + .filter((w) => fin(w.start)) + .sort((a, b) => a.start - b.start); +} + +/** + * The gaps between consecutive TIMED words at least `minGap` long (0: every + * gap, a zero-width one where two words touch). Words without an end add none. + * + * @param {Array<{ start: number, end?: number }>} words + * @param {number} [minGap] + * @returns {Array<{ from: number, to: number }>} + */ +export function wordGaps(words, minGap = 0) { + const ws = (words ?? []).filter((w) => fin(w?.start) && fin(w?.end)).sort((a, b) => a.start - b.start); + const out = []; + for (let i = 1; i < ws.length; i += 1) { + const gap = ws[i].start - ws[i - 1].end; + if (gap >= 0 && gap >= minGap) out.push({ from: ws[i - 1].end, to: ws[i].start }); + } + return out; +} + +/** A silence as `{ from, to }`: detectSilence's `{ s, e }` or already `{ from, to }`; null when it is not one. */ +function spanOf(x) { + const from = fin(x?.from) ? x.from : fin(x?.s) ? x.s : null; + const to = fin(x?.to) ? x.to : fin(x?.e) ? x.e : null; + return from !== null && to !== null && to > from ? { from, to } : null; +} + +/** + * The pauses: measured silences and the gaps between timed words, merged + * where they overlap or touch, in order, those meeting [from, to]. + * + * @param {{ words?: Array<{ start: number, end?: number }> | null, silences?: Array<{ s?: number, e?: number, from?: number, to?: number }> | null }} o + * @param {{ from?: number, to?: number, minGap?: number }} [range] + * @returns {Array<{ from: number, to: number }>} + */ +export function pauseSpans({ words = null, silences = null }, { from = -Infinity, to = Infinity, minGap = PAUSE_MIN_GAP } = {}) { + const all = [...(silences ?? []).map(spanOf).filter(Boolean), ...wordGaps(words ?? [], minGap).filter((g) => g.to > g.from)] + .sort((a, b) => a.from - b.from); + const out = []; + for (const p of all) { + const last = out[out.length - 1]; + if (last && p.from <= last.to + 1e-6) last.to = Math.max(last.to, p.to); + else out.push({ ...p }); + } + return out.filter((p) => p.to >= from && p.from <= to).map((p) => ({ from: round4(p.from), to: round4(p.to) })); +} + +/** + * The places an edge or a gap's edge can go, as points: the middle of every + * pause between consecutive words (or cues; touching ones too) and of every + * measured silence. Sorted, deduplicated within 20 ms. In [from, to]. (The + * bench waveform's marks: benchZoom.mjs quietPoints.) + * + * @param {{ words?: Array<{ start: number, end: number }> | null, silences?: Array<{ from: number, to: number }> | null }} o + * @param {number} from + * @param {number} to + */ +export function pausePoints({ words = null, silences = null }, from, to) { + const pts = wordGaps(words ?? [], 0).map((g) => (g.from + g.to) / 2); + for (const s of silences ?? []) if (fin(s?.from) && fin(s?.to)) pts.push((s.from + s.to) / 2); + const out = []; + for (const p of pts.filter((x) => x >= from && x <= to).sort((a, b) => a - b)) { + if (!out.length || p - out[out.length - 1] > 0.02) out.push(round4(p)); + } + return out; +} + +/** + * @typedef {{ at: number, from: number, moved: boolean, side: "start" | "end" | "nearest", + * pause?: { from: number, to: number }, word?: string, sentence?: boolean, bounded?: boolean, + * reason?: "fits" | "none" | "far" | "bound" }} Snap + */ + +/** + * One edge moved into a pause (see the header). `at` is where it goes; with + * `moved` false it stays, and `reason` says why: "fits" (already in quiet + * enough), "none" (no pause on that side), "far" (the pause is more than + * `maxShift` away), "bound" (only past `lo`/`hi`). `word` names the word the + * edge now sits after (an end) or before (a start); `sentence` says an end + * was carried to a sentence's last word; `bounded` that it stopped at `lo`/`hi` + * inside the pause. + * + * @param {number} t the edge + * @param {"start" | "end" | "nearest"} side + * @param {{ pauses: Array<{ from: number, to: number }>, words?: Array<{ start: number, end?: number, text?: string }> | null, + * room?: number, maxShift?: number, lo?: number, hi?: number }} o + * @returns {Snap} + */ +export function snapEdge(t, side, { pauses, words = null, room = SNAP_HARD_ROOM, maxShift = SNAP_MAX_SHIFT, lo = -Infinity, hi = Infinity }) { + const ps = [...(pauses ?? [])].filter((p) => fin(p?.from) && fin(p?.to) && p.to > p.from).sort((a, b) => a.from - b.from); + const ws = normWords(words); + const stay = (reason, extra = {}) => ({ at: t, from: t, moved: false, side, reason, ...extra }); + if (side === "nearest") { + let best = null; + for (const p of ps) { + const mid = (p.from + p.to) / 2; + if (mid < lo - 1e-9 || mid > hi + 1e-9) continue; + if (!best || Math.abs(mid - t) < Math.abs(best.mid - t)) best = { p, mid }; + } + if (!best) return stay("none"); + if (t >= best.p.from && t <= best.p.to) return stay("fits", { pause: best.p }); + if (Math.abs(best.mid - t) > maxShift + 1e-9) return stay("far", { pause: best.p }); + return { at: round4(best.mid), from: t, moved: true, side, pause: best.p }; + } + + if (side === "end") { + // The words the edge finishes: the one in progress, or through a sentence + // that ends within maxShift. A pause that starts before that word has + // sounded (MIN_WORD) is the quiet before it, not after. + let after = -Infinity; + let sentence = false; + const k = lastIndex(ws, (w) => w.start < t - 1e-6); + if (k >= 0) { + let target = k; + if (!endsSentence(ws[k].text)) { + for (let j = k + 1; j < ws.length && ws[j].start <= t + maxShift; j += 1) { + if (endsSentence(ws[j].text)) { + target = j; + sentence = true; + break; + } + } + } + after = ws[target].start + MIN_WORD; + } + // Already in quiet enough -- the whole fade in one pause -- and no + // sentence to finish: it stays. + if (!sentence) { + const holds = ps.find((x) => x.from <= t - room + 1e-6 && x.to >= t - 1e-6); + if (holds) return stay("fits", { pause: holds, ...(lastWordBefore(ws, holds.from) ? { word: lastWordBefore(ws, holds.from) } : {}) }); + } + const p = ps.find((x) => x.to > t + 1e-6 && x.from >= after - 1e-6); + if (!p) return stay("none"); + const next = ws.find((w) => w.start > p.from + 1e-6); + const cap = Math.min(p.to, next ? next.start : Infinity); + const target = Math.max(t, Math.min(p.from + room, cap)); + const word = lastWordBefore(ws, p.from); + const said = { pause: p, ...(word ? { word } : {}), ...(sentence ? { sentence } : {}) }; + if (target - t <= 1e-3) return stay("fits", said); + if (target - t > maxShift + 1e-9) return stay("far", said); + if (target > hi + 1e-9) { + if (hi > t + 1e-3 && hi >= p.from - 1e-9) return { at: round4(hi), from: t, moved: true, side, ...said, bounded: true }; + return stay("bound", said); + } + return { at: round4(target), from: t, moved: true, side, ...said }; + } + + // start: back into the last pause that starts before it. + const i = lastIndex(ps, (x) => x.from < t - 1e-6); + if (i < 0) return stay("none"); + const p = ps[i]; + const target = Math.min(t, Math.max(p.to - room, p.from)); + const first = ws.find((w) => w.start >= p.from - 1e-6); + const said = { pause: p, ...(first ? { word: first.text } : {}) }; + if (t - target <= 1e-3) return stay("fits", said); + if (t - target > maxShift + 1e-9) return stay("far", said); + if (target < lo - 1e-9) { + if (lo < t - 1e-3 && lo <= p.to + 1e-9) return { at: round4(lo), from: t, moved: true, side, ...said, bounded: true }; + return stay("bound", said); + } + return { at: round4(target), from: t, moved: true, side, ...said }; +} + +function lastIndex(list, pred) { + for (let i = list.length - 1; i >= 0; i -= 1) if (pred(list[i])) return i; + return -1; +} + +function lastWordBefore(ws, t) { + const i = lastIndex(ws, (w) => w.start < t - 1e-6); + return i >= 0 ? ws[i].text : null; +} diff --git a/umtool/report-to-video/pauses.test.mjs b/umtool/report-to-video/pauses.test.mjs @@ -0,0 +1,123 @@ +// pauses.mjs: where the quiet is in a stretch of speech, and an edge moved +// into it -- forward for an end (through its sentence), back for a start, +// to the nearest for the clip editor; bounded, and said. +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + MIN_WORD, PAUSE_MIN_GAP, SNAP_HARD_ROOM, SNAP_MAX_SHIFT, endsSentence, normWords, pausePoints, pauseSpans, snapEdge, wordGaps, +} from "./pauses.mjs"; + +const close = (a, b, eps = 1e-3) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b}`); + +test("the constants: a pause is the build's silencedetect minimum, an edge moves at most a second", () => { + assert.equal(PAUSE_MIN_GAP, 0.09); + assert.equal(SNAP_MAX_SHIFT, 1); + assert.equal(SNAP_HARD_ROOM, 0.1); + assert.equal(MIN_WORD, 0.1); +}); + +test("endsSentence: . ? ! with closing quotes or brackets after; a comma does not", () => { + for (const t of ["man.", "it?", "stop!", 'said."', "end.)", "so.” "]) assert.ok(endsSentence(t), t); + for (const t of ["So,", "[ __ ]", "every", "", null]) assert.ok(!endsSentence(t), String(t)); +}); + +test("wordGaps: gaps between TIMED words at least minGap long; start-only words add none", () => { + const ws = [{ start: 0, end: 0.4 }, { start: 0.45, end: 0.9 }, { start: 1.3, end: 1.6 }, { start: 1.6, end: 2 }]; + assert.deepEqual(wordGaps(ws, PAUSE_MIN_GAP), [{ from: 0.9, to: 1.3 }]); + assert.equal(wordGaps(ws, 0).length, 3, "every gap, the touching one too"); + assert.deepEqual(wordGaps([{ start: 0 }, { start: 1 }], 0), []); +}); + +test("pauseSpans: silences ({s,e} or {from,to}) and word gaps, merged where they touch, in range", () => { + const p = pauseSpans({ + silences: [{ s: 5, e: 5.4 }, { from: 1, to: 1.2 }, { s: 5.3, e: 5.6 }, { s: 9, e: 8 }], + words: [{ start: 0, end: 1.1 }, { start: 1.5, end: 2 }, { start: 3, end: 3.5 }], + }); + assert.deepEqual(p, [{ from: 1, to: 1.5 }, { from: 2, to: 3 }, { from: 5, to: 5.6 }]); + assert.deepEqual(pauseSpans({ silences: [{ s: 1, e: 2 }, { s: 7, e: 8 }] }, { from: 3, to: 9 }), [{ from: 7, to: 8 }]); +}); + +test("pausePoints: the middle of every word gap (touching words too) and silence, deduplicated within 20 ms", () => { + const pts = pausePoints({ words: [{ start: 0, end: 1 }, { start: 1, end: 2 }, { start: 2.5, end: 3 }], silences: [{ from: 2.1, to: 2.4 }] }, 0, 10); + assert.deepEqual(pts, [1, 2.25]); +}); + +test("normWords: w / word / text, starts in order, an end only when there is one", () => { + assert.deepEqual(normWords([{ w: "b", start: 2, end: 2.3 }, { word: "a", start: 1 }, { text: "x", start: Number.NaN }]), [ + { start: 1, text: "a" }, { start: 2, end: 2.3, text: "b" }, + ]); +}); + +// The speech of the tests below: "... every [ __ ] type. You don't ..." -- +// a pause between "[ __ ]" and "type." and another after "type.". +const WORDS = [ + { start: 9.28, text: "every" }, { start: 10.24, text: "[ __ ]" }, { start: 11.4, text: "type." }, { start: 12.16, text: "You" }, { start: 12.32, text: "don't" }, +]; +const PAUSES = [{ from: 10.9, to: 11.44 }, { from: 11.8, to: 12.26 }]; + +test("an end is carried through its sentence when it ends within maxShift, into the pause after it, at from + room", () => { + const r = snapEdge(11.2, "end", { pauses: PAUSES, words: WORDS, room: 0.3 }); + assert.equal(r.moved, true); + // 11.8 + 0.3 = 12.1, under the pause's end and "You" (12.16). + close(r.at, 12.1); + assert.equal(r.word, "type."); + assert.equal(r.sentence, true); + // Without the words it is already in quiet: it stays. + const bare = snapEdge(11.2, "end", { pauses: PAUSES, room: 0.3 }); + assert.equal(bare.moved, false); + assert.equal(bare.reason, "fits"); +}); + +test("an end never passes the next word's start, nor the pause's end", () => { + // A pause shorter than the fade: the edge goes to its end. + const short = snapEdge(1.05, "end", { pauses: [{ from: 1.1, to: 1.25 }], words: [{ start: 0.6, text: "man." }, { start: 1.3, text: "So," }], room: 0.3 }); + close(short.at, 1.25); + // A word the captions start inside the pause: the edge stops there. + const capped = snapEdge(1.05, "end", { pauses: [{ from: 1.1, to: 1.6 }], words: [{ start: 0.6, text: "is." }, { start: 1.3, text: "Stop" }], room: 0.3 }); + close(capped.at, 1.3); +}); + +test("a pause that starts before the last word has sounded (MIN_WORD) is the quiet before it, not after", () => { + // "man." starts at 28.48; a dip at 28.53 is inside it, so the edge goes to the pause after "So,". + const r = snapEdge(28.57, "end", { + pauses: [{ from: 28.53, to: 28.63 }, { from: 28.76, to: 28.9 }], + words: [{ start: 28.48, text: "man." }, { start: 28.64, text: "So," }, { start: 28.88, text: "I'm" }], + room: 0.3, + }); + close(r.at, 28.88); + assert.equal(r.word, "So,"); +}); + +test("bounded: more than maxShift away stays (far); past hi stops at hi inside the pause, or stays (bound)", () => { + const far = snapEdge(10, "end", { pauses: [{ from: 11.2, to: 12 }], room: 0.3 }); + assert.deepEqual([far.moved, far.reason, far.at], [false, "far", 10]); + const held = snapEdge(10, "end", { pauses: [{ from: 10.2, to: 11 }], room: 0.3, hi: 10.35 }); + assert.deepEqual([held.moved, held.bounded, held.at], [true, true, 10.35]); + const bound = snapEdge(10, "end", { pauses: [{ from: 10.5, to: 11 }], room: 0.3, hi: 10.4 }); + assert.deepEqual([bound.moved, bound.reason], [false, "bound"]); + const none = snapEdge(10, "end", { pauses: [{ from: 8, to: 9 }], room: 0.3 }); + assert.equal(none.reason, "none"); +}); + +test("a start goes back into the last pause before it, at to − room, bounded by lo", () => { + const ps = [{ from: 6.4, to: 6.85 }]; + const r = snapEdge(6.78, "start", { pauses: ps, words: [{ start: 6.72, text: "I" }, { start: 7.04, text: "am" }], room: 0.3 }); + close(r.at, 6.55); + assert.equal(r.word, "I"); + // Room enough after it already: it stays. + assert.equal(snapEdge(6.5, "start", { pauses: ps, room: 0.3 }).reason, "fits"); + // lo: stops there inside the pause. + const lo = snapEdge(6.78, "start", { pauses: ps, room: 0.3, lo: 6.7 }); + assert.deepEqual([lo.at, lo.bounded], [6.7, true]); + assert.equal(snapEdge(6.78, "start", { pauses: [{ from: 5, to: 5.4 }], room: 0.3 }).reason, "far"); +}); + +test("nearest: the middle of the pause nearest the edge, within maxShift and the bounds (the clip editor's snap)", () => { + const ps = [{ from: 1, to: 1.2 }, { from: 2, to: 2.6 }, { from: 5, to: 5.2 }]; + close(snapEdge(1.9, "nearest", { pauses: ps }).at, 2.3); + close(snapEdge(1.4, "nearest", { pauses: ps }).at, 1.1); + assert.equal(snapEdge(2.1, "nearest", { pauses: ps }).reason, "fits"); + assert.equal(snapEdge(3.6, "nearest", { pauses: ps, maxShift: 1 }).reason, "far"); + close(snapEdge(1.4, "nearest", { pauses: ps, lo: 1.5 }).at, 2.3); +}); diff --git a/umtool/report-to-video/rail-sections.test.mjs b/umtool/report-to-video/rail-sections.test.mjs @@ -7,7 +7,7 @@ import test from "node:test"; import { deckLayout, deckMarkers, deckSchedule, deckText, labelledMarkers, markerRowsOf, pipSegments, pipXs, railSections, - resolveDeck, validateChrome, + resolveDeck, titleKey, validateChrome, } from "./deck.mjs"; import { deckCues, deckHtml, fitSectionColor, sectionFuses } from "./chrome-deck.mjs"; import { contrast } from "./chrome-intro.mjs"; @@ -181,3 +181,19 @@ test("subtitle.lines 2: an on-screen title that repeats the source's title is no const noTitle = resolveDeck(renderWith({ subtitle: { lines: 2, parts: ["channel", "date"], head: ["channel"] } })); assert.equal(deckText(clip("Why I Use A Voice Changer"), meta, { ...PROV, channelName: "Ember" }, noTitle, true).title, "Why I Use A Voice Changer"); }); + +test("subtitle.lines 2: titles compared without punctuation, symbols, quotes, emoji or case -- lw1's \"SBI?!? ||\" is its source's \"SBI? ||\"", () => { + const deck = resolveDeck(renderWith({ subtitle: { lines: 2 } })); + const meta = { title: "Who is the shadowy figure behind the creation of SBI? || Gothic Therapy react", uploadDate: "20250522" }; + const clip = (title) => ({ id: "lw1", type: "clip", video: "v", start: 0, end: 5, onscreen: { title } }); + const lw1 = deckText(clip("Who is the shadowy figure behind the creation of SBI?!? || Gothic Therapy react"), meta, PROV, deck, false); + assert.equal(lw1.title, ""); + assert.equal(lw1.subtitleLines[0], meta.title); + // Quotes, emoji and doubled space are not words either. + assert.equal(deckText(clip("“Who is the shadowy figure behind the creation of SBI?” 🤡 Gothic Therapy react!"), meta, PROV, deck, false).title, ""); + // A word of difference stands. + assert.equal(deckText(clip("Who is the shadowy figure behind SBI? || Gothic Therapy react"), meta, PROV, deck, false).title, "Who is the shadowy figure behind SBI? || Gothic Therapy react"); + // A title of nothing but punctuation is never taken for an empty source title. + assert.equal(deckText(clip("?!"), { ...meta, title: "" }, PROV, deck, false).title, "?!"); + assert.equal(titleKey(" It's Monday Madness 🤡 "), "it s monday madness"); +}); diff --git a/umtool/report-to-video/trailer-snap.test.mjs b/umtool/report-to-video/trailer-snap.test.mjs @@ -0,0 +1,186 @@ +// trailer.mjs: each clip beat's edges into the pauses (pauses.mjs), on the +// beats of the Ember draft-24 trailer as they were BEFORE the operator moved +// their ends by hand (fixtures/ember-draft-24-trailer.json: the take's own +// schedule, cut records, master silences and caption words around the edges, +// no corpus read). The cut-off sentences that started it: b01 "man.", c01 +// "door is." and kr1 "woman." faded out, and tr3 ended before "type.". Also: +// bounded by the segment's own clip and the max shift, `--no-snap`, and the +// source labels counted past a clip's gaps. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { MIN_WORD, SNAP_MAX_SHIFT } from "./pauses.mjs"; +import { makeTrailer, parseBeats, planTrailer, trailerPauses } from "./trailer.mjs"; + +const EMBER = JSON.parse(readFileSync(new URL("./fixtures/ember-draft-24-trailer.json", import.meta.url), "utf8")); + +/** The fixture as a take's build: the brand intro, its clips in the cut's order, a closing segment after them. */ +function emberBuild() { + const segments = [ + { id: "brand-intro", type: "intro", start: 0, end: 4.733 }, + ...EMBER.order.map((id) => EMBER.clips[id].segment), + { id: "closer", type: "clip", start: EMBER.total - 10, end: EMBER.total }, + ]; + return { + schedule: { version: 1, kind: "deck", fps: EMBER.fps, transition: EMBER.transition, total: EMBER.total, segments }, + records: new Map(EMBER.order.map((id) => [id, { version: 1, id, ...EMBER.clips[id].record }])), + manifest: { timeline: EMBER.order.map((id) => ({ type: "clip", id, video: id })), provenance: {} }, + master: "master.mp4", + render: { fps: 30 }, + }; +} + +/** trailerPauses over the fixture: its silences for a segment, its words for a clip (as clip-words.mjs gives them). */ +function emberPauses(build, beats) { + return trailerPauses({ + build, beats, + silences: async (_file, _render, scan) => { + const id = EMBER.order.find((k) => Math.abs(EMBER.clips[k].segment.start - scan.from) < 1e-6); + return id ? EMBER.clips[id].silences : []; + }, + words: async (entry, _prov, from, to) => { + const c = EMBER.clips[entry.id]; + if (!c?.words) return null; + return { words: c.words.filter((w) => w.start >= from && w.start <= to), timed: !!c.timed, from: c.wordsFrom }; + }, + }); +} + +const BEATS = parseBeats(EMBER.beats); +const build = emberBuild(); +const pauses = await emberPauses(build, BEATS); +const plan = (o = {}) => planTrailer({ schedule: build.schedule, records: build.records, beats: BEATS, intro: true, xfade: 0.3, pauses, ...o }); +const SNAPPED = plan(); +const PLAIN = plan({ snap: false }); + +/** A beat's piece (the n-th of the beats, 1-based; the intro is piece 0). */ +const piece = (p, n) => p.pieces[n]; +/** Its clip's words in MASTER seconds, as the plan saw them. */ +const wordsOf = (id) => pauses.get(id).words; +const silencesOf = (id) => EMBER.clips[id].silences; +const inSilence = (id, t) => silencesOf(id).some((s) => t >= s.s - 1e-3 && t <= s.e + 1e-3); + +test("the fixture: the beats before the hand fix, b01 c01 tr3 u01 kr1 bk3 tr3", () => { + assert.deepEqual(BEATS.map((b) => b.id), ["b01", "c01", "tr3", "u01", "kr1", "bk3", "tr3"]); + assert.equal(BEATS[2].end, 3011.2); +}); + +test("tr3's first beat ends after \"type.\" -- carried through the sentence, into the pause after it, before \"You\"", () => { + const p = piece(SNAPPED, 3); + assert.equal(p.id, "tr3"); + const ws = wordsOf("tr3"); + const type = ws.find((w) => w.text === "type."); + const you = ws.find((w) => w.text === "You"); + assert.ok(p.master.end >= type.start + MIN_WORD, `ends ${p.master.end}, "type." starts ${type.start}`); + assert.ok(p.master.end <= you.start + 1 / 30, `ends ${p.master.end}, "You" starts ${you.start}`); + assert.ok(inSilence("tr3", p.master.end)); + assert.ok(p.source.end > 3011.4 + MIN_WORD); + // The unsnapped plan ended before "type." started. + assert.ok(piece(PLAIN, 3).master.end < type.start); + assert.ok(SNAPPED.notes.includes('beat 3 tr3: end 3011.20 → 3012.09 (pause after "type.", the sentence\'s end)'), SNAPPED.notes.join("\n")); + assert.equal(p.snapped.end.after, "type."); + assert.ok(Math.abs(p.snapped.end.from - 765.778) < 1e-3 && Math.abs(p.snapped.end.to - 766.667) < 1e-3, JSON.stringify(p.snapped.end)); +}); + +test("b01, c01 and kr1 end in a pause, after their last word has sounded; each move said", () => { + for (const [n, id, last] of [[1, "b01", "man."], [2, "c01", "is."], [5, "kr1", "woman."]]) { + const p = piece(SNAPPED, n); + assert.equal(p.id, id); + assert.ok(inSilence(id, p.master.end), `${id} ends at ${p.master.end}, in no silence`); + const w = wordsOf(id).filter((x) => x.text === last).at(-1); + assert.ok(p.master.end > w.start + MIN_WORD, `${id}: "${last}" at ${w.start}`); + assert.ok(p.master.end > piece(PLAIN, n).master.end, `${id} moved forward`); + assert.ok(p.master.end - piece(PLAIN, n).master.end <= SNAP_MAX_SHIFT + 1 / 30); + } + const said = SNAPPED.notes.join("\n"); + assert.match(said, /beat 1 b01: end 1818\.65 → 1818\.95 \(pause after "So,"\)/); + assert.match(said, /beat 2 c01: end 220\.95 → 221\.09 \(pause after "is\."\)/); + assert.match(said, /beat 5 kr1: end 4818\.10 → 4818\.21 \(pause after "woman\."\)/); + // c01's fade (its last 0.3 s) holds no word's start: "door is." is heard whole. + const c01 = piece(SNAPPED, 2); + assert.ok(!wordsOf("c01").some((w) => w.start > c01.master.end - 0.3 + 1e-6 && w.start < c01.master.end - 1e-6)); +}); + +test("starts go back into the pause before them, never across a gap's join or into the master's crossfade", () => { + // kr1 starts on "This", now in the pause before it. + const kr1 = piece(SNAPPED, 5); + assert.ok(kr1.master.start < piece(PLAIN, 5).master.start); + assert.match(SNAPPED.notes.join("\n"), /beat 5 kr1: start 4814\.95 → 4814\.81 \(pause before "This"\)/); + // u01 starts at its gap's join: the silence across the jump cut is no reason to play what the gap took out. + const u01 = piece(SNAPPED, 4); + assert.equal(u01.master.start, piece(PLAIN, 4).master.start); + assert.ok(u01.source.start >= 9476.7 - 0.02, `u01 starts at source ${u01.source.start}`); + // Every clip piece stays out of the master's own crossfades as far as the trailer's hides them. + for (const p of SNAPPED.pieces.filter((x) => x.kind === "clip")) { + const seg = build.schedule.segments.find((s) => s.id === p.id); + assert.ok(p.master.start >= seg.start + EMBER.transition - 0.3 - 1e-3, `${p.id} start`); + assert.ok(p.master.end <= seg.end - EMBER.transition + 0.3 + 1e-3, `${p.id} end`); + } +}); + +test("bounded by the max shift and the segment's own clip, on a made-up clip", () => { + const schedule = { + fps: 30, transition: 0.5, total: 40, + segments: [{ id: "a", type: "clip", start: 0, end: 20 }, { id: "c", type: "clip", start: 19.5, end: 30 }, { id: "z", type: "clip", start: 29.5, end: 40 }], + }; + const records = new Map([["c", { start: 100, end: 110 }]]); + const one = (beat, ps) => planTrailer({ schedule, records, beats: parseBeats([beat]), xfade: 0.3, pauses: new Map([["c", { pauses: ps, words: null }]]) }); + // A pause whose quiet (a hard end's SNAP_HARD_ROOM into it) is 1.1 s after the end: too far, said. + const far = one({ id: "c", start: 102, end: 105 }, [{ from: 25.5, to: 26 }]); + assert.equal(far.pieces[0].master.end, 24.5); + assert.match(far.notes.join("\n"), /beat 1 c: end 105\.00 kept — the pause is more than 1\.00 s away/); + // A pause running past the segment's own end (the cut record's 110 is master 29.5): it stops there. + const edge = one({ id: "c", start: 102, end: 109.7 }, [{ from: 29.3, to: 30 }]); + assert.ok(edge.pieces[0].master.end <= 29.5 + 1e-6); + // The last piece has no trailer crossfade out: a hard end wants SNAP_HARD_ROOM of quiet. + const hard = one({ id: "c", start: 102, end: 105 }, [{ from: 24.6, to: 25.4 }]); + assert.ok(Math.abs(hard.pieces[0].master.end - 24.7) < 1 / 30 + 1e-6); +}); + +test("--no-snap: every edge as written, no pause measured", async () => { + for (const p of PLAIN.pieces) assert.equal(p.snapped, undefined); + assert.ok(!PLAIN.notes.some((n) => /→|kept —/.test(n))); + assert.deepEqual(plan({ pauses: null }).pieces.map((p) => p.master), PLAIN.pieces.map((p) => p.master)); + // makeTrailer --no-snap never measures. + const dir = await mkdtemp(path.join(tmpdir(), "trailer-snap-")); + try { + const takeDir = path.join(dir, "takes", "t1"); + await mkdir(path.join(takeDir, "out", "sourced", "segments"), { recursive: true }); + await writeFile(path.join(takeDir, "video.manifest.json"), JSON.stringify({ slug: "s", render: { fps: 30 }, timeline: build.manifest.timeline })); + await writeFile(path.join(takeDir, "out", "sourced", "schedule.json"), JSON.stringify(build.schedule)); + for (const [id, rec] of build.records) await writeFile(path.join(takeDir, "out", "sourced", "segments", `${id}.cut.json`), JSON.stringify(rec)); + let measured = 0; + const measure = async (b, beats) => { + measured += 1; + return emberPauses(b, beats); + }; + const common = { takeDir, beats: BEATS, intro: true, dryRun: true, probe: async () => EMBER.total, measure }; + const off = await makeTrailer({ ...common, snap: false }); + assert.equal(measured, 0); + assert.equal(off.record.snap, false); + const on = await makeTrailer(common); + assert.equal(measured, 1); + assert.equal(on.plan.pieces[3].master.end, SNAPPED.pieces[3].master.end); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the source labels count a clip's gaps: u01 and bk3 say the seconds they play, not a gap's length early", () => { + // u01's gaps take 21.77 s out before its beat; bk3's 3.27 s. + const u01 = piece(PLAIN, 4); + const bk3 = piece(PLAIN, 6); + assert.ok(Math.abs(u01.source.start - 9476.7) < 1 / 30 + 0.02, `u01 ${u01.source.start}`); + assert.ok(Math.abs(u01.source.end - 9484.95) < 1 / 30 + 0.02, `u01 ${u01.source.end}`); + assert.ok(Math.abs(bk3.source.start - 119) < 1 / 30 + 0.02, `bk3 ${bk3.source.start}`); + assert.ok(Math.abs(bk3.source.end - 123.3) < 1 / 30 + 0.02, `bk3 ${bk3.source.end}`); + // The master span is the same as ever (it was always right). + const rec = build.records.get("u01"); + const seg = build.schedule.segments.find((s) => s.id === "u01"); + const gapsBefore = rec.gaps.reduce((n, g) => n + (g.to - g.from), 0); + assert.ok(Math.abs(u01.master.start - (seg.start + 9476.7 - rec.start - gapsBefore)) < 1 / 30 + 1e-6); +}); diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -32,6 +32,23 @@ // start D − x into its segment and the master's blend is under the trailer's. // Pulled-in edges are said, never silent (`notes`). // +// EDGES INTO PAUSES (2026-11-02). The trailer's own crossfade overlaps a +// beat's last `xfade` seconds with the next beat's first: an edge a tenth of +// a second after a word starts fades that word out ("man.", "door is."), and +// one before a sentence's last word cuts it ("every [ __ ]" without "type."). +// So once the master's crossfades are kept out (above), each clip beat's END +// moves forward into the next pause -- through the sentence when one ends +// within SNAP_MAX_SHIFT -- far enough that the fade is in the quiet, and its +// START back into the pause before it (pauses.mjs snapEdge). The pauses are +// the master's own silences over the segment (cut-points.mjs detectSilence, +// the build's measure) and the gaps between the recording's timed words; the +// words (clip-words.mjs: a words file, a whisper transcript, else the +// captions' word starts) say which sentence an edge is in and name the word +// it now follows. Never past the segment's own clip (the master's +// crossfades, the cut record's end, a gap's join), never more than +// SNAP_MAX_SHIFT; each move is a note, and `--no-snap` leaves the edges as +// written. A raw beat, the intro and the finale are taken as written. +// // The spans are cut frame-accurately (decoded, never stream-copied) in ONE // ffmpeg pass: each run of the master is a `movie` source inside the // filtergraph, decoded only when the chain reaches it (separate `-i` inputs @@ -53,7 +70,11 @@ import path from "node:path"; import { promisify } from "node:util"; import { encodeArgs } from "./build-video.mjs"; -import { offsetIn, recordGaps } from "./gaps.mjs"; +import { clipWords } from "./clip-words.mjs"; +import { DEFAULT_CHANNELS_DIR } from "./cues.mjs"; +import { detectSilence } from "./cut-points.mjs"; +import { offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; +import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -159,8 +180,11 @@ function introSpan(spans) { * @param {boolean} [a.intro] prepend the master's brand intro * @param {number|null} [a.finale] append the master's last S seconds * @param {number} [a.xfade] the trailer's crossfade (0: hard cuts) + * @param {Map<string, { pauses: Array<{ from: number, to: number }>, words?: Array<{ start: number, end?: number, text: string }> | null }> | null} [a.pauses] + * each clip segment's pauses and words in MASTER seconds (trailerPauses); none: no edge moves to a pause + * @param {boolean} [a.snap] move clip beats' edges into pauses (false: `--no-snap`) */ -export function planTrailer({ schedule, records, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT }) { +export function planTrailer({ schedule, records, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT, pauses = null, snap = true }) { const { spans, count, D, total, fps } = scheduleSpans(schedule); if (!Number.isFinite(total) || total <= 0) throw new TrailerError("schedule.json has no total"); if (!Number.isFinite(xfade) || xfade < 0) throw new TrailerError(`--xfade ${xfade}: seconds ≥ 0`); @@ -208,7 +232,7 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = if (gaps.some((g) => g.from < e && g.to > s)) { notes.push(`beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} spans a gap — it plays the master's jump cut (${fmt(b - a)} s)`); } - want.push({ kind: "clip", id: beat.id, beat, rec, seg, a, b }); + want.push({ kind: "clip", id: beat.id, beat, n: n + 1, rec, seg, gaps, a, b }); }); if (finale != null) { if (!Number.isFinite(finale) || finale <= 0) throw new TrailerError(`--finale ${finale}: seconds > 0`); @@ -234,6 +258,8 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = // Edges pulled out of the master's own crossfades (see the header), then // put on frames: a start rounded to its frame, the length a whole count. + /** The piece before's end in the master, once its edges have moved. */ + let prevEnd = null; const pieces = want.map((w, i) => { const joinIn = i > 0 && !seam[i]; const joinOut = i < n - 1 && !seam[i + 1]; @@ -252,7 +278,60 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = moved.end = { from: r3(b), to: r3(hi) }; b = hi; } + // Into the pauses (the header's "edges into pauses"): bounded by the + // master's crossfades (lo, hi), the cut record's own end (a hold after it + // is a frozen frame) and the gap joins either side of the edge. + const P = snap && w.kind === "clip" ? pauses?.get(w.id) : null; + if (P) { + const toMaster = (src) => w.seg.start + offsetIn(src, w.rec.start, w.gaps); + const joins = w.gaps.map((g) => toMaster(g.from)); + const recEnd = toMaster(w.rec.end); + const label = (t) => fmt(r3(sourceAtOffset(t - w.seg.start, w.rec.start, w.gaps))); + const say = (edge, r, was) => { + const where = r.word ? `pause ${edge === "end" ? "after" : "before"} "${r.word}"` : `pause at ${label(r.pause.from)}–${label(r.pause.to)}`; + const extra = [r.sentence ? "the sentence's end" : null, r.bounded ? "held at the segment's edge" : null].filter(Boolean).join(", "); + notes.push(`beat ${w.n} ${w.id}: ${edge} ${label(was)} → ${label(r.at)} (${where}${extra ? `, ${extra}` : ""})`); + }; + const kept = (edge, r, was, bound) => { + // At the segment's own edge already (the master's crossfade, a + // join): nothing to say beyond what the crossfade note says. + if (r.reason === "bound" && Math.abs(was - bound) < 1e-3) return; + const why = r.reason === "far" ? `the pause is more than ${fmt(SNAP_MAX_SHIFT)} s away` + : r.reason === "bound" ? "the pause is past the segment's own clip" : `no pause ${edge === "end" ? "after" : "before"} it`; + notes.push(`beat ${w.n} ${w.id}: ${edge} ${label(was)} kept — ${why}`); + }; + if (!seam[i + 1]) { + const room = xOut > 0 ? xOut : SNAP_HARD_ROOM; + // Never into the next piece when it plays on from here in the master. + const next = want[i + 1]; + const nextA = next && next.a >= w.b - 1e-6 ? next.a : Infinity; + const hiSnap = Math.min(hi, recEnd, nextA, ...joins.filter((j) => j >= b - 1e-3)); + const r = snapEdge(b, "end", { pauses: P.pauses, words: P.words, room, maxShift: SNAP_MAX_SHIFT, hi: hiSnap }); + if (r.moved) { + // On the frame at or before it: the frame rounding below never carries it past the word after. + const at = Math.max(b, Math.floor(r.at * fps + 1e-6) / fps); + moved.snapped = { ...(moved.snapped ?? {}), end: { from: r3(b), to: r3(at), ...(r.word ? { after: r.word } : {}) } }; + say("end", { ...r, at }, b); + b = at; + } else if (r.reason !== "fits") kept("end", r, b, hiSnap); + } + if (!seam[i]) { + const room = xIn > 0 ? xIn : SNAP_HARD_ROOM; + // Never back into the piece before when it played up to here in the master. + const prevB = i > 0 && prevEnd !== null && prevEnd <= w.a + 1e-6 ? prevEnd : -Infinity; + const loSnap = Math.max(lo, prevB, ...joins.filter((j) => j <= a + 1e-3)); + const r = snapEdge(a, "start", { pauses: P.pauses, words: P.words, room, maxShift: SNAP_MAX_SHIFT, lo: loSnap }); + if (r.moved) { + // On the frame at or after it, for the same reason. + const at = Math.min(a, Math.ceil(r.at * fps - 1e-6) / fps); + moved.snapped = { ...(moved.snapped ?? {}), start: { from: r3(a), to: r3(at), ...(r.word ? { before: r.word } : {}) } }; + say("start", { ...r, at }, a); + a = at; + } else if (r.reason !== "fits") kept("start", r, a, loSnap); + } + } } + prevEnd = b; const fa = Math.round(a * fps); const frames = Math.round(b * fps) - fa; const name = w.kind === "clip" ? w.id : w.kind === "intro" ? "intro" : w.kind === "finale" ? "finale" : `beat ${i + 1}`; @@ -271,18 +350,21 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = master: { start: r3(start), end: r3(start + duration), duration: r3(duration) }, frames: { start: fa, count: frames }, ...(seam[i] ? { seamless: true } : {}), + // The source seconds it plays, its gaps counted: a beat after a gap is + // that much later in its source than in its segment. ...(w.kind === "clip" ? { source: { - start: r3(w.rec.start + (start - w.seg.start)), - end: r3(w.rec.start + (start + duration - w.seg.start)), + start: r3(sourceAtOffset(start - w.seg.start, w.rec.start, w.gaps)), + end: r3(sourceAtOffset(start + duration - w.seg.start, w.rec.start, w.gaps)), asked: { start: w.beat.start, end: w.beat.end }, }, segment: { start: r3(w.seg.start), end: r3(w.seg.end), cut: { start: w.rec.start, end: w.rec.end } }, } : {}), ...(w.kind === "raw" ? { asked: { at: w.beat.at, dur: w.beat.dur } } : {}), - ...(moved.start || moved.end ? { moved } : {}), + ...(moved.start || moved.end ? { moved: { ...(moved.start ? { start: moved.start } : {}), ...(moved.end ? { end: moved.end } : {}) } } : {}), + ...(moved.snapped ? { snapped: moved.snapped } : {}), }; if (moved.start) { notes.push(`${name}: starts at master ${fmt(moved.start.to)}, not ${fmt(moved.start.from)} — the master's crossfade into it runs until ${fmt(w.seg.start + D)}`); @@ -456,6 +538,52 @@ export async function loadTakeBuild(takeDir) { return { manifest, slug, render: manifest.render, master, schedule, records }; } +/** + * Each clip beat's segment's pauses and words, in MASTER seconds, for + * planTrailer: the master's silences over the segment (`silences`, the + * build's detectSilence with the take's render settings) and the recording's + * words over the cut (`words`, clip-words.mjs), mapped onto the master by the + * cut record -- a word in one of the clip's gaps is not in the master. Once + * per segment, however many beats it plays in. A segment whose measure fails + * has no pauses: its edges stay. + * + * @param {object} a + * @param {object} a.build loadTakeBuild's + * @param {object[]} a.beats parseBeats's + * @param {(file: string, render: object, scan: { from: number, to: number }) => Promise<Array<{ s: number, e: number }>>} [a.silences] + * @param {(entry: object, provenance: object, from: number, to: number) => Promise<{ words: Array<{ start: number, end?: number, text: string }>, timed: boolean } | null>} [a.words] + */ +export async function trailerPauses({ + build, beats, + silences = (file, render, scan) => detectSilence(file, render, scan), + words = (entry, provenance, from, to) => clipWords(entry, provenance, from, to, { channelsDir: DEFAULT_CHANNELS_DIR }), +}) { + const { spans } = scheduleSpans(build.schedule); + const entries = new Map((build.manifest?.timeline ?? []).filter((e) => e?.id).map((e) => [e.id, e])); + const out = new Map(); + for (const beat of beats) { + if (beat.kind !== "clip" || out.has(beat.id)) continue; + const seg = spans.get(beat.id); + const rec = build.records.get(beat.id); + if (!seg || !rec || !Number.isFinite(rec.start) || !Number.isFinite(rec.end)) continue; + const gaps = recordGaps(rec); + const sil = await silences(build.master, build.render, { from: seg.start, to: seg.end }).catch(() => []); + const entry = entries.get(beat.id); + const got = entry ? await words(entry, build.manifest?.provenance ?? {}, rec.start - 1, rec.end + 1).catch(() => null) : null; + const inGap = (t) => gaps.some((g) => t > g.from && t < g.to); + const toMaster = (t) => seg.start + offsetIn(t, rec.start, gaps); + const ws = (got?.words ?? []) + .filter((w) => !inGap(w.start)) + .map((w) => ({ start: toMaster(w.start), ...(got.timed && Number.isFinite(w.end) ? { end: toMaster(w.end) } : {}), text: w.text })); + out.set(beat.id, { + pauses: pauseSpans({ silences: sil, words: ws }, { from: seg.start, to: seg.end }), + words: ws, + ...(got ? { wordsFrom: got.from ?? null } : {}), + }); + } + return out; +} + /** The master's length in seconds (its frames over the fps), or null when it cannot be read. */ export async function probeMasterSeconds(file, fps) { try { @@ -498,13 +626,20 @@ export async function runFfmpeg(argv) { * @param {(file: string, fps: number) => Promise<number|null>} [a.probe] * @param {(fn: () => Promise<any>) => Promise<any>} [a.slot] the heavy slot around the encode * @param {() => number} [a.now] + * @param {boolean} [a.snap] move clip beats' edges into pauses (false: `--no-snap`) + * @param {(build: object, beats: object[]) => Promise<Map<string, any>>} [a.measure] the pauses (trailerPauses; tests stub it) */ export async function makeTrailer({ takeDir, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT, out = null, dryRun = false, run = runFfmpeg, probe = probeMasterSeconds, slot = (fn) => fn(), now = Date.now, + snap = true, measure = (build, list) => trailerPauses({ build, beats: list }), }) { const build = await loadTakeBuild(takeDir); - const plan = planTrailer({ schedule: build.schedule, records: build.records, beats, intro, finale, xfade }); + // Checked once without the pauses first: a beat that is refused is refused + // before anything is measured. + planTrailer({ schedule: build.schedule, records: build.records, beats, intro, finale, xfade, snap: false }); + const pauses = snap ? await measure(build, beats) : null; + const plan = planTrailer({ schedule: build.schedule, records: build.records, beats, intro, finale, xfade, pauses, snap }); const masterSeconds = await probe(build.master, plan.fps); if (masterSeconds == null) throw new TrailerError(`${path.basename(takeDir)} has no master: ${build.master} cannot be read`); if (Math.abs(masterSeconds - plan.masterSeconds) > 0.1) { @@ -526,6 +661,7 @@ export async function makeTrailer({ schedule: path.join(takeDir, "out", "sourced", "schedule.json"), }, xfade: plan.xfade, + snap, transition: plan.transition, fps: plan.fps, encode: { crf: build.render.crf ?? 20, preset: build.render.preset ?? "medium", audioBitrate: build.render.audioBitrate ?? "160k" }, @@ -567,7 +703,8 @@ export function describePlan(plan) { : p.kind === "raw" ? `${"(master)".padEnd(22)} at ${fmt(p.asked.at)} for ${fmt(p.asked.dur)}` : `${`(${p.kind})`.padEnd(22)}`; const span = `master ${clock(p.master.start)}–${clock(p.master.end)}`; - return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.master.duration)} s${p.moved ? " (edge moved)" : ""}`; + const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}`; + return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.master.duration)} s${marks}`; }); lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces, crossfade ${fmt(plan.xfade)} s`); return lines; diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs @@ -46,11 +46,24 @@ const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim(); * span): `{ chapters, note }` -- `chapters` null when the block is left out, * `note` saying what was folded or why the block is left out. * - * @param {Array<{ start: number, end?: number, title: string, section?: boolean }> | null | undefined} list + * With the deck's `markers` (and the opening's title, `first`), the chapters + * are its sections (markerChapters) when the list names each entry (`id`) and + * where its segment starts in the cut (`cutStart`). + * + * @param {Array<{ start: number, end?: number, title: string, section?: boolean, id?: string, cutStart?: number }> | null | undefined} list * @param {number | null} [total] + * @param {{ markers?: Array<{ after?: string, label?: string, level?: number }> | null, first?: string | null }} [opts] */ -export function youtubeChapters(list, total = null) { +export function youtubeChapters(list, total = null, { markers = null, first = null } = {}) { if (!Array.isArray(list) || !list.length) return { chapters: null, note: "no chapters: the build made none" }; + // A deck with markers: its sections are the chapters (markerChapters), at + // the second each section's first segment starts in the cut (`cutStart`, + // before the crossfade it lands after). The list must say which entry each + // chapter is (`id`): the build's does. + if (hasChapterMarkers(markers) && list.every((c) => typeof c?.id === "string" && Number.isFinite(c?.cutStart))) { + const r = markerChapters({ markers, segments: list.map((c) => ({ id: c.id, start: c.cutStart })), total, first }); + return { chapters: r.chapters, note: r.notes.join("; ") }; + } // The build's list has a chapter per segment (a player's navigation). A // description's chapters are the cut's SECTIONS: when the list says which // entries open one (`section`: a title or chapter card), every other entry @@ -86,6 +99,118 @@ export function youtubeChapters(list, total = null) { return { chapters: kept, note: foldNote }; } +// ---- chapters from the deck's markers (2026-11-02) ------------------------ +// +// A cut whose deck carries markers (`render.chrome.deck.markers`) has its +// sections named already: the rail's flags. Its chapters are those -- each +// TOP-LEVEL marker (a `level: 2` subsection is a tick inside its section, not +// a chapter) at the second the section after it starts in the master: the +// start of the segment after the clip it follows (`after`), where the +// dissolve into that section begins. The stretch before the first marker is +// the opening, titled `deck.sectionTitle.first` (the section title's "first +// section's title"); with none, the opening takes the first section's label +// and that section starts at 0:00. Replaces the hand script that read +// schedule.json and the markers (night1030 chapters.py), row for row. + +/** Does this deck have a marker a chapter can be made of (top-level, labelled)? */ +export function hasChapterMarkers(markers) { + return Array.isArray(markers) && markers.some((m) => m && m.level !== 2 && oneLine(m.label)); +} + +/** + * YouTube's rules over a list in order (`{ start, title }`, seconds), with + * what had to change said by name: the first at 0:00 (a list that does not + * start there is left out), each at least ten seconds (one that starts under + * ten seconds after the chapter before it is merged into that one -- but an + * OPENING under ten seconds gives 0:00 to the chapter after it), the last + * ten seconds before `total` too, at least three. + * + * @param {Array<{ start: number, title: string }>} list + * @param {number | null} total + * @returns {{ chapters: Array<{ start: number, title: string }> | null, notes: string[] }} + */ +export function youtubeChapterRules(list, total = null) { + const notes = []; + const all = list.map((c) => ({ start: Math.floor(Number(c.start)), title: oneLine(c.title) || "Chapter" })); + if (!all.length) return { chapters: null, notes: ["no chapters: none to make"] }; + if (all[0].start !== 0) return { chapters: null, notes: [`no chapters: the first starts at ${chapterStamp(all[0].start)}, not 0:00`] }; + const min = YOUTUBE_CHAPTERS.minSeconds; + const kept = [all[0]]; + for (const c of all.slice(1)) { + const prev = kept.at(-1); + const gap = c.start - prev.start; + if (gap >= min) { + kept.push(c); + continue; + } + if (kept.length === 1 && prev.start === 0) { + notes.push(`the opening “${prev.title}” runs ${gap} s, under ${min}: “${c.title}” starts at 0:00, not ${chapterStamp(c.start)}`); + kept[0] = { start: 0, title: c.title }; + continue; + } + notes.push(`“${c.title}” (${chapterStamp(c.start)}) is ${gap} s after “${prev.title}”, under ${min}: merged into it`); + } + const end = Number.isFinite(Number(total)) && total !== null ? Math.floor(Number(total)) : null; + while (end !== null && kept.length > 1 && end - kept.at(-1).start < min) { + const last = kept.pop(); + notes.push(`“${last.title}” (${chapterStamp(last.start)}) runs ${end - last.start} s to the end, under ${min}: merged into “${kept.at(-1).title}”`); + } + if (kept.length < YOUTUBE_CHAPTERS.min) { + notes.unshift(`no chapters: ${kept.length} of at least ${YOUTUBE_CHAPTERS.min}`); + return { chapters: null, notes }; + } + return { chapters: kept, notes }; +} + +/** + * The chapters a cut's deck markers make, by YouTube's rules + * (youtubeChapterRules): `{ chapters, notes }`, `chapters` null when the deck + * has no top-level labelled marker in the cut, or too few survive. + * + * @param {object} o + * @param {Array<{ after?: string, label?: string, level?: number }>} o.markers `deck.markers` + * @param {Array<{ id: string, start: number }>} o.segments the master's segments in order, each where it starts (schedule.json's) + * @param {number | null} [o.total] the master's length + * @param {string | null} [o.first] the opening's title (`deck.sectionTitle.first`) + */ +export function markerChapters({ markers, segments, total = null, first = null }) { + const notes = []; + const index = new Map((segments ?? []).map((s, i) => [s.id, i])); + const rows = []; + for (const m of Array.isArray(markers) ? markers : []) { + if (!m || m.level === 2) continue; + const label = oneLine(m.label); + const after = String(m.after ?? "").trim(); + if (!label) continue; + const i = index.get(after); + if (i === undefined) { + notes.push(`“${label}” follows ${after || "no clip"}, which is not in the cut: no chapter`); + continue; + } + const next = segments[i + 1]; + if (!next) { + notes.push(`“${label}” follows the cut's last segment: no chapter`); + continue; + } + rows.push({ start: Number(next.start), title: label }); + } + if (!rows.length) return { chapters: null, notes: [...notes, "no chapters: no labelled top-level marker in the cut"] }; + rows.sort((a, b) => a.start - b.start); + const opening = oneLine(first); + if (opening) rows.unshift({ start: 0, title: opening }); + else if (Math.floor(rows[0].start) !== 0) { + notes.push(`the opening has no title (deck.sectionTitle.first): “${rows[0].title}” starts at 0:00, not ${chapterStamp(rows[0].start)}`); + rows[0] = { ...rows[0], start: 0 }; + } + const r = youtubeChapterRules(rows, total); + return { chapters: r.chapters, notes: [...notes, ...r.notes] }; +} + +/** The chapter block's lines (`0:00 Title`), as out/youtube.txt and `umtool export --format chapters` print them. */ +export function chapterLines(chapters) { + return (chapters ?? []).map((c) => `${chapterStamp(c.start)} ${oneLine(c.title)}`); +} + /** * A clip's moment link: its `citeUrl` when it has one, else the archive's page * at the cited second (`cite`, else `start`) -- the link the citation makes @@ -129,7 +254,7 @@ export function composeYoutubeText({ youtube, chapters = null, sources = [] }) { const parts = [title]; const description = String(youtube?.description ?? "").trim(); if (description) parts.push(description); - if (chapters?.length) parts.push(["Chapters", ...chapters.map((c) => `${chapterStamp(c.start)} ${oneLine(c.title)}`)].join("\n")); + if (chapters?.length) parts.push(["Chapters", ...chapterLines(chapters)].join("\n")); if (sources.length) parts.push(["Sources", ...sources].join("\n")); return `${parts.join("\n\n")}\n`; } diff --git a/umtool/report-to-video/youtube.test.mjs b/umtool/report-to-video/youtube.test.mjs @@ -6,7 +6,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { - chapterStamp, composeYoutubeText, momentLinkOf, youtubeChapters, youtubePreview, youtubeSources, youtubeTextName, YOUTUBE_CHAPTERS, + chapterLines, chapterStamp, composeYoutubeText, markerChapters, momentLinkOf, youtubeChapterRules, youtubeChapters, youtubePreview, youtubeSources, youtubeTextName, YOUTUBE_CHAPTERS, } from "./youtube.mjs"; const FULL = new URL("../../common/testing/draft/manifests/full.video.manifest.json", import.meta.url); @@ -105,3 +105,53 @@ test("youtubeChapters: with sections marked, the clips fold into the section tha // Too few sections: the block is left out rather than listing clips. assert.equal(youtubeChapters(list.filter((c) => c.title !== "Insulinoma"), 130).chapters, null); }); + +// ---- chapters from the deck's markers (2026-11-02) ------------------------ + +const EMBER = JSON.parse(await (await import("node:fs/promises")).readFile(new URL("./fixtures/ember-draft-24-chapters.json", import.meta.url), "utf8")); +const emberSegments = EMBER.segments.map(([id, start]) => ({ id, start })); + +test("markerChapters: Ember draft-24's 12 markers make the hand script's 13 rows, row for row", () => { + const r = markerChapters({ markers: EMBER.markers, segments: emberSegments, total: EMBER.total, first: EMBER.first }); + assert.deepEqual(chapterLines(r.chapters), EMBER.expected); + assert.deepEqual(r.notes, []); +}); + +test("markerChapters: subsections are no chapters; an untitled opening gives 0:00 to the first section; what YouTube's rules merge is said", () => { + const markers = [ + ...EMBER.markers.slice(0, 3), + { after: "rf1", label: "A subsection", level: 2 }, + { after: "rf1", label: "Too close" }, // a segment 5.1 s after "Leaves it open" starts + { after: "nope", label: "Gone" }, + { after: "ho3", label: "After the last" }, + { after: "mk1", label: "" }, + ]; + const segments = emberSegments.flatMap((s) => (s.id === "rf1" ? [s, { id: "rf1b", start: 330 }] : [s])); + const r = markerChapters({ markers, segments, total: EMBER.total }); + assert.deepEqual(chapterLines(r.chapters), ["0:00 Sex appeal", "4:59 Not a character", "5:24 Leaves it open"]); + assert.ok(!chapterLines(r.chapters).some((l) => l.includes("A subsection"))); + const said = r.notes.join("\n"); + assert.match(said, /“Gone” follows nope, which is not in the cut/); + assert.match(said, /“After the last” follows the cut's last segment/); + assert.match(said, /the opening has no title \(deck\.sectionTitle\.first\): “Sex appeal” starts at 0:00, not 2:56/); + assert.match(said, /“Too close” \(5:30\) is 6 s after “Leaves it open”, under 10: merged into it/); +}); + +test("youtubeChapterRules: a short opening gives 0:00 to the next; a short last one is merged; under three is left out", () => { + const r = youtubeChapterRules([{ start: 0, title: "Open" }, { start: 4.7, title: "First" }, { start: 30, title: "Second" }, { start: 60, title: "Third" }, { start: 95, title: "Tail" }], 100); + assert.deepEqual(r.chapters.map((c) => [c.start, c.title]), [[0, "First"], [30, "Second"], [60, "Third"]]); + assert.match(r.notes.join("\n"), /the opening “Open” runs 4 s, under 10: “First” starts at 0:00, not 0:04/); + assert.match(r.notes.join("\n"), /“Tail” \(1:35\) runs 5 s to the end, under 10: merged into “Third”/); + const two = youtubeChapterRules([{ start: 0, title: "A" }, { start: 30, title: "B" }], 60); + assert.equal(two.chapters, null); + assert.match(two.notes[0], /^no chapters: 2 of at least 3/); +}); + +test("youtubeChapters: a build's list with ids and cut starts, under a deck with markers, is the markers' chapters", () => { + const list = emberSegments.map((s, i) => ({ start: i === 0 ? 0 : s.start + 0.4, title: `seg ${s.id}`, id: s.id, cutStart: s.start })); + const r = youtubeChapters(list, EMBER.total, { markers: EMBER.markers, first: EMBER.first }); + assert.deepEqual(chapterLines(r.chapters), EMBER.expected); + // No markers: as before, one per entry folded by the ten-second rule. + const plain = youtubeChapters(list, EMBER.total); + assert.equal(plain.chapters[1].title, "seg v01t"); +});