// The chat signal (release 36 B2): a live stream's chat replay as a second // ear for the clip finder. When the room laughs, the chat says so — a burst of // "lol", "KEKW", 😂 — a few seconds AFTER the moment (the viewers watch the // stream late, and type). From `live_chat.cues.json` (the editor writes it // beside a YouTube video: common/controller/normalizeLiveChat.ts), pure apart // from the one reader: // // bins CHAT_BIN_S bins over the recording: messages, and messages // holding a laugh token (isChatLaugh) // the lag the chat-laugh series cross-correlated with the laugh scan's // score (CED), searched 0..CHAT_LAG_MAX_S; a weak peak (or no // scan) → CHAT_LAG_DEFAULT_S // moments a bin with at least CHAT_BURST_MIN laughs and CHAT_BURST_RATIO // × the local median (±CHAT_MEDIAN_HALF_S, at least 1) is a // burst; a run of them is a `chat` moment at (t − lag), scored // under CHAT_WEIGHT — always below what a host laugh can score // // No chat file: nothing here runs, and the analysis is what it was. // // lib may not import controller (and this is plain ESM run by bare node), so // the file is read here directly: `{version, source: "live_chat", cues: // [{start, end, text: ": "}]}` (normalizeLiveChat's shape; // readNormalizedLiveChat's checks). // // Plain ESM with a .d.mts beside it. import { readFile } from "node:fs/promises"; import path from "node:path"; export const CHAT_FILE = "live_chat.cues.json"; export const CHAT_BIN_S = 2; export const CHAT_LAG_MAX_S = 20; export const CHAT_LAG_DEFAULT_S = 6; /** A cross-correlation peak under this is weak: the default lag is used. */ export const CHAT_LAG_MIN_R = 0.2; export const CHAT_BURST_RATIO = 2.5; export const CHAT_BURST_MIN = 3; export const CHAT_MEDIAN_HALF_S = 60; /** A chat moment's score is at most this (a host laugh's weight is 1). */ export const CHAT_WEIGHT = 0.6; /** A word of chat that is a laugh: lol, lmao, lmfao, KEKW, LUL, OMEGALUL, rofl, haha…, as a word or an emote's :name:. */ export const CHAT_LAUGH_RE = /^:?(?:l+o+l+|lmf?ao+|kekw|lul|omegalul|rofl|(?:ha){2,}h?|face[_-]with[_-]tears[_-]of[_-]joy|rolling[_-]on[_-]the[_-]floor[_-]laughing|joy)\:?$/i; const LAUGH_EMOJI_RE = /[\u{1F602}\u{1F923}]/u; /** "W" alone (or a few of them): the chat's cheer. */ const LONE_W_RE = /^[Ww](?:\s+[Ww])*!*$/; const round = (x, d = 2) => Math.round(x * 10 ** d) / 10 ** d; const num = (x) => typeof x === "number" && Number.isFinite(x); /** A chat cue's message, the author (": ") taken off. */ export function chatMessage(text) { const s = String(text ?? ""); const i = s.indexOf(": "); return i >= 0 ? s.slice(i + 2) : s; } /** Whether a chat message laughs. */ export function isChatLaugh(text) { const msg = chatMessage(text).trim(); if (!msg) return false; if (LONE_W_RE.test(msg) || LAUGH_EMOJI_RE.test(msg)) return true; return msg.split(/\s+/).some((tok) => CHAT_LAUGH_RE.test(tok.replace(/^[^\p{L}\p{N}:]+|[^\p{L}\p{N}:]+$/gu, ""))); } /** * The chat replay beside a recording, or null when there is none (or it is * not one). * @param {string} videoDir * @returns {Promise<{ source: string, cues: { start: number, text: string }[] } | null>} */ export async function readChatCues(videoDir) { let doc; try { doc = JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ videoDir, CHAT_FILE), "utf8")); } catch { return null; } if (!doc || typeof doc.version !== "number" || doc.source !== "live_chat" || !Array.isArray(doc.cues)) return null; const cues = doc.cues.filter((c) => c && num(c.start) && c.start >= 0 && typeof c.text === "string").map((c) => ({ start: c.start, text: c.text })); return { source: CHAT_FILE, cues }; } /** * Messages and laughing messages per bin, over [0, duration). * @param {{ start: number, text: string }[]} cues * @param {{ duration: number, hop?: number }} o * @returns {{ hop: number, rate: number[], laugh: number[] }} */ export function chatBins(cues, { duration, hop = CHAT_BIN_S }) { const n = Math.max(0, Math.ceil((Number(duration) || 0) / hop)); const rate = new Array(n).fill(0); const laugh = new Array(n).fill(0); for (const c of cues ?? []) { if (!c || !num(c.start) || c.start < 0) continue; const k = Math.floor(c.start / hop); if (k >= n) continue; rate[k] += 1; if (isChatLaugh(c.text)) laugh[k] += 1; } return { hop, rate, laugh }; } function pearson(xs, ys) { const n = xs.length; if (n < 3) return null; let mx = 0; let my = 0; for (let i = 0; i < n; i += 1) { mx += xs[i]; my += ys[i]; } mx /= n; my /= n; let sxy = 0; let sxx = 0; let syy = 0; for (let i = 0; i < n; i += 1) { const a = xs[i] - mx; const b = ys[i] - my; sxy += a * b; sxx += a * a; syy += b * b; } return sxx > 0 && syy > 0 ? sxy / Math.sqrt(sxx * syy) : null; } /** * How late the chat laughs: the shift (0..CHAT_LAG_MAX_S) that best lines * the chat-laugh bins up with the laugh scan's scores (each bin the * strongest window centred in it), refined between bins on the peak's * parabola; CHAT_LAG_DEFAULT_S when there is no scan or the peak's * correlation is under CHAT_LAG_MIN_R. * @param {number[]} laugh the chat-laugh bins * @param {{ t0?: number, hop?: number, window?: number, scores?: number[] | null } | null} scan * @param {{ from?: number, to?: number, hop?: number }} [o] * @returns {{ lagS: number, how: "xcorr" | "default", r: number | null, why: string }} */ export function chatLag(laugh, scan, { from = 0, to = Infinity, hop = CHAT_BIN_S } = {}) { const fallback = (why, r = null) => ({ lagS: CHAT_LAG_DEFAULT_S, how: /** @type {const} */ ("default"), r, why }); const scores = scan && Array.isArray(scan.scores) ? scan.scores : null; if (!scores || !scores.length) return fallback("no laugh scores to line the chat up with"); const n = laugh.length; const ced = new Array(n).fill(0); const t0 = scan.t0 ?? 0; const sh = scan.hop ?? 0.5; const win = scan.window ?? 1; scores.forEach((s, i) => { if (!num(s)) return; const k = Math.floor((t0 + i * sh + win / 2) / hop); if (k >= 0 && k < n && s > ced[k]) ced[k] = s; }); const k0 = Math.max(0, Math.ceil(from / hop)); const k1 = Math.min(n, Number.isFinite(to) ? Math.floor(to / hop) : n); const shifts = Math.floor(CHAT_LAG_MAX_S / hop); const rs = []; for (let s = 0; s <= shifts; s += 1) { const xs = []; const ys = []; for (let k = k0 + s; k < k1; k += 1) { xs.push(laugh[k]); ys.push(ced[k - s]); } rs.push(pearson(xs, ys)); } let best = -1; rs.forEach((r, i) => { if (r !== null && (best < 0 || r > /** @type {number} */ (rs[best]))) best = i; }); if (best < 0) return fallback("the chat or the scan does not vary"); const r = /** @type {number} */ (rs[best]); if (r < CHAT_LAG_MIN_R) return fallback(`a weak peak (r ${round(r, 2)})`, round(r, 3)); let at = best; const a = rs[best - 1]; const c = rs[best + 1]; if (a !== null && a !== undefined && c !== null && c !== undefined) { const d = a - 2 * r + c; if (d < 0) at = best + Math.max(-0.5, Math.min(0.5, (0.5 * (a - c)) / d)); } const lagS = round(Math.max(0, Math.min(CHAT_LAG_MAX_S, at * hop)), 1); return { lagS, how: "xcorr", r: round(r, 3), why: `cross-correlated with the laugh scan (r ${round(r, 2)})` }; } /** * The chat's bursts as moments, moved back by the lag; only those wholly * inside [from, to]. * @param {{ hop: number, laugh: number[] }} bins * @param {{ lagS: number, from?: number, to?: number }} o * @returns {{ t: number, end: number, score: number, messages: number }[]} */ export function chatMoments(bins, { lagS, from = 0, to = Infinity }) { const { hop, laugh } = bins; const n = laugh.length; const half = Math.round(CHAT_MEDIAN_HALF_S / hop); const base = laugh.map((_, k) => { const w = laugh.slice(Math.max(0, k - half), Math.min(n, k + half + 1)).sort((x, y) => x - y); return Math.max(1, w[Math.floor(w.length / 2)] ?? 0); }); const burst = laugh.map((v, k) => v >= CHAT_BURST_MIN && v >= CHAT_BURST_RATIO * base[k]); const out = []; for (let k = 0; k < n; ) { if (!burst[k]) { k += 1; continue; } let j = k; // A run: burst bins, one quiet bin between them allowed. while (j + 1 < n && (burst[j + 1] || (j + 2 < n && burst[j + 2]))) j += burst[j + 1] ? 1 : 2; let messages = 0; let strength = 0; for (let i = k; i <= j; i += 1) { messages += laugh[i]; strength += Math.max(0, laugh[i] / base[i] - 1); } const t = Math.max(0, k * hop - lagS); const end = Math.max(t + hop, (j + 1) * hop - lagS); if (t >= from - 1e-9 && end <= to + 1e-9) { out.push({ t: round(t), end: round(end), score: round(CHAT_WEIGHT * (1 - Math.exp(-strength / 6)), 3), messages }); } k = j + 1; } return out; }