// THE LOOK of a highlights cut (release 36 lane C): three opt-in render keys // and one clip key, validated here (the build's validators and the lint call // validateLook, as they call validateTransitionStyle), and the pure pieces the // build draws them with. // // render.captions {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"} // burned-in captions, coloured and placed by who speaks // (reactions.json's turns and roles), 2-6 words a line // render.loudness {target: -16} (LUFS, -30 to -8) // each clip's cut measured (ebur128) and brought to the // target with one gain and a limiter (montage.mjs's // loudnessGain + levelFilters) // clip.vertical {crop: [x, y, w, h], aspect?} fractions of the source // picture: the box a vertical short (1080x1920) is cut from; // `aspect` is the source's width/height (16/9 when absent) // // Absent (or null) = off, and the render is byte for byte what it was. // // THE CAPTION COLOURS are fixed, not the palette's: a caption has to read on // any footage, and a person tells the voices apart by colour first. // host #FFC840 amber bottom left // subject #6FD3FF sky bottom right // other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn) // Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR. // The checks (captions, loudness, the vertical crop, room) and their bounds // are the look's rules (common lib/report/look.mjs, release 38): re-exported // here, so the writer, the build and the video assistant refuse the same things. import { DEFAULT_SOURCE_ASPECT, VERTICAL_RATIO, loudnessTargetOf } from "yt-dlp-transcript-common/lib/report/look.mjs"; export { CAPTION_LABEL_MAX, CAPTION_SIZES, CAPTION_STYLES, DEFAULT_SOURCE_ASPECT, LOUDNESS_MAX, LOUDNESS_MIN, VERTICAL_RATIO, VERTICAL_TOLERANCE, captionsOn, loudnessOn, loudnessTargetOf, validateCaptions, validateLoudness, validateLook, validateVertical, verticalErrors, } from "yt-dlp-transcript-common/lib/report/look.mjs"; export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]); export const CAPTION_COLOURS = Object.freeze({ host: "#FFC840", subject: "#6FD3FF", other: "#F6F1E6" }); /** ASS alignment (numpad): host bottom-left, subject bottom-right, other bottom-centre. */ export const CAPTION_ALIGN = Object.freeze({ host: 1, subject: 3, other: 2 }); /** The font, vendored in fonts/ (IBM Plex Sans, OFL): libass is pointed at that directory. */ export const CAPTION_FONT = "IBM Plex Sans"; /** Words a line: at least (unless a speaker change or the clip's end forces fewer), at most. */ export const CAPTION_MIN_WORDS = 2; export const CAPTION_MAX_WORDS = 6; /** A gap between two words this long (s) ends a line that has its minimum. */ export const CAPTION_PAUSE = 0.45; /** How long a line stays up after its last word (s), never past the next line. */ export const CAPTION_HOLD = 0.3; /** A short's target when the cut sets none. */ export const SHORT_LOUDNESS = -16; export const SHORT_WIDTH = 1080; export const SHORT_HEIGHT = 1920; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); // --------------------------------------------------------------------------- // The vertical crop. // --------------------------------------------------------------------------- /** The centred, full-height 9:16 box on a source of `aspect` (w/h), as fractions. */ export function defaultCrop(aspect = DEFAULT_SOURCE_ASPECT) { const a = num(aspect) && aspect > 0 ? aspect : DEFAULT_SOURCE_ASPECT; let w = VERTICAL_RATIO / a; let h = 1; if (w > 1) { h = a / VERTICAL_RATIO; w = 1; } const r = (n) => Number(n.toFixed(4)); return [r((1 - w) / 2), r((1 - h) / 2), r(w), r(h)]; } const even = (n) => Math.max(2, 2 * Math.round(n / 2)); /** * A crop (fractions) as pixels of a `srcW`×`srcH` picture, exactly 9:16 and * even: the box's height kept (its width made 9/16 of it, about its centre), * clamped inside the picture. `{x, y, w, h}`. */ export function cropPixels(crop, srcW, srcH) { const [fx, fy, fw, fh] = Array.isArray(crop) && crop.length === 4 ? crop : defaultCrop(srcW / srcH); let h = Math.min(srcH, Math.max(2, fh * srcH)); let w = (h * 9) / 16; if (w > srcW) { w = srcW; h = (w * 16) / 9; } w = Math.min(even(w), srcW - (srcW % 2)); h = Math.min(even(h), srcH - (srcH % 2)); const cx = (fx + fw / 2) * srcW; const cy = (fy + fh / 2) * srcH; const x = Math.round(Math.max(0, Math.min(srcW - w, cx - w / 2))); const y = Math.round(Math.max(0, Math.min(srcH - h, cy - h / 2))); return { x, y, w, h }; } /** The ffmpeg chain that cuts a short's picture: the crop, scaled to fill 1080x1920. */ export function verticalFilters(crop, srcW, srcH, { width = SHORT_WIDTH, height = SHORT_HEIGHT, fps } = {}) { const b = cropPixels(crop, srcW, srcH); return [`crop=${b.w}:${b.h}:${b.x}:${b.y}`, `scale=${width}:${height}:flags=lanczos`, "setsar=1", ...(fps ? [`fps=${fps}`] : [])]; } /** * The render a short is made with: 1080x1920, no header, footer, QR, rail or * deck; speaker captions at size "l" (the cut's labels kept); the cut's * loudness target, else SHORT_LOUDNESS. */ export function shortRender(render = {}) { const { chrome: _c, rail: _r, chromeEngine: _e, brand: _b, montage: _m, ...rest } = render; const labels = isObj(render.captions?.labels) ? { labels: render.captions.labels } : {}; return { ...rest, width: SHORT_WIDTH, height: SHORT_HEIGHT, headerHeight: 0, footerHeight: 0, qr: false, captions: { style: "speakers", ...labels, size: "l" }, loudness: { target: loudnessTargetOf(render) ?? SHORT_LOUDNESS }, }; } // --------------------------------------------------------------------------- // The captions: words and turns to lines, lines to an ASS document. // --------------------------------------------------------------------------- /** The label reactions.json gives a speaker it was never told about (common/lib/clips/reactions.mjs labelOf). */ export const defaultSpeakerLabel = (role, index) => (role === "host" ? "Host" : role === "subject" ? "Subject" : `Speaker ${Number(index) + 1}`); /** * What a speaker's lines are headed with, or null: the cut's * `render.captions.labels[role]` when set, else the speaker's own label when * a person gave it one (anything but the default) -- voices are told apart by * colour and side, and named only when somebody names them. */ export function speakerCaptionLabel(speaker, captions) { const role = CAPTION_ROLES.includes(speaker?.role) ? speaker.role : "other"; const set = captions?.labels?.[role]; if (typeof set === "string" && set.trim()) return set.trim(); const own = typeof speaker?.label === "string" ? speaker.label.trim() : ""; if (own && own !== defaultSpeakerLabel(speaker?.role, speaker?.index)) return own; return null; } /** * Which speaker says a word: the turn its middle is in; else the turn whose * edge is nearest, within `reach` seconds; else null. */ export function speakerAt(turns, start, end, reach = 0.6) { const mid = (start + end) / 2; let best = null; let gap = Infinity; for (const t of turns ?? []) { if (mid >= t.start && mid <= t.end) return t.speaker; const d = mid < t.start ? t.start - mid : mid - t.end; if (d < gap) { gap = d; best = t.speaker; } } return gap <= reach ? best : null; } /** A word as a caption shows it: no ASS override braces or backslashes, trimmed. */ export const captionText = (w) => String(w ?? "").replace(/[{}\\]/g, "").replace(/\s+/g, " ").trim(); /** * The caption lines of one segment. * * @param {{ words: Array<{text: string, start: number, end: number}>, turns?: Array<{start: number, end: number, speaker: number}>, * speakers?: Array<{index: number, role?: string, label?: string}>, captions?: object, seconds?: number, * maxChars?: number }} o every time in the segment's seconds * @returns {Array<{start: number, end: number, text: string, role: string, speaker: number|null, label: string|null}>} */ export function captionLines({ words, turns = [], speakers = [], captions = {}, seconds = Infinity, maxChars = 40 }) { const roleOf = (sp) => { const s = speakers.find((x) => x?.index === sp); return CAPTION_ROLES.includes(s?.role) ? s.role : "other"; }; const used = (words ?? []) .map((w) => ({ text: captionText(w.text), start: Number(w.start), end: Number(w.end) })) .filter((w) => w.text && Number.isFinite(w.start) && Number.isFinite(w.end) && w.end > 0 && w.start < seconds) .map((w) => ({ ...w, start: Math.max(0, w.start), end: Math.min(seconds, Math.max(w.start, w.end)) })) .sort((a, b) => a.start - b.start); const groups = []; let cur = null; for (const w of used) { const speaker = speakerAt(turns, w.start, w.end); const prev = cur?.words[cur.words.length - 1]; const chars = cur ? cur.words.reduce((n, x) => n + x.text.length + 1, 0) + w.text.length : 0; const split = !cur || speaker !== cur.speaker || cur.words.length >= CAPTION_MAX_WORDS || (cur.words.length >= CAPTION_MIN_WORDS && (w.start - prev.end >= CAPTION_PAUSE || chars > maxChars)); if (split) { cur = { speaker, words: [w] }; groups.push(cur); } else cur.words.push(w); } const lines = groups.map((g, i) => { const sp = speakers.find((x) => x?.index === g.speaker) ?? (g.speaker == null ? null : { index: g.speaker }); const role = g.speaker == null ? "other" : roleOf(g.speaker); // A label heads the first line of each turn (the first, or a change of voice). const first = i === 0 || groups[i - 1].speaker !== g.speaker; return { start: g.words[0].start, end: g.words[g.words.length - 1].end, text: g.words.map((x) => x.text).join(" "), role, speaker: g.speaker ?? null, label: first && sp ? speakerCaptionLabel({ ...sp, role }, captions) : null, }; }); for (let i = 0; i < lines.length; i += 1) { const next = lines[i + 1]; lines[i].end = Math.min(seconds, next ? Math.max(lines[i].end, Math.min(next.start, lines[i].end + CAPTION_HOLD)) : lines[i].end + CAPTION_HOLD); if (lines[i].end - lines[i].start < 0.2) lines[i].end = Math.min(seconds, lines[i].start + 0.2); } return lines; } /** Seconds as an ASS time, h:mm:ss.cc (centiseconds, rounded). */ export function assTime(t) { const cs = Math.max(0, Math.round(t * 100)); const h = Math.floor(cs / 360000); const m = Math.floor((cs % 360000) / 6000); const s = Math.floor((cs % 6000) / 100); const c = cs % 100; return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(c).padStart(2, "0")}`; } /** `#RRGGBB` as an ASS colour, `&HAABBGGRR`. */ export function assColour(hex, alpha = 0) { const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex)); if (!m) throw new Error(`not a #rrggbb colour: ${hex}`); const a = Math.max(0, Math.min(255, Math.round(alpha))).toString(16).padStart(2, "0"); return `&H${a}${m[3]}${m[2]}${m[1]}`.toUpperCase(); } /** The caption geometry for a frame: font size, outline, margins (px). */ export function captionGeometry({ width, height, size = "m", bottom = 0 }) { const vertical = height > width; const base = Math.min(width, height); const fontSize = Math.round(base * (size === "l" ? 0.075 : 0.052)); return { fontSize, outline: Math.max(1, Math.round(fontSize * 0.055)), shadow: Math.max(0, Math.round(fontSize * 0.03)), marginH: Math.round(width * (vertical ? 0.06 : 0.05)), // A short's captions sit above the bottom fifth (a phone app's own controls). marginV: Math.round(bottom + height * (vertical ? 0.2 : 0.07)), // Characters a line, so a line never wraps at this size (about 55 % of the width). maxChars: Math.max(12, Math.floor((width * (vertical ? 0.88 : 0.55)) / (fontSize * 0.52))), }; } /** * The ASS document for a segment's lines. One style per role (its colour and * side); a label is the line's head, smaller. No wrapping: the lines are * already short. */ export function assDocument(lines, { width, height, size = "m", bottom = 0, font = CAPTION_FONT } = {}) { const g = captionGeometry({ width, height, size, bottom }); const style = (role) => `Style: ${role},` + [ font, g.fontSize, assColour(CAPTION_COLOURS[role]), "&H000000FF", assColour("#000000"), assColour("#000000", 0x80), -1, 0, 0, 0, 100, 100, 0, 0, 1, g.outline, g.shadow, CAPTION_ALIGN[role], g.marginH, g.marginH, g.marginV, 1, ].join(","); const labelSize = Math.round(g.fontSize * 0.62); const events = lines.map((l) => { const head = l.label ? `{\\fs${labelSize}}${captionText(l.label)}{\\fs${g.fontSize}} ` : ""; return `Dialogue: 0,${assTime(l.start)},${assTime(l.end)},${l.role},,0,0,0,,${head}${captionText(l.text)}`; }); return [ "[Script Info]", "ScriptType: v4.00+", `PlayResX: ${width}`, `PlayResY: ${height}`, "WrapStyle: 2", "ScaledBorderAndShadow: yes", "YCbCr Matrix: None", "", "[V4+ Styles]", "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding", ...CAPTION_ROLES.map(style), "", "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text", ...events, "", ].join("\n"); } /** * A path as a filter option value, single-quoted (as the header's `fontfile` * is). A path with a quote or a colon in it cannot be said this way: refused. */ export function filterPath(p) { const s = String(p); if (/[':\\]/.test(s)) throw new Error(`captions: ${s} has a quote, a colon or a backslash in it, which a filter option cannot carry`); return `'${s}'`; } /** The `ass=` filter that burns a document in, its fonts from `fontsDir`. */ export const assFilter = (file, fontsDir) => `ass=filename=${filterPath(file)}${fontsDir ? `:fontsdir=${filterPath(fontsDir)}` : ""}`;