// THE PLAY VIEW's data (umtool/docs/knobs.md, "Play the cut"): what `/projects/
/play`
// (and `?take=`) plays, read on the server -- the cut's entries in
// timeline order, each clip's play window and the cached source window its
// media comes from (the bench's own rule, serve.mjs windowsFor: the widest
// file holding it, an excerpt of a long recording), the estimate's segments
// (the clock when the cut has no deck; with a deck the live preview's
// schedule replaces them, holds included), and the takes it can switch to.
//
// Nothing is fetched or cut here: a clip whose source window is not on disk
// is listed with `media: null` and plays as a placeholder.
import { censorRegionsOf } from "umtool-report-to-video/clip-censor";
import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video";
import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck";
import { resolveFactcheck } from "umtool-report-to-video/factcheck";
import { basicOn, basicSpans } from "umtool-report-to-video/basic";
import { channelsDirFor, clipDateKey, readManifest } from "../projects/report.mjs";
import { rejectionOf } from "./rejectReasons.mjs";
import { dateKeyLabel } from "./playCut.mjs";
import { panelEntry, postDay, postItemPlan } from "umtool-report-to-video/post-item";
import { planContext } from "umtool-report-to-video/post-conversation";
import { playableEntry } from "umtool-report-to-video/post-thread";
import { clockPlan } from "umtool-report-to-video/post-clock";
import { progressPlan } from "umtool-report-to-video/post-progress";
import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs";
import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs";
import { draftLine, readWorkingCut } from "./workingCut.mjs";
import { listTakes, previewFile } from "./takes.mjs";
import { sectionModel } from "./sectionEdit.mjs";
import { effectiveManifest, manifestToken } from "./manifest.mjs";
import { clipGapCueOf, gapCueBorderOf, gapCueWanted } from "yt-dlp-transcript-common/lib/report/gapCue.mjs";
import { projectCombos } from "umtool-report-to-video/post-combo-prints";
import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene";
import { videoAudio, videoEnter, videoFit, videoHidesChrome, videoLead, videoSeconds, videoSpan } from "umtool-report-to-video/video-entry";
const fin = (v) => typeof v === "number" && Number.isFinite(v);
const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : "");
/** The words a placeholder shows for an entry that is not a clip (a card, a teaser, an image). */
export function headingOf(e) {
const line = Array.isArray(e?.lines) ? e.lines.map((l) => (typeof l === "string" ? l : text(l?.text))).find(Boolean) : "";
return text(e?.heading) || text(e?.title) || text(e?.onscreen?.title) || line || text(e?.text) || String(e?.type ?? "entry");
}
/**
* A POST ITEM as Play plays it (post-item.mjs): the entry itself (its card is
* drawn from it, by the same HTML the build screenshots), the plan of what
* plays when, and the day for the reel strip's tint. Its files are served by
* /api/report/post-item, which serves only what a post item names.
*
* @param {Record} e
* @param {Record} [render]
* @param {{ prev?: Record | null, scene?: Record | null } | null} [ctx] the item before it
* in the cut and the scene its run leaves on screen (post-conversation.mjs planContext)
* @param {Record | null} [mediaScene] its media scene (post-media-scene.mjs mediaSceneOf): `post` is
* the item as the scene plays it (the shared attachment the anchor's), its plan's card the scene's column -- unless
* the conversation's scene takes the card (it wins; the media scene keeps the attachment)
*/
export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = null) {
const day = postDay(e.date);
const dateKey = day ? Number(day.replace(/-/g, "")) : null;
const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
const plan = postItemPlan(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null });
return {
id: e.id,
type: "post",
heading: `${e.author ?? (e.handle ? `@${e.handle}` : "a post")}: ${words.length > 80 ? `${words.slice(0, 77)}…` : words || "(no words)"}`,
section: e.section ?? null,
dateKey,
dateLabel: dateKeyLabel(dateKey),
date: day || null,
quote: words || null,
post: panelEntry(sceneEntry(e, mediaScene), render),
// Its read, NOT played (post-thread.mjs playableEntry): why -- Play and Present say so.
...(e.readRefused ? { readRefused: e.readRefused } : {}),
// `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: the
// posts its run left on screen (post-conversation.mjs: one conversation played as one scene) -- it wins the card.
postPlan: plan,
// Its progress bar (post-progress.mjs): the read's span and its parts' ticks (Play lays a stack card's end).
postProgress: progressPlan(e, render, plan),
// Its clock (post-clock.mjs): its post's time, run from the clock item before it.
postClock: clockPlan(e, render, ctx?.prev ?? null),
...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}),
};
}
/**
* A VIDEO entry as Play plays it (video-entry.mjs): a file of the project, its
* span (`from`–`to` source seconds), how it fits the frame, its entrance (the
* item before fades to black over `enter.out`, it fades up over `enter.in`
* after its `lead`), its sound's bass and gain, and whether the chrome is off
* over it. Its file is served by /api/report/file (lib/report/projectFile.mjs). Its length on the
* clock is the segment's (videoSeconds, which the estimate's segments use).
*
* @param {Record} e
* @param {number} D the cut's transition
*/
export function videoPlayEntry(e, D) {
const span = videoSpan(e);
return {
id: e.id,
type: "video",
heading: text(e.title) || String(e.src ?? "").split("/").pop() || e.id,
section: e.section ?? null,
// Not `video` (a clip's recording id): the file and how it plays.
videoEntry: {
src: String(e.src ?? ""),
from: span.from,
to: span.to,
fit: videoFit(e),
enter: videoEnter(e),
lead: videoLead(e, D),
hold: fin(e.holdLast) ? e.holdLast : 0,
seconds: videoSeconds(e, D),
...videoAudio(e),
noChrome: videoHidesChrome(e),
},
};
}
/**
* WHAT PLAYS BY DEFAULT is THE DRAFT (umtool redesign L3: every edit lands in
* the project's manifest, the working draft; a take is a frozen saved
* version): with no `take`, the project's manifest as it is now. `take` plays
* that version read-only -- its frozen manifest (lib/report/versions.mjs), or
* a legacy take's patch over the manifest as it always did -- with Open in
* draft beside it. `bare` (`?cut=1`) is the draft too, said the old way. The
* draft's parent and its edits ride along (`working`, `draft`) for the header.
*
* @param {{ id: string, dir: string }} project
* @param {{ take?: string | null, bare?: boolean }} [opts]
*/
export async function playView(project, { take = null, bare = false } = {}) {
const r = await playViewWith(project, { take, bare });
return r.view ?? { error: String(r.error) };
}
/**
* THE PLAY VIEW AND WHAT IT WAS MADE FROM (present mode, lib/report/present.mjs): `{ view, manifest, base }` --
* the view playView answers, the cut it played (the take's patch applied, the default variant selected) and the
* project's own manifest -- or `{ error }`. `postFor`, given the cut that plays, answers how each post item is
* turned before it is planned (present.mjs: the build's own `censorEntry`, the channel markup's censored
* attachments; Play draws the item as written).
*
* @param {{ id: string, dir: string }} project
* @param {{ take?: string | null, bare?: boolean, postFor?: ((manifest: Record) => Promise<(e: Record) => Record>) | null }} [opts]
*/
export async function playViewWith(project, { take = null, bare = false, postFor = null } = {}) {
const base = await readManifest(project.dir);
if (!base) return { error: "this project has no video.manifest.json" };
const working = await readWorkingCut(project.dir).catch(() => null);
void bare;
let manifest = base;
/** @type {null | { id: string, label: string, summary: string, made: boolean, from: string, ownTimeline: boolean, version: boolean, frozen: boolean, parent: boolean, render: string | null }} */
let takeInfo = null;
let note = null;
if (take) {
try {
const r = await resolveTakeManifest(project.dir, take, { base });
manifest = r.manifest;
const listed = r.take.made ? (await listTakes(project.dir)).takes.find((t) => t.id === take) ?? null : null;
const file = listed ? await previewFile(project.dir, listed) : null;
takeInfo = {
id: r.take.id,
label: r.take.label,
summary: r.take.summary,
made: r.take.made,
from: r.take.from,
// A patch that brings its own timeline (a legacy take walked): Open in draft merges it (versions.mjs).
ownTimeline: Array.isArray(/** @type {any} */ (r.take.patch)?.timeline),
// A saved version (frozen base), or a legacy take that follows the draft.
version: listed?.version === true,
frozen: r.frozen === true,
// The draft's parent: opening it with no edits writes nothing.
parent: working?.parent?.id === take,
// Its render, when there is one ("Watch render").
render: file ? `/api/report/takes/preview?${new URLSearchParams({ project: project.id, take, v: String(file.mtimeMs) })}` : null,
};
note = r.note;
} catch (e) {
return { error: e instanceof Error ? e.message : String(e) };
}
}
// Each entry's place in the manifest's own timeline, by identity: the variant selection keeps an entry's object
// (one it turns -- `variants` -- and the intro it prepends are new, so they carry none). The workspace's writers
// name an entry by it, so a variant twin is never taken for the one on screen (lane block-menus L8b).
const sourceAt = new WeakMap();
(manifest.timeline ?? []).forEach((e, i) => e && typeof e === "object" && sourceAt.set(e, i));
const selected = selectVariant(manifest, DEFAULT_VARIANT);
const render = selected.render ?? {};
// The mark at the gaps' joins (lane gap-cue) as the build reads it: the look preset under the cut's own render.
let cueRender = render;
try {
cueRender = effectiveManifest(selected).render ?? render;
} catch {
// An unknown preset: the manifest's own word.
}
// THE BASIC OUTPUT MODE (render.mode, report-to-video basic.mjs): Play plays what the basic render cuts --
// the clips alone, their spans exactly (no lead-in), hard cuts, nothing drawn over the footage.
const basic = basicOn(render);
const post = postFor ? await postFor(selected) : null;
const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string" && (!basic || e.type === "clip"));
const D = basic ? 0 : transitionOf(render);
const durs = timeline.map((e) => (basic ? Math.max(0.5, basicSpans(e, render).reduce((n, x) => n + x.to - x.from, 0)) : estimatedDuration(e, render, D)));
const { starts } = scheduleFrom(durs, D);
const segments = timeline.map((e, i) => ({ id: e.id, start: Math.round(starts[i] * 1000) / 1000, duration: Math.round(durs[i] * 1000) / 1000 }));
const cache = await projectCache(project, manifest);
// The combo counter's repeat groups (post-combo.mjs), counted over the cut played: its badges, and its media
// scenes (post-media-scene.mjs: neighbours with the same attachment).
const { combos, groups: repeatGroups } = timeline.some((e) => e.type === "post")
? await projectCombos(project.dir, selected, { channelsDir: channelsDirFor(project.dir, base) }).catch(() => ({ combos: {}, groups: [] }))
: { combos: {}, groups: [] };
const entries = await Promise.all(
timeline.map(async (e, i) => {
// Never a read the build refuses (post-thread.mjs playableEntry, judged on the item as written): it plays silent.
if (e.type === "post") {
const pe = playableEntry(e);
return postPlayEntry(post ? post(pe) : pe, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, render));
}
if (e.type === "video") return videoPlayEntry(e, D);
if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null };
const win = pickWindow(await windowsFor(project, e, cache), null);
const dateKey = clipDateKey(e);
const onscreenDate = text(e.onscreen?.title);
return {
id: e.id,
type: "clip",
// The recording's date (the on-screen date, else the upload date): the reel strip's tint.
dateKey,
dateLabel: dateKey === null ? null : /^\d{1,2}\s+[A-Za-z]{3}/.test(onscreenDate) ? onscreenDate : dateKeyLabel(dateKey),
section: e.section ?? null,
channel: typeof e.channel === "string" ? e.channel : null,
// The channel the clip cuts from, the provenance's when the clip names none: its life cycle's address (lane L5).
sourceChannel: typeof e.channel === "string" && e.channel ? e.channel : typeof selected.provenance?.channelSlug === "string" ? selected.provenance.channelSlug : null,
heading: text(e.onscreen?.title) || text(e.title) || text(e.quote) || e.id,
date: text(e.date) || text(e.onscreen?.title) || null,
quote: text(e.quote) || null,
video: String(e.video ?? ""),
start: e.start,
end: e.end,
cutStart: fin(e.cutStart) ? e.cutStart : null,
cutEnd: fin(e.cutEnd) ? e.cutEnd : null,
// Seconds taken out of its middle (gaps.mjs): the plan plays it as one item of jump cuts.
...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}),
// The mark at those gaps' joins (common gapCue.mjs): its settings, the clip's over the project's -- only when a
// gap of it is marked (lib/report/gapCueView.mjs draws it at Play's joins, on the render's timing).
// `borderColor`: its border as the render resolves it (gapCueBorderOf: the setting, else the deck's accent).
...(!basic && Array.isArray(e.gaps) && e.gaps.length && gapCueWanted(cueRender, e) ? { gapCue: { ...clipGapCueOf(cueRender, e), borderColor: gapCueBorderOf(cueRender, e) } } : {}),
blur: e.blur && typeof e.blur === "object" ? e.blur : null,
// Its hidden regions (report-to-video clip-censor.mjs): Play draws them over the picture as the cut hides them.
censor: censorRegionsOf(e, render, selected.provenance ?? {}),
// Its SIDE POST (lane vertical, common lib/report/vertical.mjs): shown beside it over `from`-`to` (seconds
// into the clip as it plays), never read -- Play lays its card (the post-item route's `side` page) over the clip.
...(e.side && typeof e.side === "object" && fin(e.side.from) && fin(e.side.to) ? { side: { from: e.side.from, to: e.side.to, place: typeof e.side.place === "string" ? e.side.place : null } } : {}),
// Rejected by the walk (a fact error -- doesn't match, wrong speaker -- or a cut
// reason: irrelevant, repeats, …): why, in words -- Play skips it unless asked to show it.
rejected: (() => {
const r = rejectionOf(e);
return r ? { reason: r.reason, label: r.label, fact: r.fact, why: r.why } : null;
})(),
// The verdict's fields as written: what Reject prefills, and what its keep-in-place Undo writes back.
review: {
verdict: typeof e.verdict === "string" ? e.verdict : null,
reason: typeof e.reason === "string" ? e.reason : null,
correction: typeof e.correction === "string" ? e.correction : null,
rejectNote: typeof e.rejectNote === "string" ? e.rejectNote : null,
},
// The window the bench would play: its name for the raw route, the source second its file starts at,
// and the version of its bytes (`v`: a refetch under the same name is a new URL -- serve.mjs,
// "A REPLACED FILE IS A NEW FILE").
media: win ? { name: win.name, from: win.from, to: win.to, v: await windowVersion(win) } : null,
};
}),
);
// The combo counter (post-combo.mjs): a post item that repeats an earlier one's attachment carries its badge
// (`postCombo`: its count, which attachment, the knobs, whether it shows), counted over the cut played.
for (const e of entries) if (e.type === "post" && combos[e.id]) Object.assign(e, { postCombo: combos[e.id] });
entries.forEach((e, i) => Object.assign(e, { timelineAt: sourceAt.get(timeline[i]) ?? null }));
// The counter (the deck's tally): each stamp's landing second and count on
// the estimate's clock, and each verdict's word -- the reel strip's
// staircase before (or without) the chrome's own schedule.
let counter = { verdicts: /** @type {Array<{ id: string, label: string }>} */ ([]), stamps: /** @type {Array<{ landed: number, verdict: string, count: number }>} */ ([]) };
try {
const est = estimateSchedule(selected);
const stamps = (est?.factcheck?.stamps ?? []).filter((x) => fin(x.landed));
const words = /** @type {Record} */ (resolveFactcheck(render).verdicts ?? {});
const ids = [...new Set(stamps.map((x) => String(x.verdict)))];
counter = {
verdicts: ids.map((id) => ({ id, label: words[id]?.label ?? id })),
stamps: stamps.map((x) => ({ landed: x.landed, verdict: String(x.verdict), count: fin(x.count) ? x.count : 1 })),
};
} catch {
// A cut the deck cannot schedule counts nothing on the strip.
}
const markers = Array.isArray(render.chrome?.deck?.markers)
? render.chrome.deck.markers.filter((m) => m && typeof m.after === "string").map((m) => ({ after: m.after, label: typeof m.label === "string" ? m.label : "", ...(m.level === 2 ? { level: 2 } : {}) }))
: [];
// THE SECTIONS A DROP LANDS IN: the project's manifest's (what a reorder writes), each clip's
// section and each section's label and colour (sectionEdit.mjs sectionModel) -- as many as
// the markers make, no limit assumed here.
const model = sectionModel(base);
// A take whose patch sets its OWN markers, out of step with the cut's (patchMarkers.mjs: a patch
// not synced): a drop moves the cut's clips and sections, and this take keeps showing its own.
const markersOf = (m) => JSON.stringify(m?.render?.chrome?.deck?.markers ?? null);
const sectionsDiffer = !!takeInfo && markersOf(selected) !== markersOf(selectVariant(base, DEFAULT_VARIANT));
// A subsection (level 2) is a section a drop lands in like any other; `within` names its section.
const sections = model.sections.map((x) => ({
index: x.index, label: x.label, color: x.color, marker: x.marker, count: x.clips.length,
...(x.level === 2 ? { level: 2, within: x.within ?? null } : {}),
}));
// The claim groups (lib/report/claimGroups.mjs): the strip's lighter seams, from the cut played.
const groups = (Array.isArray(selected.groups) ? selected.groups : [])
.filter((g) => g && typeof g.id === "string" && Array.isArray(g.ids))
.map((g) => ({ id: g.id, claim: typeof g.claim === "string" ? g.claim : "", ids: g.ids.filter((x) => typeof x === "string") }));
const view = {
project: project.id,
title: text(manifest.title) || project.id,
groups,
sections,
sectionOf: Object.fromEntries(model.sectionOf),
sectionsDiffer,
// The manifest's token: a reorder written from a view older than the file is refused (409), not lost.
token: await manifestToken(project.dir),
counter,
markers,
take: takeInfo,
note,
takes: await playableTakes(project.dir),
working,
// The draft's header: "Draft · from v5 · 3 edits", "Draft · unsaved" (workingCut.mjs draftLine).
draft: { line: draftLine(working), parent: working?.parent?.id ?? null, edits: working?.edits?.count ?? null },
leadIn: basic ? 0 : fin(render.leadIn) ? render.leadIn : 0.4,
transition: D,
blurRendered: render.blur !== "off",
deckOn: !basic && deckOn(render),
// A basic cut (render.mode "basic"): the footage alone -- Play draws nothing over it.
basic,
segments,
entries,
};
return { view, manifest: selected, base };
}