// THE COMBO COUNTER (umtool/docs/report-video.md, "The combo counter"): when a // post item's attachment is one an EARLIER item of the cut already played -- // the same reaction video answering a third person -- a fighting-game badge // pops onto the card as that attachment starts: "COMBO ×2", "×3", … (operator, // 3 Nov: "an effect that shows a combo counter or something when he uses the // same video to reply to someone"). // // WHAT IS A REPEAT. Two attachments are the same when they share, in order of // trust: // // media-id X's own id for the media, from the capture's source url // (`amplify_video/`, `ext_tw_video/`, `tweet_video/`, // pbs `media/`) -- the same upload, attached again // sha256 the file's bytes (capture.json's `media[i].sha256`, trusted when // its `bytes` match the project's copy; else the copy hashed) // audio (opt-in, `match: "audio"`) the sound's fingerprint and its length // (chromaprint's fpcalc, else a coarse energy hash by ffmpeg): the // same clip re-encoded // // Any one tier links two attachments; the links make the groups (a GIF X // re-uploads gets a new id every time, and its bytes are what match). The // prints are read by post-combo-prints.mjs; everything here is PURE -- the // build, Play, the bench and `umtool posts repeats` read the same rules. // // THE COUNT is the use's number in the cut's ORDER (the timeline's, post items // only): the 2nd use is ×2. An item that turns its badge off (`combo: false`) // still counts -- the viewer saw the attachment -- its own badge is not drawn. // The badge shows from `minCount` (default 2). // // render.posts.combo = { on, label, position, color, scale, sfx, minCount, match } // timeline[i].combo = false | { on?, label?, position?, color?, scale?, sfx? } /** The cut's knobs (render.posts.combo) and their defaults. */ export const COMBO_DEFAULTS = Object.freeze({ on: true, label: "COMBO", position: "top-right", color: "#ffcf33", scale: 1, sfx: "off", minCount: 2, match: "file", }); export const COMBO_POSITIONS = Object.freeze(["top-right", "top-left", "bottom-right", "bottom-left", "center"]); /** The bundled sounds (assets/combo/.wav), and `off`. */ export const COMBO_SFX = Object.freeze(["off", "hit", "coin"]); /** How deep the match goes: `id` the media id alone, `file` + the bytes, `audio` + the sound. */ export const COMBO_MATCH = Object.freeze(["id", "file", "audio"]); export const COMBO_TIERS = Object.freeze(["media-id", "sha256", "audio"]); export const COMBO_LABEL_MAX = 16; export const COMBO_SCALE = Object.freeze({ min: 0.4, max: 2.5 }); export const COMBO_MIN_COUNT = Object.freeze({ min: 2, max: 20 }); /** The knobs a post item may override (minCount and match are the cut's). */ export const COMBO_ITEM_KEYS = Object.freeze(["on", "label", "position", "color", "scale", "sfx"]); /** * THE MOTION, in seconds from the attachment's start: a slam in from small to * an OVERSHOOT (1.32×), a spring back through 0.86× to rest, a shake that dies * away, the hold, then a fade out growing a little. */ export const COMBO_TIMING = Object.freeze({ fadeIn: 0.06, pop: 0.12, settle: 0.34, shake: 0.56, out: 2.2, end: 2.6 }); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const r3 = (v) => Math.round(v * 1000) / 1000 + 0; const HEX_RE = /^#[0-9a-fA-F]{6}$/; // --------------------------------------------------------------------------- // The media id (tier 1) // --------------------------------------------------------------------------- /** * X's id for a media url, `/` (`amplify_video/2117…`, * `tweet_video/HWCOFy3bwAAsJJS`, `media/HWEqGNfWYAAbqx_`), or null. */ export function xMediaIdOf(url) { if (typeof url !== "string" || !url) return null; let u; try { u = new URL(url); } catch { return null; } if (!/(^|\.)twimg\.com$/.test(u.hostname)) return null; const v = /^\/(amplify_video|ext_tw_video|tweet_video)\/([A-Za-z0-9_-]+)/.exec(u.pathname); if (v) return `${v[1]}/${v[2]}`; const thumb = /^\/(amplify_video_thumb|ext_tw_video_thumb|tweet_video_thumb)\/([A-Za-z0-9_-]+)/.exec(u.pathname); if (thumb) return `${thumb[1].replace(/_thumb$/, "")}/${thumb[2]}`; const pic = /^\/media\/([A-Za-z0-9_-]+)/.exec(u.pathname); return pic ? `media/${pic[1]}` : null; } // --------------------------------------------------------------------------- // The audio print (tier 3): compared pure // --------------------------------------------------------------------------- const popcount = (x) => { let v = x >>> 0; v -= (v >>> 1) & 0x55555555; v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24; }; /** * How alike two audio prints are, 0-1: the best share of equal bits over * small shifts of one against the other (`bits` per word: 32 for chromaprint, * the energy hash's own). Null when they overlap too little to say. * * @param {{ words: number[], bits?: number }} a * @param {{ words: number[], bits?: number }} b */ export function printSimilarity(a, b, o = {}) { const x = Array.isArray(a?.words) ? a.words : []; const y = Array.isArray(b?.words) ? b.words : []; const bits = a?.bits ?? 32; // About a second of overlap either way: chromaprint's word is ~0.12 s, the energy hash's 1 s. const { maxShift = bits >= 32 ? 8 : 1, minOverlap = bits >= 32 ? 8 : 3 } = o; let best = null; for (let o = -maxShift; o <= maxShift; o += 1) { let same = 0; let n = 0; for (let i = Math.max(0, -o); i < x.length && i + o < y.length; i += 1) { same += bits - popcount((x[i] ^ y[i + o]) & (bits >= 32 ? 0xffffffff : (1 << bits) - 1)); n += 1; } if (n < minOverlap) continue; const s = same / (n * bits); if (best === null || s > best) best = s; } return best; } /** The share of bits two prints must agree on to be the same sound (chromaprint's; the coarse hash's is its own). */ export const AUDIO_MATCH = Object.freeze({ chromaprint: 0.85, energy: 0.8 }); /** Two attachments' sounds the same: the prints alike and the lengths within 0.3 s (or 3%). */ export function audioSame(a, b) { if (!isObj(a) || !isObj(b) || a.kind !== b.kind) return false; if (fin(a.seconds) && fin(b.seconds) && Math.abs(a.seconds - b.seconds) > Math.max(0.3, 0.03 * Math.max(a.seconds, b.seconds))) return false; const s = printSimilarity(a, b); return s !== null && s >= (AUDIO_MATCH[a.kind] ?? 0.85); } // --------------------------------------------------------------------------- // The groups and the count // --------------------------------------------------------------------------- /** The post items of a timeline in its order, with an attachment. */ export const comboItems = (timeline) => (Array.isArray(timeline) ? timeline : []).filter((e) => isObj(e) && e.type === "post" && typeof e.id === "string" && Array.isArray(e.media) && e.media.length); /** The tiers a `match` uses. */ export const tiersOf = (match) => (match === "id" ? ["media-id"] : match === "audio" ? ["media-id", "sha256", "audio"] : ["media-id", "sha256"]); /** The strongest tier on which two prints agree, or null. */ export function linkTier(p, q, tiers = tiersOf("file")) { if (!isObj(p) || !isObj(q)) return null; if (tiers.includes("media-id") && p.mediaId && p.mediaId === q.mediaId) return "media-id"; if (tiers.includes("sha256") && p.sha256 && p.sha256 === q.sha256) return "sha256"; if (tiers.includes("audio") && p.audio && q.audio && audioSame(p.audio, q.audio)) return "audio"; return null; } /** * THE REPEAT GROUPS, pure: every attachment that another item of the cut * also plays. `prints(itemId, i)` is attachment i's print (`{ mediaId?, * sha256?, audio? }`, post-combo-prints.mjs). Each group's members are in * the cut's order, one per item (an item with the attachment twice is one * use), numbered from 1, each with the strongest tier linking it to an * earlier member (`tier`, null for the first). * * @param {Array>} timeline * @param {(id: string, i: number) => Record | null | undefined} prints * @param {{ match?: string }} [o] * @returns {Array<{ key: string, tiers: string[], members: Array<{ id: string, i: number, n: number, post: string|null, date: string|null, tier: string|null }> }>} */ export function repeatGroups(timeline, prints, { match = COMBO_DEFAULTS.match } = {}) { const tiers = tiersOf(match); const items = comboItems(timeline); const atts = []; items.forEach((e, order) => e.media.forEach((m, i) => atts.push({ id: e.id, i, order, entry: e, p: prints(e.id, i) ?? null }))); // Union-find over the attachments: any tier links two. const up = atts.map((_, k) => k); const find = (k) => (up[k] === k ? k : (up[k] = find(up[k]))); for (let a = 0; a < atts.length; a += 1) { for (let b = a + 1; b < atts.length; b += 1) { if (atts[a].id === atts[b].id && atts[a].i === atts[b].i) continue; if (linkTier(atts[a].p, atts[b].p, tiers)) up[find(b)] = find(a); } } const byRoot = new Map(); atts.forEach((x, k) => { const r = find(k); if (!byRoot.has(r)) byRoot.set(r, []); byRoot.get(r).push(x); }); const groups = []; for (const list of byRoot.values()) { // One use per item: its first attachment in the group. const seen = new Set(); const uses = list.sort((a, b) => a.order - b.order || a.i - b.i).filter((x) => (seen.has(x.id) ? false : seen.add(x.id))); if (uses.length < 2) continue; const members = uses.map((x, n) => { let tier = null; for (let j = 0; j < n; j += 1) { const t = linkTier(x.p, uses[j].p, tiers); if (t && (tier === null || COMBO_TIERS.indexOf(t) < COMBO_TIERS.indexOf(tier))) tier = t; } // Linked only through a later member (a chain): the weakest tier of the group says how. return { id: x.id, i: x.i, n: n + 1, post: typeof x.entry.post === "string" ? x.entry.post : null, date: typeof x.entry.date === "string" ? x.entry.date : null, tier, src: typeof x.entry.media[x.i]?.src === "string" ? x.entry.media[x.i].src : null }; }); const tiersUsed = [...new Set(members.map((m) => m.tier).filter(Boolean))].sort((a, b) => COMBO_TIERS.indexOf(a) - COMBO_TIERS.indexOf(b)); groups.push({ key: "", tiers: tiersUsed, members }); } groups.sort((a, b) => items.findIndex((e) => e.id === a.members[0].id) - items.findIndex((e) => e.id === b.members[0].id)); groups.forEach((g, k) => (g.key = `g${k + 1}`)); return groups; } /** * The cut's knobs with every default filled in (render.posts.combo), and an * item's overrides on top (`combo: false` is `{ on: false }`). */ export function comboKnobs(render, entry = null) { const r = isObj(render?.posts) && isObj(render.posts.combo) ? render.posts.combo : {}; const own = entry?.combo === false ? { on: false } : isObj(entry?.combo) ? entry.combo : {}; const pick = Object.fromEntries(COMBO_ITEM_KEYS.filter((k) => own[k] !== undefined).map((k) => [k, own[k]])); return { ...COMBO_DEFAULTS, ...r, ...pick }; } /** Whether use `count` of item `entry` draws its badge: the cut's on, the item's own, count ≥ minCount. */ export function comboShow(count, render, entry = null) { const cut = comboKnobs(render); return cut.on !== false && comboKnobs(render, entry).on !== false && count >= Math.max(COMBO_MIN_COUNT.min, cut.minCount); } /** * The combo of an item as it stands NOW (the bench: its `combo` edited, not * yet saved): its count and attachment as counted, its knobs and `show` read * again from `render` and `entry`. */ export const liveCombo = (combo, render, entry) => (combo ? { ...combo, knobs: comboKnobs(render, entry), show: comboShow(combo.count, render, entry) } : null); /** * EACH ITEM's COMBO, pure: `{ [itemId]: { count, media, group, show, knobs, * members } }` for every item in a repeat group -- `count` its use's number, * `media` the attachment it repeats (the first of its attachments with an * earlier use; else its first in a group), `show` whether its badge is drawn * (the cut's `on`, the item's own, count ≥ minCount). */ export function comboCounts(timeline, groups, render = undefined) { const out = {}; const byId = new Map((Array.isArray(timeline) ? timeline : []).filter(isObj).map((e) => [e.id, e])); // The item's repeat: an attachment with an earlier use before one that is a first, then the lower index. const better = (m, had) => (m.n >= 2) !== (had.count >= 2) ? m.n >= 2 : m.i < had.media; for (const g of groups) { for (const m of g.members) { const had = out[m.id]; if (had && !better(m, had)) continue; const entry = byId.get(m.id); const knobs = comboKnobs(render, entry); out[m.id] = { count: m.n, media: m.i, group: g.key, tier: m.tier, show: comboShow(m.n, render, entry), knobs, members: g.members.map(({ id, i, n, post, date, tier }) => ({ id, i, n, post, date, tier })), }; } } return out; } /** The text a badge draws: its label and "×". */ export const comboText = (count, knobs = COMBO_DEFAULTS) => ({ label: String(knobs.label ?? COMBO_DEFAULTS.label), count: `×${count}` }); /** When the badge pops, on the item's clock: the start of the step that plays attachment `media` (null: it never plays). */ export function comboStart(plan, media) { const st = (Array.isArray(plan?.steps) ? plan.steps : []).find((s) => (s.items ?? []).some((m) => m.i === media)); return st && fin(st.at) ? r3(st.at) : null; } // --------------------------------------------------------------------------- // The motion // --------------------------------------------------------------------------- const easeOutCubic = (u) => 1 - (1 - u) ** 3; /** * The badge at `t` seconds after it pops, pure: `{ scale, x, y, rotate, * opacity }` (x, y px of a 1080-high frame, before `k`; rotate degrees), or * null when it is not up. `mirror` tilts it the other way (a left corner). */ export function comboFrame(t, { mirror = false } = {}) { const T = COMBO_TIMING; if (!fin(t) || t < 0 || t >= T.end) return null; let scale; if (t < T.pop) scale = 0.3 + (1.32 - 0.3) * easeOutCubic(t / T.pop); else if (t < T.settle) { const u = (t - T.pop) / (T.settle - T.pop); scale = 1 + 0.32 * (1 - u) ** 2 * Math.cos(3 * Math.PI * u); } else if (t < T.out) scale = 1; else scale = 1 + 0.12 * ((t - T.out) / (T.end - T.out)); const opacity = t < T.fadeIn ? t / T.fadeIn : t >= T.out ? 1 - (t - T.out) / (T.end - T.out) : 1; const d = t >= T.pop && t < T.shake ? 1 - (t - T.pop) / (T.shake - T.pop) : 0; const x = 14 * d * Math.sin(2 * Math.PI * 24 * t); const y = 9 * d * Math.sin(2 * Math.PI * 31 * t + 1); const tilt = mirror ? 7 : -7; const rotate = tilt + 4 * d * Math.sin(2 * Math.PI * 19 * t); return { scale: r3(scale), x: r3(x), y: r3(y), rotate: r3(rotate), opacity: r3(Math.max(0, Math.min(1, opacity))) }; } /** The badge's CSS transform for a frame (`k`: px per 1080-frame px). */ export const comboTransform = (f, k = 1) => `translate(${r3(f.x * k)}px, ${r3(f.y * k)}px) rotate(${f.rotate}deg) scale(${f.scale})`; // --------------------------------------------------------------------------- // Its box and its look // --------------------------------------------------------------------------- /** The badge's size at rest, px of the item's box: label over count, sized from their characters. */ export function comboSize(count, knobs, boxHeight) { const k = (boxHeight / 1080) * (fin(knobs?.scale) ? knobs.scale : 1); const { label, count: n } = comboText(count, knobs); const N = 150 * k; const L = 48 * k; const w = Math.max(label.length * 0.66 * L + 0.14 * L * label.length, n.length * 0.62 * N) + 48 * k; const h = (label ? L * 1.1 : 0) + N * 0.98 + 30 * k; const even = (v) => Math.max(2, Math.ceil(v / 2) * 2); return { width: even(w), height: even(h), number: Math.round(N), label: Math.round(L), k }; } /** * WHERE IT SITS, px of the item's box: centred on the attachment's corner * (`position`), pulled in by a third of its size so it overlaps the picture, * kept inside the box. `region` is what the build draws its frames in: the * badge at its biggest, tilted and shaken, around the same centre. * * @param {{ x: number, y: number, width: number, height: number }} media the attachment's box (stepBoxes) * @param {{ width: number, height: number }} box the item's box */ export function comboPlace(count, knobs, media, box) { const s = comboSize(count, knobs, box.height); const pos = COMBO_POSITIONS.includes(knobs?.position) ? knobs.position : COMBO_DEFAULTS.position; const left = pos.endsWith("left"); const top = pos.startsWith("top"); let cx = pos === "center" ? media.x + media.width / 2 : left ? media.x + s.width * 0.18 : media.x + media.width - s.width * 0.18; let cy = pos === "center" ? media.y + media.height / 2 : top ? media.y + s.height * 0.12 : media.y + media.height - s.height * 0.12; // The region: the badge at 1.32×, tilted to 11°, shaken 14 px -- its bounding box, even-sized -- kept in the box. const a = (11 * Math.PI) / 180; const big = 1.32; const rw = big * (s.width * Math.cos(a) + s.height * Math.sin(a)) + 2 * 14 * s.k + 4; const rh = big * (s.width * Math.sin(a) + s.height * Math.cos(a)) + 2 * 9 * s.k + 4; const even = (v) => Math.max(2, Math.ceil(v / 2) * 2); const region = { width: Math.min(even(rw), Math.floor(box.width / 2) * 2), height: Math.min(even(rh), Math.floor(box.height / 2) * 2) }; cx = Math.min(box.width - region.width / 2, Math.max(region.width / 2, cx)); cy = Math.min(box.height - region.height / 2, Math.max(region.height / 2, cy)); region.x = Math.round(cx - region.width / 2); region.y = Math.round(cy - region.height / 2); return { center: { x: r3(cx), y: r3(cy) }, size: s, region, mirror: left }; } const esc = (s) => String(s ?? "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => `\\${c === "\n" ? "a " : c}`); function shade(hex, to, t) { const h = HEX_RE.test(hex) ? hex.slice(1) : COMBO_DEFAULTS.color.slice(1); const g = HEX_RE.test(to) ? to.slice(1) : "000000"; const c = [0, 2, 4].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) + (parseInt(g.slice(i, i + 2), 16) - parseInt(h.slice(i, i + 2), 16)) * t)); return `#${c.map((v) => v.toString(16).padStart(2, "0")).join("")}`; } /** * THE BADGE's MARKUP, the same in the build's frames and in Play: a `
${label ? `${esc(label)}` : ""}${esc(n)}
`; } // --------------------------------------------------------------------------- // The validators // --------------------------------------------------------------------------- function knobErrors(o, where, keys) { const errors = []; for (const k of Object.keys(o)) if (!keys.includes(k)) errors.push(`${where}.${k} is not a combo knob (${keys.join(", ")})`); if (o.on !== undefined && typeof o.on !== "boolean") errors.push(`${where}.on must be true or false`); if (o.label !== undefined && !(typeof o.label === "string" && o.label.length <= COMBO_LABEL_MAX && !/[\n<>]/.test(o.label))) errors.push(`${where}.label must be a short line (at most ${COMBO_LABEL_MAX} characters; "" for the count alone)`); if (o.position !== undefined && !COMBO_POSITIONS.includes(o.position)) errors.push(`${where}.position must be one of ${COMBO_POSITIONS.join(", ")}`); if (o.color !== undefined && !(typeof o.color === "string" && HEX_RE.test(o.color))) errors.push(`${where}.color must be a #rrggbb colour`); if (o.scale !== undefined && !(fin(o.scale) && o.scale >= COMBO_SCALE.min && o.scale <= COMBO_SCALE.max)) errors.push(`${where}.scale must be ${COMBO_SCALE.min}–${COMBO_SCALE.max}`); if (o.sfx !== undefined && !COMBO_SFX.includes(o.sfx)) errors.push(`${where}.sfx must be one of ${COMBO_SFX.join(", ")}`); if (o.minCount !== undefined && !(Number.isInteger(o.minCount) && o.minCount >= COMBO_MIN_COUNT.min && o.minCount <= COMBO_MIN_COUNT.max)) errors.push(`${where}.minCount must be a whole number ${COMBO_MIN_COUNT.min}–${COMBO_MIN_COUNT.max} (the use the badge first shows on)`); if (o.match !== undefined && !COMBO_MATCH.includes(o.match)) errors.push(`${where}.match must be one of ${COMBO_MATCH.join(", ")}`); return errors; } /** The keys `render.posts` holds, each its own module's. */ export const POSTS_RENDER_KEYS = ["combo", "redact", "slurs", "scene", "clock", "progress", "panel", "join", "linkVisit", "threadMap"]; /** Every reason `render.posts.combo` cannot be built. */ export function validatePostComboRender(render) { const p = render?.posts; if (p === undefined || p === null) return []; if (!isObj(p)) return ["render.posts must be an object (its `combo` knobs)"]; // render.posts is shared: `redact`, `slurs`, `clock` and `progress` are post-redact.mjs's (validatePostsRender checks // them), `scene` post-media-scene.mjs's, `panel` post-item.mjs's, `join` post-join.mjs's, `linkVisit` // post-link-visit.mjs's, `threadMap` post-branch-map.mjs's -- each validated by its own module. A key none of // them owns (a typo) is refused here. (`posts progress auto` wrote a `progress` this list refused: every cut // with the cut's progress bar failed its lint, 4 Nov.) const errors = Object.keys(p).filter((k) => !POSTS_RENDER_KEYS.includes(k)).map((k) => `render.posts.${k} is not a knob (${POSTS_RENDER_KEYS.join(", ")})`); if (p.combo === undefined) return errors; if (!isObj(p.combo)) return [...errors, "render.posts.combo must be an object of knobs"]; return [...errors, ...knobErrors(p.combo, "render.posts.combo", Object.keys(COMBO_DEFAULTS))]; } /** Every reason one post item's `combo` cannot be built (false, or its overrides). */ export function validatePostCombo(e) { if (e?.combo === undefined || e.combo === false) return []; const where = `timeline ${e?.id ?? "?"}.combo`; if (!isObj(e.combo)) return [`${where} must be false (no badge on this item) or an object of knobs`]; return knobErrors(e.combo, where, [...COMBO_ITEM_KEYS]); } /** The cut's: every post item's combo and render.posts.combo (lint.mjs). */ export function validatePostCombos(manifest) { const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; return [...validatePostComboRender(manifest?.render), ...tl.filter((e) => e?.type === "post").flatMap((e) => validatePostCombo(e))]; }