// EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a // single clip, cut from the file the build would cut it from, with none of the // deck's chrome -- no rail, subtitles, QR or cards -- into the project's // `exports/`, where the operator keeps the hand-made ones // (`exports/tr3-2026-08-12-deal-with-it-autogynephiliac.mp4`). // // THREE KINDS (UI notes 2026-10-30, item 12: "as cut (no chrome)", "with N s // context", "raw / full exchange (fetch if needed)"). // // cut the clip as the cut plays it: the render's edges (cutPoints.mjs -- // the build's own source, snap and room; the muted room at an edge is // left off, since nothing is heard there), its `gaps` taken out as // jump cuts on the frame grid with the build's 25 ms fades at each // join (gaps.mjs gapFilterParts), its sound silenced where the cut // silences it (mute.mjs soundOnSegment: `muteFrom`, a locked edge), // its `audio` knobs (offset, gain, fades) and the cut's loudness gain. // When the edges cannot be measured, the manifest's play window // (noted). A blur, a montage's phrase cut and the deck are not applied. // context what the cut plays (its play window: the lead-in, the cut) with // N seconds either side (`context`, 1-120, default 5), as recorded: no // gaps, no mute, no knobs -- "what was said around it". // raw a stretch of the recording as recorded: `span` {from, to} in // source seconds (the full exchange), else the clip and the build's // fetch pad either side. No gaps, no mute, no knobs. // // Each cuts from a cached window that HOLDS what it asks for (the build's own // source for a cut; for context and raw the tightest window of the recording // holding the span), clamped to the file and said when none does. // `exportNeeds` says what a context or raw export needs that is not on disk, // as the pads the editor's fetch-window takes (POST /api/report/clip-export // with `fetch: true` runs that fetch first, in the same job). // // Re-encoded, never stream-copied, so every cut is on the asked-for frame: // libx264 crf 18, AAC 192k, +faststart. Run as a umtool job (the route) or // from a terminal (`umtool export`), and either way through the machine's // heavy slot (the CLI takes it: report-to-video/heavy-gate.mjs, a small // declared estimate, so it runs beside others when memory allows). Nothing is // fetched here: a cut with no window on disk is refused with "fetch it first". // // The pure half (names, the plan's ffmpeg arguments) is tested in // clipExport.test.mjs; `exportClip` runs it. import { censorParts } from "umtool-report-to-video/clip-censor"; import { spawn } from "node:child_process"; import { mkdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { gapFilterParts, gappedLength, gapsOf, gapsOnSegment, gapsWithin } from "umtool-report-to-video/gaps"; import { MUTE_FADE, playEdges, soundOnSegment } from "umtool-report-to-video/mute"; import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow } from "umtool-report-to-video/clip-audio"; /** The folder under a project that exports go into. */ export const EXPORTS_DIR = "exports"; /** The kinds of export. */ export const EXPORT_KINDS = Object.freeze(["cut", "context", "raw"]); /** Seconds of context either side (the `context` kind): the default, and the bounds (the editor's fetch pad cap). */ export const EXPORT_CONTEXT = Object.freeze({ default: 5, min: 1, max: 120 }); /** What an export declares to the heavy slot (MB): one short re-encode. */ export const EXPORT_ESTIMATE_MB = 600; /** What a name under exports/ may be: one plain file name, an mp4. */ export const EXPORT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,180}\.mp4$/; const fin = (v) => typeof v === "number" && Number.isFinite(v); const n3 = (v) => Number(Number(v).toFixed(3)).toString(); /** * A few words as a file-name slug: lower case, ASCII, hyphens. The bracketed * ASR notes and bleeps a quote carries (`[ __ ]`, `[ASR; likely 'time']`) * are left out. * * @param {string} text * @param {{ words?: number, max?: number }} [opts] */ export function exportSlug(text, { words = 6, max = 48 } = {}) { const plain = String(text ?? "") .replace(/\[[^\]]*\]/g, " ") .normalize("NFKD") .replace(/[̀-ͯ]/g, "") .toLowerCase() .replace(/['’]/g, "") .replace(/[^a-z0-9]+/g, " ") .trim(); if (!plain) return ""; let out = ""; for (const w of plain.split(/\s+/).slice(0, words)) { const next = out ? `${out}-${w}` : w; if (next.length > max) break; out = next; } return out || plain.slice(0, max).replace(/\s+/g, "-"); } const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }; const ymd = (y, m, d) => `${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`; /** * The day a clip was said, as YYYY-MM-DD: its `date`, else the on-screen * date ("12 Aug 2026"), else the upload date; null when it carries none. * * @param {Record} entry */ export function exportDate(entry) { const d = typeof entry?.date === "string" ? entry.date.trim() : ""; const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(d); if (iso) return `${iso[1]}-${iso[2]}-${iso[3]}`; for (const t of [d, typeof entry?.onscreen?.title === "string" ? entry.onscreen.title.trim() : ""]) { const m = /^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\.?\s+(\d{4})$/.exec(t); if (m && MON[m[2].toLowerCase()]) return ymd(m[3], MON[m[2].toLowerCase()], m[1]); } const u = String(entry?.uploadDate ?? ""); return /^\d{8}$/.test(u) ? ymd(u.slice(0, 4), u.slice(4, 6), u.slice(6, 8)) : null; } /** * The export's file name: `[-ctx | -raw[--]]--.mp4`, * the shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`). * The slug is the quote's first words, else the title's, else the video id; * the date the clip's, else `today` (YYYY-MM-DD). A raw export of a span of * its own (the full exchange) carries the span's whole seconds, so two * exchanges of one clip are two files. * * @param {Record} entry * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, today?: string }} [opts] */ export function exportName(entry, { kind = "cut", context = EXPORT_CONTEXT.default, span = null, today = new Date().toISOString().slice(0, 10) } = {}) { const id = exportSlug(String(entry?.id ?? "clip"), { words: 8, max: 40 }) || "clip"; const date = exportDate(entry) ?? today; const slug = exportSlug(entry?.quote) || exportSlug(entry?.onscreen?.title) || exportSlug(entry?.title) || exportSlug(entry?.video); const tag = kind === "raw" ? span && fin(span.from) && fin(span.to) ? `raw-${Math.floor(span.from)}-${Math.ceil(span.to)}` : "raw" : kind === "context" ? `ctx${Math.round(context)}` : null; return `${[id, tag, date, slug || null].filter(Boolean).join("-")}.mp4`; } /** `context` as seconds inside EXPORT_CONTEXT's bounds, or an error naming them. */ export function contextSeconds(v) { if (v === undefined || v === null || v === "") return EXPORT_CONTEXT.default; const n = Number(v); if (!Number.isFinite(n) || n < EXPORT_CONTEXT.min || n > EXPORT_CONTEXT.max) { throw new ExportRefused(`context is ${EXPORT_CONTEXT.min}–${EXPORT_CONTEXT.max} seconds either side (got ${String(v)})`, 400); } return Math.round(n * 10) / 10; } /** A raw export's span `{from, to}` (source seconds), checked; null when none is asked for. */ export function spanOf(v) { if (v === undefined || v === null) return null; const from = Number(v?.from); const to = Number(v?.to); if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || to - from < 0.5) { throw new ExportRefused("a raw span is {from, to}: source seconds, from ≥ 0, at least half a second", 400); } if (to - from > 1800) throw new ExportRefused("a raw span is at most 30 minutes", 400); return { from: Math.round(from * 100) / 100, to: Math.round(to * 100) / 100 }; } /** * The SOURCE seconds an export asks for, before the file clamps it: a cut's * is its play window (the render may snap it a second either way), a context * export's that ± N, a raw one's its span or the clip ± the fetch pad. * * @param {Record} entry * @param {Record} render * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} opts */ export function exportSpan(entry, render, { kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) { if (kind === "raw") { if (span) return { from: span.from, to: span.to }; const pad = fin(render?.fetchPad) ? render.fetchPad : 3; return { from: Math.max(0, entry.start - pad), to: entry.end + pad }; } const pw = playEdges(entry, render ?? {}); if (kind === "context") return { from: Math.max(0, pw.from - context), to: pw.to + context }; return { from: pw.from, to: pw.to }; } /** * What one export cuts, in SOURCE seconds -- the arithmetic, no I/O. * * @typedef {{ * kind: "cut" | "context" | "raw", * context?: number, span?: { from: number, to: number }, * file: string, fetchStart: number, duration?: number | null, hasVideo?: boolean, * from: number, to: number, * gaps: Array<{ from: number, to: number }>, * mute: number | null, soundFrom: number | null, * audio: null | { offset?: number, gain?: number, fadeIn?: number, fadeOut?: number }, * gainDb: number | null, * fps: number, * edges: "render" | "manifest" | "window", * notes: string[], * }} ExportPlan */ /** * The plan for one clip, from what the caller resolved: the entry and its * render block, the source on disk (`{path, fetchStart}`, the clock aligned), * its probed duration and picture, and -- for a cut -- the render's cut row * (cutPoints.mjs; null or an errored row falls back to the manifest's edges). * * @param {{ entry: Record, render?: Record, source: { path: string, fetchStart: number }, * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record | null, kind?: "cut" | "context" | "raw", * context?: number, span?: { from: number, to: number } | null }} o * @returns {ExportPlan} */ export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null }) { const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30; const fileFrom = source.fetchStart; const fileTo = fin(media.duration) ? source.fetchStart + /** @type {number} */ (media.duration) : Infinity; const notes = []; const base = { kind, file: source.path, fetchStart: source.fetchStart, duration: media.duration ?? null, hasVideo: media.hasVideo !== false, fps, notes, }; if (kind === "raw" || kind === "context") { // As recorded: the span asked for (raw: the full exchange, else the clip // and the fetch pad; context: what the cut plays ± N -- the render's // edges when measured), clamped to the file and said. let want = exportSpan(entry, render, { kind, context, span }); if (kind === "context" && row && !row.missing && !row.error && fin(row.cutStart) && fin(row.cutEnd)) { want = { from: Math.max(0, row.cutStart - context), to: row.cutEnd + context }; } let from = Math.max(fileFrom, want.from); let to = Math.min(fileTo, want.to); if (want.from < fileFrom - 0.05) notes.push(`the cached window starts ${(fileFrom - want.from).toFixed(2)} s after what was asked: from its first frame`); if (want.to > fileTo + 0.05) notes.push(`the cached window ends ${(want.to - fileTo).toFixed(2)} s before what was asked: to its last frame`); if (to < from) to = from; return { ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window", ...(kind === "context" ? { context } : {}), ...(kind === "raw" && span ? { span } : {}), }; } let from; let to; let gaps; let edges; if (row && !row.missing && !row.error && fin(row.cutStart) && fin(row.cutEnd)) { from = row.cutStart; to = row.cutEnd; // Room's muted picture at an edge is nothing heard: a clean clip leaves it off. if (Array.isArray(row.sound) && fin(row.sound[0]) && fin(row.sound[1])) { from = Math.max(from, row.sound[0]); to = Math.min(to, row.sound[1]); } gaps = gapsWithin(Array.isArray(row.gaps) ? row.gaps : [], from, to); edges = "render"; if (row.montage) notes.push("a montage cuts this clip to its phrase in the render; exported as a plain cut"); } else { const pw = playEdges(entry, render); from = pw.from; to = pw.to; gaps = gapsWithin(gapsOf(entry), from, to); edges = "manifest"; notes.push(row?.error ? `the render's edges could not be measured (${row.error}): the manifest's edges` : "the manifest's edges (the render's were not measured)"); } if (from < fileFrom - 0.02) { notes.push(`the cut starts ${(fileFrom - from).toFixed(2)} s before the cached window: from its first frame`); from = fileFrom; } if (to > fileTo + 0.02) { notes.push(`the cut ends ${(to - fileTo).toFixed(2)} s past the cached window: to its last frame`); to = fileTo; } // The gaps on the export's own frame grid (the build's rule), back in source seconds. const local = gapsOnSegment(gaps, from, to - from, fps); gaps = local.map((g) => ({ from: Number((from + g.from).toFixed(6)), to: Number((from + g.to).toFixed(6)) })); const seconds = gappedLength(from, to, gaps); const on = soundOnSegment(entry, render, from, seconds, gaps.length ? gaps : null); const mute = on.mute != null && on.mute < seconds ? on.mute : null; const soundFrom = on.soundFrom != null ? on.soundFrom : null; if (entry?.blur && typeof entry.blur === "object" && render.blur !== "off") notes.push("exported unblurred: the render's blur is not applied"); const gainDb = fin(row?.gainDb) ? row.gainDb : null; return { ...base, from, to, gaps, mute, soundFrom, audio: clipAudioOf(entry), gainDb, edges }; } /** The seconds an export plays: its span less its gaps. */ export const planSeconds = (plan) => gappedLength(plan.from, plan.to, plan.gaps); /** * The ffmpeg arguments for a plan, writing `out`. The picture is cut on the * input (`-ss` / `-to`, the build's cutArgs), so the re-encode starts on the * asked-for frame; the gaps come out with the build's own filter; the sound * is laid on its clock first (AUDIO_ON_CLOCK) and read again at the shifted * window for an `audio.offset`. * * @param {ExportPlan} plan * @param {string} out * @param {{ crf?: number, preset?: string, audioBitrate?: string }} [opts] * @returns {string[]} */ /** The seconds an export plays (planSeconds, before it is declared below). */ const kept0 = (plan) => gappedLength(plan.from, plan.to, plan.gaps); export function exportArgs(plan, out, { crf = 18, preset = "medium", audioBitrate = "192k" } = {}) { const a = Math.max(0, plan.from - plan.fetchStart); const b = Math.max(a, plan.to - plan.fetchStart); const seconds = b - a; const args = ["-nostdin", "-hide_banner", "-v", "error", "-y", "-ss", n3(a), "-to", n3(b), "-i", plan.file]; const shifted = plan.kind === "cut" ? offsetWindow(plan.audio, a, b) : null; let ain = "[0:a]"; if (shifted) { if (shifted.from < 0) args.push("-itsoffset", n3(-shifted.from)); args.push("-ss", n3(Math.max(0, shifted.from)), "-to", n3(shifted.to), "-i", plan.file); ain = "[1:a]"; } const parts = [`${ain}${AUDIO_ON_CLOCK}[aclk]`]; const local = plan.gaps.map((g) => ({ from: g.from - plan.from, to: g.to - plan.from })); const g = gapFilterParts({ gaps: local, seconds, vIn: plan.hasVideo === false ? null : "[0:v]", aIn: "[aclk]" }); parts.push(...g.parts); // Hidden regions (report-to-video clip-censor.mjs): on the picture as the cut hides them, over their spans on this // export's clock (its first frame is plan.from). let vOut = g.v; if (vOut && plan.censor?.regions?.length) { const cp = censorParts(vOut.slice(1, -1), "vcen", plan.censor.regions, { width: plan.censor.width, height: plan.censor.height, from: plan.from, gaps: plan.gaps, seconds: kept0(plan) }); parts.push(...cp); vOut = "[vcen]"; } const kept = planSeconds(plan); const af = []; if (plan.soundFrom != null) af.push(`afade=t=in:st=${n3(plan.soundFrom)}:d=${n3(MUTE_FADE)}`); // The mute's fade ENDS at the mark (mute.mjs): silent from it on. if (plan.mute != null) af.push(`afade=t=out:st=${n3(Math.max(0, plan.mute - MUTE_FADE))}:d=${n3(MUTE_FADE)}`); if (plan.gainDb != null && plan.gainDb !== 0) af.push(`volume=${n3(plan.gainDb)}dB`); af.push(...clipAudioFilters(plan.kind === "cut" ? plan.audio : null, kept)); parts.push(`${g.a}${af.length ? af.join(",") : "anull"}[aout]`); args.push("-filter_complex", parts.join(";")); if (vOut) args.push("-map", vOut === "[0:v]" ? "0:v:0" : vOut); args.push("-map", "[aout]"); if (g.v) args.push("-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p"); args.push("-c:a", "aac", "-b:a", audioBitrate, "-movflags", "+faststart", "-map_metadata", "-1", "-map_chapters", "-1", "-sn", "-dn"); args.push(out); return args; } /** The plan in one line, for the CLI and the route's answer. */ export function planSummary(plan) { const parts = [`${n3(plan.from)}–${n3(plan.to)} s`]; if (plan.gaps.length) parts.push(`${plan.gaps.length} gap${plan.gaps.length === 1 ? "" : "s"} out`); if (plan.mute != null) parts.push(`muted from ${n3(plan.mute)} s`); if (plan.soundFrom != null) parts.push(`sound from ${n3(plan.soundFrom)} s`); parts.push(`${n3(planSeconds(plan))} s`); parts.push( plan.kind === "raw" ? plan.span ? "the span asked for, as recorded" : "the whole window" : plan.kind === "context" ? `the cut with ${plan.context ?? EXPORT_CONTEXT.default} s either side, as recorded` : plan.edges === "render" ? "the render's edges" : "the manifest's edges", ); return parts.join(" · "); } /** * Run ffmpeg; resolves when it exits 0, rejects with its last lines of * stderr otherwise. */ function runFfmpeg(bin, args, { signal } = {}) { return new Promise((resolve, reject) => { const child = spawn(bin, args, { stdio: ["ignore", "ignore", "pipe"], ...(signal ? { signal } : {}) }); let err = ""; child.stderr.on("data", (d) => { err = (err + d.toString()).slice(-4000); }); child.on("error", (e) => reject(e?.code === "ENOENT" ? new Error(`${bin} is not installed`) : e)); child.on("close", (code, sig) => { if (code === 0) resolve(undefined); else reject(new Error(`ffmpeg ${sig ? `was stopped (${sig})` : `exited ${code}`}${err.trim() ? `: ${err.trim().split("\n").slice(-3).join(" ")}` : ""}`)); }); }); } /** An export refused for a reason the caller should show as it is (no window on disk, no such clip). */ export class ExportRefused extends Error { /** @param {string} message @param {number} [status] */ constructor(message, status = 409) { super(message); this.status = status; } } /** Exports being made in this process, by output path: a second ask waits for the first. */ const inflight = new Map(); /** * What a context or raw export of this clip asks for, and whether a cached * window holds it: `{ entry, want, held, padBefore, padAfter }`, the pads as * the editor's fetch-window takes them (from the clip's extent, whole * seconds, at most EXPORT_CONTEXT.max). A cut asks for what its own source * holds (`held` is whether there is one). * * @param {{ id: string, dir: string }} project * @param {string} clipId * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} [opts] */ export async function exportNeeds(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) { const { clipSourceOf } = await import("./cutPoints.mjs"); const got = await clipSourceOf(project, clipId, { take }); if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404); const e = got.entry; if (kind === "cut") return { entry: e, want: null, held: !!got.source, padBefore: 0, padAfter: 0 }; const want = exportSpan(e, got.render, { kind, context, span }); const held = !!(await heldWindow(project, e, want, take)); const pad = (v) => Math.min(EXPORT_CONTEXT.max, Math.max(0, Math.ceil(v))); return { entry: e, want, held, padBefore: pad(e.start - want.from), padAfter: pad(want.to - e.end) }; } /** * The tightest cached window of the clip's recording holding [want.from, want.to] (projectCache: out/clips-raw and the corpus's windows). * A take's clip is looked up through the TAKE's manifest: the corpus dirs listed are its clips' videos, and a clip only the take has * cites a recording the cut may not. */ async function heldWindow(project, entry, want, take = null) { const { projectCache } = await import("./serve.mjs"); const manifest = take ? (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest : null; const cache = await projectCache(project, manifest); return cache.containing(entry.video, want.from + 0.02, want.to - 0.02) ?? null; } /** * Export one clip of a project's cut (or of a take) into `/exports/`. * * @param {{ id: string, dir: string }} project * @param {string} clipId * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, * ffmpeg?: string, today?: string }} [opts] * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "context" | "raw", name: string, rel: string, * abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>} */ export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today, uncensoredRaw = false } = {}) { if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400); const ctx = kind === "context" ? contextSeconds(context) : EXPORT_CONTEXT.default; const sp = kind === "raw" ? spanOf(span) : null; const { clipSourceOf, cutPointsFor } = await import("./cutPoints.mjs"); const { FFMPEG_BIN, alignedClipSource, probeMedia } = await import("umtool-report-to-video/build-video"); const got = await clipSourceOf(project, clipId, { take }); if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404); // A context or raw export is cut from the window that holds what it asks for -- a wider fetch // than the build's own source, often (the full exchange) -- when there is one. /** @type {{ path: string, fetchStart: number, pieced?: { entry: Record } } | null} */ let source = got.source; if (kind !== "cut") { const want = exportSpan(got.entry, got.render, { kind, context: ctx, span: sp }); const win = await heldWindow(project, got.entry, want); if (win) source = await alignedClipSource({ path: win.path, fetchStart: win.from }).then((x) => ({ path: x.path, fetchStart: x.fetchStart }), () => ({ path: win.path, fetchStart: win.from })); } if (!source) { throw new ExportRefused( `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)` + (kind === "cut" ? "" : `; \`umtool export ${project.id} ${clipId} … --fetch\` asks the editor for what this export needs`), 409, ); } const media = await probeMedia(source.path).catch(() => ({ hasVideo: true, duration: null })); let row = null; if (kind === "cut" || kind === "context") { try { row = (await cutPointsFor(project, { take, clips: [clipId] })).clips?.[0] ?? null; } catch (e) { row = { error: e instanceof Error ? e.message : String(e) }; } } // A clip cut from its pieces (cutPoints.mjs piecedDiskSourceOf) is a file on its own clock: // the plan is made on that clock -- the clip and the cut's numbers as the build sees them. const pieced = source.pieced ?? null; const planRow = pieced && row && !row.error && !row.missing && row.pieced ? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps } : row; const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source, media, row: planRow, kind, context: ctx, span: sp }); // HIDDEN REGIONS (report-to-video clip-censor.mjs): a privacy control, so a cut or a context export hides them as // the cut does; a raw export is "as recorded" and is REFUSED for a clip with boxes unless asked for uncensored, // which it then says. const { censorRegionsOf } = await import("umtool-report-to-video/clip-censor"); const regions = media.hasVideo === false ? [] : censorRegionsOf(got.entry, got.render, got.provenance ?? {}); if (regions.length && kind === "raw" && !uncensoredRaw) { throw new ExportRefused(`${clipId} hides ${regions.length} region(s) of its picture (render.censor / its censor): a raw export is as recorded, and would show them -- export the cut or with --context (both hide them), or add --uncensored-raw to export the recording as it is`, 409); } if (regions.length && kind !== "raw") { const { probeDims } = await import("umtool-report-to-video/build-video"); const [width, height] = await probeDims(source.path); plan.censor = { regions, width, height }; plan.notes.push(`${regions.length} region(s) hidden (render.censor / its censor)`); } if (regions.length && kind === "raw") plan.notes.push(`UNCENSORED: ${regions.length} region(s) this clip hides are SHOWN (--uncensored-raw)`); if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422); const name = exportName(got.entry, { kind, context: ctx, span: sp, ...(today ? { today } : {}) }); const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR); const abs = path.join(/* turbopackIgnore: true */ dir, name); const run = inflight.get(abs) ?? (async () => { await mkdir(/* turbopackIgnore: true */ dir, { recursive: true }); const tmp = path.join(/* turbopackIgnore: true */ dir, `.${name}.${process.pid}.part.mp4`); try { await runFfmpeg(ffmpeg ?? FFMPEG_BIN, exportArgs(plan, tmp)); await rename(/* turbopackIgnore: true */ tmp, abs); } catch (e) { await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); throw e; } })(); if (!inflight.has(abs)) { inflight.set(abs, run); run.then(() => inflight.delete(abs), () => inflight.delete(abs)); } await run; const st = await stat(/* turbopackIgnore: true */ abs); return { project: project.id, clip: clipId, take, kind, name, rel: path.posix.join(EXPORTS_DIR, name), abs, size: st.size, mtimeMs: Math.round(st.mtimeMs), seconds: Number(planSeconds(plan).toFixed(3)), summary: planSummary(plan), notes: plan.notes, plan, }; } /** * The job that makes an export (the route's): the editor's fetch first when * `fetch` names the pads a context or raw export still needs (driver.mjs * editorFetchSteps, the bench's own; fetchSteps under UMTOOL_LOCAL_FETCH=1), * then `umtool export … --progress ndjson`, which takes the heavy slot itself * and ends with one `export` event. * * @param {{ id: string, dir: string }} project * @param {string} clipId * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null, uncensoredRaw?: boolean }} o */ export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null, uncensoredRaw = false } = {}) { const { UMTOOL_DIR, editorFetchSteps, fetchSteps, localFetch } = await import("./driver.mjs"); const steps = []; if (fetch) { const pads = { padBefore: fetch.padBefore, padAfter: fetch.padAfter }; steps.push(...(localFetch() ? fetchSteps(project, clipId, pads, { manifestPath }) : editorFetchSteps(project, clipId, pads, { manifestPath }))); } const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : []), ...(uncensoredRaw ? ["--uncensored-raw"] : [])] : []; steps.push({ cwd: UMTOOL_DIR, env: {}, label: `export ${clipId}${kind === "context" ? ` with ${context} s either side` : kind === "raw" ? (span ? ` ${span.from}–${span.to} s, as recorded` : " raw") : ""}`, argv: [process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "export", project.id, clipId, ...kindArgs, ...(take ? ["--take", take] : []), "--progress", "ndjson"], ndjson: true, timeoutMs: 15 * 60_000, }); return steps; } /** * The exports a project holds, newest first: `{name, size, mtimeMs}`. * * @param {string} projectDir */ export async function listExports(projectDir) { const { readdir } = await import("node:fs/promises"); const dir = path.join(/* turbopackIgnore: true */ projectDir, EXPORTS_DIR); const names = await readdir(/* turbopackIgnore: true */ dir).catch(() => []); const out = []; for (const name of names) { if (!EXPORT_NAME_RE.test(name)) continue; const st = await stat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, name)).catch(() => null); if (st?.isFile()) out.push({ name, size: st.size, mtimeMs: Math.round(st.mtimeMs) }); } return out.sort((x, y) => y.mtimeMs - x.mtimeMs); } /** * An export's absolute path, from a name a request carried: one plain mp4 * name under the project's exports/, or null. * * @param {string} projectDir * @param {unknown} name */ export function exportFileOf(projectDir, name) { const n = String(name ?? ""); if (!EXPORT_NAME_RE.test(n) || n.includes("..")) return null; return path.join(/* turbopackIgnore: true */ projectDir, EXPORTS_DIR, n); }