Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 207068c4b6536f82d51f77cabac5c99e61fa10d6
parent dad8c275f0fd0392d4ac60acb71a22c62ab8d19f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 20 Nov 2026 15:07:46 -0500

Merge lane/chat-clock: a chat captured while live is on the recording's clock

A live-captured chat line is placed by its own posting time against the recording's zero; a replay line is never moved; duplicates of a replay line are dropped. fetch-chat gains "renormalize": true (no network). No version-1 cues file goes stale.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/buildIndex.ts | 10+++++++---
Mcommon/controller/fetchLiveChat.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchLiveChat.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Acommon/controller/normalizeLiveChat.test.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/normalizeLiveChat.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/normalizeTranscript.ts | 5++++-
Acommon/lib/liveChat.test.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/liveChat.ts | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/CHANGELOG.md | 14++++++++++++++
Meditor/app/api/ops/fetch-chat/route.ts | 16++++++++++++----
Meditor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts | 8+++++++-
Mscripts/archilyzer-ops.mjs | 8+++++++-
13 files changed, 859 insertions(+), 32 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -236,7 +236,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/&lt;slug&gt;.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | | `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -&gt; {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` | -| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` | +| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` | | `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/&lt;id&gt;/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` | | `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` | | `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /cookies, then {"resume": "&lt;run id&gt;"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` | diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -44,7 +44,6 @@ import { open } from "lmdb"; import { writeJsonAtomic as writeJsonAtomicShared } from "../lib/jsonFile-server"; import { parseVtt, type Cue } from "../lib/vtt"; import { parseTranscriptJson } from "../lib/whisper"; -import { parseLiveChat } from "../lib/liveChat"; import { platformLabelStale, summarize, @@ -57,6 +56,7 @@ import { } from "./normalizeTranscript"; import { isLiveChatCuesFresh, + parseLiveChatOnRecordingClock, readNormalizedLiveChat, } from "./normalizeLiveChat"; import type { @@ -1310,11 +1310,15 @@ export async function buildIndex({ else retrySubs = true; continue; } - trackCues = parseLiveChat(raw); + trackCues = (await parseLiveChatOnRecordingClock(videoFullDir, raw)).cues; } else { const raw = await readFile(rawPath, "utf8"); + // A stale chat's raw is parsed onto the recording's clock, + // as the normalizer does (lane chat-clock). trackCues = - t.track === "live_chat" ? parseLiveChat(raw) : parseVtt(raw); + t.track === "live_chat" + ? (await parseLiveChatOnRecordingClock(videoFullDir, raw)).cues + : parseVtt(raw); } } if (trackCues.length > 0) { diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts @@ -348,3 +348,83 @@ test("the job: refusals before any job (info for a skip), a fetch job, a normali assert.equal(spawn.calls.length, 0, "no network for a replay already here"); assert.equal(JSON.parse(await readFile(path.join(dir6, "live_chat.cues.json"), "utf8")).cues.length, 3); }); + +// RE-NORMALIZE ONLY (lane chat-clock): the raw on disk parsed again, fresh or +// not, never a fetch. +test("renormalize: refused with no raw chat on disk (it never fetches), and no job", async () => { + await video("rn1", { webpage_url: "https://www.youtube.com/watch?v=rn1", was_live: true }); + const spawn = stubRunner(); + const out = await runFetchChatJob({ + paths, slug: SLUG, videoId: "rn1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, renormalize: true, + }); + assert.ok(!out.ok && !out.info && /no raw chat on disk/.test(out.error) && /never fetches/.test(out.error), JSON.stringify(out)); + assert.equal(spawn.calls.length, 0); + const none = await runFetchChatJob({ + paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, renormalize: true, + }); + assert.ok(!none.ok); +}); + +test("renormalize: a FRESH chat captured live is parsed again onto the broadcast's clock, with no spawn", async () => { + const t0 = Date.UTC(2026, 0, 2, 3, 0, 0); + const dir = await video("rn2", { + webpage_url: "https://www.youtube.com/watch?v=rn2", + was_live: true, + release_timestamp: t0 / 1000, + }); + const live = JSON.stringify({ + replayChatItemAction: { + actions: [{ + addChatItemAction: { + item: { + liveChatTextMessageRenderer: { + message: { runs: [{ text: "hello" }] }, + authorName: { simpleText: "viewer1" }, + id: "m1", + timestampUsec: String((t0 + 2_335_000) * 1000), + }, + }, + }, + }], + }, + videoOffsetTimeMsec: "100000", + isLive: true, + }); + await writeFile(path.join(dir, "transcript.live_chat.json"), live + "\n"); + // A v1 file written before the fix: fresh by its mtime. + await writeFile( + path.join(dir, "live_chat.cues.json"), + '{"version":1,"source":"live_chat","cues":[{"start":100,"end":105,"text":"viewer1: hello"}]}', + ); + const plain = await runFetchChatJob({ paths, slug: SLUG, videoId: "rn2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); + assert.ok(!plain.ok && plain.info && /already here/.test(plain.error), "without the flag: fresh, no job"); + + const spawn = stubRunner(); + const job = await runFetchChatJob({ + paths, slug: SLUG, videoId: "rn2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, renormalize: true, + }); + assert.ok(job.ok, JSON.stringify(job)); + void job.stream.cancel(); + assert.equal((await job.done).status, "done"); + assert.equal(spawn.calls.length, 0, "no network"); + const doc = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")); + assert.equal(doc.version, 2); + assert.equal(doc.cues[0].start, 2335); + assert.equal(doc.clock.basis, "broadcast-start"); + assert.equal(doc.clock.shiftSeconds, 2235); +}); + +test("renormalize: held by the media guard while the channel's media is moving", async () => { + const dir = await video("rn3", { webpage_url: "https://www.youtube.com/watch?v=rn3", was_live: true }); + await writeFile(path.join(dir, "transcript.live_chat.json"), REPLAY); + const marker = path.join(CORPUS, "channels", SLUG, ".relocating.json"); + await writeFile(marker, JSON.stringify({ target: "/nowhere", direction: "out", startedAt: new Date().toISOString(), phase: "copying", scope: "media" })); + try { + const out = await runFetchChatJob({ + paths, slug: SLUG, videoId: "rn3", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, renormalize: true, + }); + assert.ok(!out.ok && /moving|transition|held/i.test(out.error), JSON.stringify(out)); + } finally { + await rm(marker, { force: true }); + } +}); diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts @@ -29,10 +29,14 @@ // // `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a // tierable big file, and the normalizer moves it into the channel's media/. +// +// `renormalize: true` (lane chat-clock) parses the raw already on disk again, +// fresh or not, and never fetches: the one-video repair for a chat normalized +// before a live capture was put on the recording's clock (normalizeLiveChat). import { localMediaFetchRefusal } from "../lib/localMedia"; import path from "node:path"; -import { readFile, readdir, stat } from "node:fs/promises"; +import { lstat, readFile, readdir, stat } from "node:fs/promises"; import { AUTH_RETRY_CLASSES, classifyDownloadFailure, @@ -79,7 +83,10 @@ export type LiveChatPlan = | { kind: "no-fetcher"; platform: string } // The metadata says the video was never live: there is no replay to ask for. | { kind: "not-live"; liveStatus: string } - | { kind: "fetch"; url: string; platform: string } + // `live`: the metadata says the stream is live now, so the pass captures + // the chat as it is typed (on the capture's clock until normalizeLiveChat + // puts it on the recording's). + | { kind: "fetch"; url: string; platform: string; live?: boolean } | { kind: "refused"; error: string }; async function isDirectory(p: string): Promise<boolean> { @@ -133,7 +140,7 @@ export async function liveChatPlan( if (!CHAT_PLATFORMS.has(platform)) return { kind: "no-fetcher", platform }; const live = await liveStatusOf(videoDir); if (live === "not_live") return { kind: "not-live", liveStatus: live }; - return { kind: "fetch", url, platform }; + return { kind: "fetch", url, platform, ...(live === "is_live" ? { live: true } : {}) }; } function succeeded(exitCode: number | null): boolean { @@ -158,6 +165,8 @@ export type FetchLiveChatOpts = { signal: AbortSignal; onPlatformBackoff?: () => Promise<void> | void; onPlatformClean?: () => Promise<string | null> | string | null; + // The stream is live now (LiveChatPlan `live`): the log says it is a capture. + capturingLive?: boolean; // Test seams: the spawn, and the platform pace in the argv. run?: ChatRunner; paceSeconds?: number; @@ -189,7 +198,12 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC const pass = (cookies: string | undefined) => run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds)); - opts.onLog(`Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`); + opts.onLog( + opts.capturingLive + ? `Capturing the live chat of ${opts.videoId} from ${opts.videoUrl} while it is live (no media); ` + + `it is put on the broadcast's clock when it is normalized\n` + : `Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`, + ); const firstCookies = alwaysCookies(policy); let outcome = await pass(firstCookies); // A pass the platform refused for THIS video ("Join this channel …") is an @@ -278,8 +292,35 @@ export type FetchChatJobOpts = { queueKey?: string; afterRun?: () => void | Promise<void>; run?: ChatRunner; + // RE-NORMALIZE ONLY (lane chat-clock): parse the raw replay already on disk + // again — e.g. a chat captured live and normalized before the chat was put + // on the recording's clock — even when its cues are fresh. Never a fetch: + // refused when no raw is here. No network; the job's kind still declares + // `needsMedia`, so a raw that is a tier link onto an unreachable drive is + // refused by runManagedFunction's guard like any other media reader. + renormalize?: boolean; }; +/** Why a re-normalize cannot run for this video, or null. Reads the disk only. */ +export async function renormalizeChatRefusal( + paths: Paths, + slug: string, + videoId: string, +): Promise<string | null> { + if (!isVideoIdSegment(videoId)) return `"${videoId}" is not a video id (one path segment)`; + const videoDir = path.join(paths.channelsDir, slug, "data", videoId); + if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug); + const here = (name: string) => lstat(path.join(videoDir, name)).then(() => true, () => false); + if (!(await here(LIVE_CHAT_FILENAME))) { + return ( + `${videoId} has no raw chat on disk (${LIVE_CHAT_FILENAME}): "renormalize" reads only the file ` + + `already here and never fetches — fetch-chat without it fetches the chat` + ); + } + if (!(await here(META_FILENAME))) return `${videoId} has no ${META_FILENAME}: its chat cannot be normalized`; + return null; +} + // Every refusal before any job, in the sentences the rest of the app uses. export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamActionResult> { const { paths, slug, videoId, channelConfig } = opts; @@ -288,7 +329,13 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct } catch (err) { return { ok: false, error: (err as Error).message }; } - const plan = await liveChatPlan(paths, slug, videoId, channelConfig); + if (opts.renormalize) { + const refusal = await renormalizeChatRefusal(paths, slug, videoId); + if (refusal) return { ok: false, error: refusal }; + } + const plan: LiveChatPlan = opts.renormalize + ? { kind: "normalize" } + : await liveChatPlan(paths, slug, videoId, channelConfig); switch (plan.kind) { case "refused": return { ok: false, error: plan.error }; @@ -326,7 +373,11 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct ...(plan.kind === "normalize" ? { network: false as const } : {}), fn: async (onLog, signal) => { if (plan.kind === "normalize") { - onLog(`The chat replay of ${videoId} is on disk; normalizing it (no network).`); + onLog( + opts.renormalize + ? `Re-normalizing the chat of ${videoId} from the raw on disk (no network).` + : `The chat replay of ${videoId} is on disk; normalizing it (no network).`, + ); await normalizeChat({ slug, videoId, channelConfig, onLog }, videoDir); } else { await fetchLiveChat({ @@ -340,6 +391,7 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct signal, onPlatformBackoff: () => recordDownloadBackoff(plan.platform, paths), onPlatformClean: () => recordPlatformClean(plan.platform, paths), + ...(plan.live ? { capturingLive: true } : {}), ...(opts.run ? { run: opts.run } : {}), }); } diff --git a/common/controller/normalizeLiveChat.test.ts b/common/controller/normalizeLiveChat.test.ts @@ -0,0 +1,227 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/normalizeLiveChat.test.ts +// +// ONE CLOCK PER RECORDING, THE CUES' — for the live chat (lane chat-clock). +// A chat yt-dlp captures WHILE THE STREAM IS LIVE is timed from the moment the +// capture began (`videoOffsetTimeMsec = timestampUsec/1000 − start_time`, +// every line `"isLive": true`); a recording made from the broadcast's start is +// timed from the broadcast's start. These cases pin the normalizer putting the +// chat on the recording's clock. Temp dirs, synthetic names, no network. + +const ROOT = await mkdtemp(path.join(tmpdir(), "chat-clock-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const { normalizeLiveChat, isLiveChatCuesFresh } = await import("./normalizeLiveChat"); + +// The broadcast went live at T0; the chat capture began 2,235 s later. +const T0_MS = Date.UTC(2026, 0, 2, 3, 0, 0); +const SHIFT_MS = 2_235_000; +const CAPTURE_MS = T0_MS + SHIFT_MS; +const URL = "https://www.youtube.com/watch?v=abc123"; + +type Msg = { id?: string; author: string; text: string }; + +function renderer(m: Msg, postedMs: number) { + return { + liveChatTextMessageRenderer: { + message: { runs: [{ text: m.text }] }, + authorName: { simpleText: m.author }, + ...(m.id ? { id: m.id } : {}), + timestampUsec: String(postedMs * 1000), + }, + }; +} + +// yt-dlp's live pseudo-replay line: the offset is from the capture's start. +function liveLine(offsetMs: number, m: Msg, captureMs = CAPTURE_MS): string { + return JSON.stringify({ + replayChatItemAction: { actions: [{ addChatItemAction: { item: renderer(m, captureMs + offsetMs) } }] }, + videoOffsetTimeMsec: String(offsetMs), + isLive: true, + }); +} + +// A replay line (after the stream): YouTube's offset, on the VOD's clock. +function replayLine(offsetMs: number, m: Msg): string { + return JSON.stringify({ + replayChatItemAction: { + actions: [{ addChatItemAction: { item: renderer(m, T0_MS + offsetMs) } }], + videoOffsetTimeMsec: String(offsetMs), + }, + }); +} + +const META = { + id: "abc123", + title: "Demo stream", + upload_date: "20260102", + release_timestamp: T0_MS / 1000, + live_status: "post_live", + was_live: true, + duration: 10_000, + webpage_url: URL, +}; + +function recording(o: { fromStart?: boolean; status?: string; startedAtMs?: number } = {}) { + const startedAt = new Date(o.startedAtMs ?? CAPTURE_MS - 5_000).toISOString(); + const fromStart = o.fromStart ?? true; + return { + status: o.status ?? "landed", + url: URL, + platform: "youtube", + fromStart, + startedAt, + parts: [{ method: "ytdlp", url: URL, fromStart, startedAt, seconds: 10_000 }], + ...((o.status ?? "landed") === "landed" ? { landedPart: 0 } : {}), + }; +} + +let n = 0; +async function videoDir(files: { meta?: object; raw: string[]; rec?: object }): Promise<string> { + const dir = path.join(ROOT, `case-${++n}`, "demo-channel", "data", "abc123"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(files.meta ?? META)); + await writeFile(path.join(dir, "transcript.live_chat.json"), files.raw.join("\n") + "\n"); + if (files.rec) await writeFile(path.join(dir, "live-recording.json"), JSON.stringify(files.rec)); + return dir; +} + +type Doc = { version: number; cues: { start: number; text: string }[]; clock?: Record<string, unknown> }; +async function normalize(dir: string): Promise<Doc> { + const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", force: true, tier: false }); + assert.equal(out.status, "wrote"); + return JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")) as Doc; +} + +test("a chat captured while live lands on a from-start recording's clock (the broadcast's start)", async () => { + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" }), liveLine(-300_000, { id: "m0", author: "viewer0", text: "backlog" })], + rec: recording(), + }); + const doc = await normalize(dir); + assert.deepEqual( + doc.cues.map((c) => [c.start, c.text]), + [ + [1935, "viewer0: backlog"], + [2335, "viewer1: hello"], + ], + ); + assert.equal(doc.version, 2); + assert.equal(doc.clock?.basis, "broadcast-start"); + assert.equal(doc.clock?.certain, true); + assert.equal(doc.clock?.shiftSeconds, 2235); + assert.equal(doc.clock?.zeroAt, new Date(T0_MS).toISOString()); + assert.equal(doc.clock?.liveLines, 2); +}); + +test("a recording still in progress has the same zero (the chat may be normalized before it lands)", async () => { + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })], + rec: recording({ status: "recording" }), + }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 2335); + assert.equal(doc.clock?.basis, "broadcast-start"); +}); + +test("no recording: the media is the post-live VOD, timed from the broadcast's start too", async () => { + const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })] }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 2335); + assert.equal(doc.clock?.basis, "broadcast-start"); +}); + +test("a live head then a replay (a resumed .part): the replay copy wins, a head-only message is shifted, an id-less line is kept", async () => { + const dir = await videoDir({ + raw: [ + liveLine(10_000, { id: "dup", author: "viewer1", text: "said twice" }), + liveLine(20_000, { id: "head-only", author: "viewer2", text: "only live" }), + liveLine(30_000, { author: "viewer3", text: "no id" }), + replayLine(500_000, { id: "early", author: "viewer4", text: "replay" }), + replayLine(2_245_000, { id: "dup", author: "viewer1", text: "said twice" }), + ], + }); + const doc = await normalize(dir); + assert.deepEqual( + doc.cues.map((c) => [c.start, c.text]), + [ + [500, "viewer4: replay"], + [2245, "viewer1: said twice"], + [2255, "viewer2: only live"], + [2265, "viewer3: no id"], + ], + ); + assert.equal(doc.clock?.duplicatesDropped, 1); + assert.equal(doc.clock?.liveLines, 3); + assert.equal(doc.clock?.replayLines, 2); +}); + +test("a recording NOT from the start: its part's start is the zero, and it is not certain", async () => { + const startedAtMs = T0_MS + 3_000_000; + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" }, startedAtMs + 2_000)], + rec: recording({ fromStart: false, startedAtMs }), + }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 102); + assert.equal(doc.clock?.basis, "recording-start"); + assert.equal(doc.clock?.certain, false); +}); + +test("no zero to be had (no release_timestamp, no recording): the capture's clock, said so", async () => { + const { release_timestamp, ...meta } = META; + void release_timestamp; + const dir = await videoDir({ meta, raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })] }); + const doc = await normalize(dir); + assert.equal(doc.cues[0].start, 100); + assert.equal(doc.clock?.basis, "capture-start"); + assert.equal(doc.clock?.certain, false); +}); + +test("a recording NOT from the start with no readable start: no zero, the capture's clock, and the log says so", async () => { + const rec = recording({ fromStart: false }); + const parts = rec.parts.map(({ startedAt, ...p }) => (void startedAt, p)); + const dir = await videoDir({ + raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })], + rec: { ...rec, parts }, + }); + const logs: string[] = []; + const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", force: true, tier: false, log: (m) => logs.push(m) }); + assert.equal(out.status, "wrote"); + const doc = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")) as Doc; + assert.equal(doc.cues[0].start, 100); + assert.equal(doc.clock?.basis, "capture-start"); + assert.equal(doc.clock?.certain, false); + assert.ok(logs.some((l) => /left on the capture's clock/.test(l)), logs.join("\n")); +}); + +test("a pure replay: the same starts as ever, basis replay", async () => { + const dir = await videoDir({ + raw: [replayLine(12_000, { id: "a", author: "viewer1", text: "lol" }), replayLine(14_000, { id: "b", author: "viewer2", text: "W" })], + rec: recording(), + }); + const doc = await normalize(dir); + assert.deepEqual(doc.cues.map((c) => c.start), [12, 14]); + assert.equal(doc.clock?.basis, "replay"); + assert.equal(doc.clock?.liveLines, 0); +}); + +test("the version bump makes no v1 file stale: a v1 cues file over a pure replay stays fresh and byte-unchanged", async () => { + const dir = await videoDir({ raw: [replayLine(12_000, { id: "a", author: "viewer1", text: "lol" })] }); + const cuesPath = path.join(dir, "live_chat.cues.json"); + const v1 = '{"version":1,"source":"live_chat","id":"abc123","cues":[{"start":12,"end":17,"text":"viewer1: lol"}]}'; + await writeFile(cuesPath, v1); + const older = new Date(Date.now() - 60_000); + await utimes(path.join(dir, "metadata.info.json"), older, older); + await utimes(path.join(dir, "transcript.live_chat.json"), older, older); + assert.equal((await isLiveChatCuesFresh(dir)).fresh, true); + const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", tier: false }); + assert.equal(out.status, "fresh"); + assert.equal(await readFile(cuesPath, "utf8"), v1); +}); diff --git a/common/controller/normalizeLiveChat.ts b/common/controller/normalizeLiveChat.ts @@ -2,12 +2,28 @@ // alongside the raw file so that downstream consumers (buildIndex, archives) // can skip re-parsing potentially huge live-chat JSON-lines payloads. Shape // matches NormalizedTranscript with source: "live_chat". +// +// ONE CLOCK PER RECORDING, THE CUES' (lane chat-clock): a chat yt-dlp captured +// WHILE THE STREAM WAS LIVE is timed from the moment the capture began, not +// from the broadcast's start. The cues written here are on the recording's +// clock — the zero is the metadata's `release_timestamp` or the recording's +// own part (lib/liveChat.ts liveChatClockZero) — and the file says so in +// `clock`. A chat fetched as a replay is already on that clock and is not moved. import path from "node:path"; import { lstat, readFile, stat } from "node:fs/promises"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { tierMediaFile } from "../lib/mediaTier-server"; -import { parseLiveChat } from "../lib/liveChat"; +import { + hasLiveCapturedLines, + liveChatClockOf, + liveChatClockZero, + parseLiveChatDetailed, + type LiveChatClock, + type LiveChatZero, + type LiveRecordingLike, +} from "../lib/liveChat"; +import { LIVE_RECORDING_FILENAME, coerceLiveRecording } from "../lib/liveCapture"; import type { Cue } from "../lib/vtt"; import { summarize, type RawMetadata } from "../lib/transcripts-server"; import { @@ -19,7 +35,13 @@ import { META_FILENAME, } from "../lib/videoStatus"; -export const LIVE_CHAT_FILE_VERSION = 1; +// 2 (lane chat-clock): a chat captured while live is on the recording's +// clock, and the file says which clock in `clock`. A version-1 file is NOT +// stale for being version 1 — freshness stays the mtimes below, so no build +// re-reads every raw replay off the media drive; a v1 file over a live capture +// is re-normalized one video at a time (`pnpm ops fetch-chat {…, +// "renormalize": true}`). +export const LIVE_CHAT_FILE_VERSION = 2; export type NormalizeLiveChatOptions = { videoDir: string; @@ -59,6 +81,53 @@ async function rawMtimeMs(p: string): Promise<number | null> { } } +/** + * The recording's zero for this video's live-captured chat: its metadata's + * `release_timestamp` and its `live-recording.json`, when there is one + * (lib/liveChat.ts liveChatClockZero). `meta` is the parsed metadata when the + * caller holds it already (it can be tens of MB). + */ +export async function readLiveChatZero( + videoDir: string, + meta?: { release_timestamp?: unknown } | null, +): Promise<LiveChatZero> { + const parsedMeta = + meta !== undefined + ? meta + : await readFile(path.join(videoDir, META_FILENAME), "utf8").then( + (raw) => JSON.parse(raw) as { release_timestamp?: unknown }, + () => null, + ); + // The record as written, not coerceLiveRecording's: that drops a part with + // no `startedAt`, and a "from now" part with no start must still say "no + // zero" rather than fall back to the broadcast's start. + const record = await readFile(path.join(videoDir, LIVE_RECORDING_FILENAME), "utf8").then( + (raw) => { + const parsed: unknown = JSON.parse(raw); + return coerceLiveRecording(parsed) ? (parsed as LiveRecordingLike) : null; + }, + () => null, + ); + return liveChatClockZero(parsedMeta, record); +} + +/** + * Parse a raw replay onto the recording's clock. The zero is read only when + * the raw holds a line captured live: a pure replay is never moved, and costs + * no extra read. + */ +export async function parseLiveChatOnRecordingClock( + videoDir: string, + raw: string, + meta?: { release_timestamp?: unknown } | null, +): Promise<{ cues: Cue[]; clock: LiveChatClock }> { + const zero: LiveChatZero = hasLiveCapturedLines(raw) + ? await readLiveChatZero(videoDir, meta) + : { zeroMs: null, basis: "capture-start", certain: false }; + const { cues, stats } = parseLiveChatDetailed(raw, { liveZeroMs: zero.zeroMs }); + return { cues, clock: liveChatClockOf(zero, stats) }; +} + // TODO: live_chat files can be hundreds of MB. parseLiveChat already splits // on "\n", so a streaming readline variant is straightforward if we hit a // memory wall. For now this matches the readFile pattern used by the @@ -99,8 +168,13 @@ export async function normalizeLiveChat( const rawLiveChat = await readFile(rawPath, "utf8"); let cues: Cue[]; + let clock: LiveChatClock; try { - cues = parseLiveChat(rawLiveChat); + ({ cues, clock } = await parseLiveChatOnRecordingClock( + opts.videoDir, + rawLiveChat, + parsedMeta as { release_timestamp?: unknown }, + )); } catch (err) { throw new Error( `Failed to parse ${LIVE_CHAT_FILENAME} for ${opts.channelSlug}/${path.basename(opts.videoDir)}: ${(err as Error).message}`, @@ -111,13 +185,15 @@ export async function normalizeLiveChat( version: LIVE_CHAT_FILE_VERSION, source: "live_chat", ...summary, + clock, cues, }; // Compact, no trailing newline: live_chat.cues.json's historical bytes. await writeJsonAtomic(cuesPath, out, { indent: 0, newline: false }); opts.log?.( - `Normalized live chat ${opts.channelSlug}/${path.basename(opts.videoDir)} (${cues.length} cues)`, + `Normalized live chat ${opts.channelSlug}/${path.basename(opts.videoDir)} (${cues.length} cues)` + + clockNote(clock), ); // THE MEDIA TIER'S HOOK (release 17): the raw replay is read once, here, and // every other reader uses the cues just written — so it moves into @@ -128,6 +204,20 @@ export async function normalizeLiveChat( return { status: "wrote", cuesPath }; } +// The log's word on the clock, for a chat that had lines captured live. +function clockNote(clock: LiveChatClock): string { + if (clock.basis === "replay") return ""; + const dup = clock.duplicatesDropped > 0 ? `, ${clock.duplicatesDropped} duplicate(s) of the replay dropped` : ""; + if (clock.basis === "capture-start") { + return ` — ${clock.liveLines} line(s) captured live, left on the capture's clock (no zero known for the recording)${dup}`; + } + const shift = clock.shiftSeconds !== undefined ? ` ${clock.shiftSeconds} s` : ""; + return ( + ` — ${clock.liveLines} line(s) captured live, moved${shift} onto the recording's clock ` + + `(${clock.basis}${clock.certain ? "" : ", not certain"})${dup}` + ); +} + export async function readNormalizedLiveChat( cuesPath: string, ): Promise<NormalizedLiveChat | null> { @@ -144,7 +234,8 @@ export async function readNormalizedLiveChat( // Sidecar is fresh iff it exists and its mtime is >= both metadata.info.json // and transcript.live_chat.json. Used by buildIndex to decide whether to -// trust the cached cues without re-parsing the raw payload. +// trust the cached cues without re-parsing the raw payload. Its version is +// not asked (LIVE_CHAT_FILE_VERSION above). export async function isLiveChatCuesFresh( videoDir: string, ): Promise<{ fresh: boolean; cuesPath: string }> { diff --git a/common/controller/normalizeTranscript.ts b/common/controller/normalizeTranscript.ts @@ -12,6 +12,7 @@ import { parseTranscriptJson, } from "../lib/whisper"; import type { TranscriptOutputFormat } from "../lib/transcriptionApps"; +import type { LiveChatClock } from "../lib/liveChat"; import { summarize, type RawMetadata } from "../lib/transcripts-server"; import type { TranscriptDetail } from "../lib/transcripts"; import { @@ -51,7 +52,9 @@ export type NormalizedTranscript = TranscriptDetail & { transcriptFormat?: TranscriptOutputFormat; }; -export type NormalizedLiveChat = NormalizedTranscript & { source: "live_chat" }; +// `clock` (version 2, lane chat-clock): the clock a chat's cues were put on +// (lib/liveChat.ts LiveChatClock). Absent from a version-1 file. +export type NormalizedLiveChat = NormalizedTranscript & { source: "live_chat"; clock?: LiveChatClock }; export type NormalizeOptions = { videoDir: string; diff --git a/common/lib/liveChat.test.ts b/common/lib/liveChat.test.ts @@ -0,0 +1,113 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + hasLiveCapturedLines, + liveChatClockOf, + liveChatClockZero, + parseLiveChat, + parseLiveChatDetailed, +} from "./liveChat"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/liveChat.test.ts +// +// The pure half of lane chat-clock: the parser's two clocks and the +// recording's zero. normalizeLiveChat.test.ts drives it through the files. + +const T0 = Date.UTC(2026, 0, 2, 3, 0, 0); + +function line(o: { offsetMs: number; live?: boolean; postedMs?: number; id?: string; text?: string }): string { + const renderer: Record<string, unknown> = { + message: { simpleText: o.text ?? "hi" }, + authorName: { simpleText: "viewer1" }, + }; + if (o.id) renderer.id = o.id; + if (o.postedMs !== undefined) renderer.timestampUsec = String(o.postedMs * 1000); + const actions = [{ addChatItemAction: { item: { liveChatTextMessageRenderer: renderer } } }]; + return o.live + ? JSON.stringify({ replayChatItemAction: { actions }, videoOffsetTimeMsec: String(o.offsetMs), isLive: true }) + : JSON.stringify({ replayChatItemAction: { actions, videoOffsetTimeMsec: String(o.offsetMs) } }); +} + +test("without a zero, the parser answers exactly as before (live and replay lines alike)", () => { + const src = [line({ offsetMs: 5000, live: true, postedMs: T0 + 9000 }), line({ offsetMs: 2000 })].join("\n"); + assert.deepEqual(parseLiveChat(src).map((c) => c.start), [2, 5]); +}); + +test("a live line with no timestamp of its own takes the capture zero before it", () => { + const capture = T0 + 600_000; + const src = [ + line({ offsetMs: 1000, live: true, postedMs: capture + 1000, id: "a" }), + line({ offsetMs: 4000, live: true, id: "b" }), + ].join("\n"); + const { cues, stats } = parseLiveChatDetailed(src, { liveZeroMs: T0 }); + assert.deepEqual(cues.map((c) => c.start), [601, 604]); + assert.equal(stats.captureZeroMs, capture); +}); + +test("two capture sessions in one file: each message by its own posting time", () => { + const src = [ + line({ offsetMs: 1000, live: true, postedMs: T0 + 101_000, id: "a" }), + line({ offsetMs: 1000, live: true, postedMs: T0 + 901_000, id: "b" }), + ].join("\n"); + assert.deepEqual(parseLiveChat(src, { liveZeroMs: T0 }).map((c) => c.start), [101, 901]); +}); + +test("the cheap scan for a live capture", () => { + assert.equal(hasLiveCapturedLines(line({ offsetMs: 0, live: true })), true); + assert.equal(hasLiveCapturedLines(line({ offsetMs: 0 })), false); +}); + +test("the recording's zero", () => { + const meta = { release_timestamp: T0 / 1000 }; + const part = (fromStart: boolean, startedAt = new Date(T0 + 50_000).toISOString()) => ({ fromStart, startedAt }); + // From the start, landed or still recording; no recording at all. + assert.deepEqual(liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [part(true)] }), { + zeroMs: T0, basis: "broadcast-start", certain: true, + }); + assert.equal(liveChatClockZero(meta, { status: "recording", parts: [part(true)] }).zeroMs, T0); + assert.equal(liveChatClockZero(meta, null).zeroMs, T0); + // A playlist reach that missed the first 60 s of the broadcast. + assert.equal( + liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [part(true)], reach: { fromStart: false, missingSeconds: 60 } }).zeroMs, + T0 + 60_000, + ); + // From now: the part's start, not certain. + assert.deepEqual(liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [part(false)] }), { + zeroMs: T0 + 50_000, basis: "recording-start", certain: false, + }); + // From now with no readable start: no zero (never the broadcast's start). + for (const startedAt of [undefined, "not a date"]) { + assert.deepEqual( + liveChatClockZero(meta, { status: "landed", landedPart: 0, parts: [{ fromStart: false, ...(startedAt ? { startedAt } : {}) }] }), + { zeroMs: null, basis: "capture-start", certain: false }, + ); + } + // The landed part missing from the record: the record's own mode decides. + assert.deepEqual(liveChatClockZero(meta, { status: "landed", landedPart: 0, fromStart: false, parts: [] }), { + zeroMs: null, basis: "capture-start", certain: false, + }); + assert.equal(liveChatClockZero(meta, { status: "landed", landedPart: 0, fromStart: true, parts: [] }).zeroMs, T0); + // A recording that landed nothing did not make the media. + assert.equal(liveChatClockZero(meta, { status: "failed", parts: [part(false)] }).basis, "broadcast-start"); + // Nothing known. + assert.deepEqual(liveChatClockZero({}, null), { zeroMs: null, basis: "capture-start", certain: false }); +}); + +test("the clock record", () => { + const stats = { liveLines: 2, replayLines: 1, duplicatesDropped: 1, captureZeroMs: T0 + 2_234_980 }; + assert.deepEqual(liveChatClockOf({ zeroMs: T0, basis: "broadcast-start", certain: true }, stats), { + basis: "broadcast-start", + certain: true, + zeroAt: new Date(T0).toISOString(), + captureStartedAt: new Date(T0 + 2_234_980).toISOString(), + shiftSeconds: 2234.98, + liveLines: 2, + replayLines: 1, + duplicatesDropped: 1, + }); + assert.equal( + liveChatClockOf({ zeroMs: null, basis: "capture-start", certain: false }, { ...stats, liveLines: 0 }).basis, + "replay", + ); +}); diff --git a/common/lib/liveChat.ts b/common/lib/liveChat.ts @@ -7,7 +7,8 @@ import type { Cue } from "./vtt"; // `liveChatPaidMessageRenderer`, `liveChatMembershipItemRenderer`, etc.). // // We emit one Cue per addChatItemAction that has a renderable text body, with -// `start` derived from `videoOffsetTimeMsec` and `text` formatted as +// `start` derived from `videoOffsetTimeMsec` — on the recording's clock for a +// line captured while live (parseLiveChatDetailed) — and `text` formatted as // `<author>: <message>`. Non-text events (ticker pings without an associated // message, viewer-engagement nags) are skipped. @@ -19,6 +20,9 @@ type ChatRenderer = { headerSubtext?: MessageBody; text?: MessageBody; authorName?: AuthorBody; + // The message's id and its posting time (epoch µs, a string). + id?: string; + timestampUsec?: string; }; type ChatItem = Record<string, ChatRenderer | undefined>; type AddAction = { item?: ChatItem }; @@ -30,6 +34,8 @@ type ReplayAction = { type ReplayEnvelope = { replayChatItemAction?: ReplayAction; videoOffsetTimeMsec?: string; + // yt-dlp's mark on a line captured while the stream was live. + isLive?: boolean; }; const TEXT_RENDERERS = [ @@ -71,11 +77,75 @@ function textOf(renderer: ChatRenderer): string { ); } -export function parseLiveChat(src: string): Cue[] { +// ONE CLOCK PER RECORDING, THE CUES' (lane chat-clock, 20 Nov 2026). yt-dlp +// writes two kinds of line, and they are not on one clock: +// +// a REPLAY line (the chat fetched after the stream) carries YouTube's own +// `videoOffsetTimeMsec` — the VOD's clock, zero at the broadcast's start; +// a LIVE line (`"isLive": true`, the chat captured while the stream is live) +// carries `timestampUsec/1000 − start_time`, where start_time is the +// moment yt-dlp's chat downloader began — the CAPTURE's clock. A capture +// begun 37 minutes into a broadcast put every message 37 minutes early on a +// from-start recording. +// +// So a live line is placed by its item's ABSOLUTE posting time against the +// recording's zero (`liveZeroMs`, liveChatClockZero below) — not by the offset +// plus one constant, so a file stitched from several capture sessions (several +// start_times) still comes out right. A replay line is never moved. A live +// line with no timestamp of its own is placed by the nearest capture zero +// before it (else the file's first). With no zero, live lines keep yt-dlp's +// offsets, exactly as before, and the stats say so. +// +// A file can hold both: yt-dlp resuming a live `.part` after the stream ended +// appends the replay, from 0, below the live head — whose messages the replay +// mostly carries again. A message (item `id`) the replay holds is taken from +// the replay alone; a line with no id is never dropped. + +export type LiveChatParseStats = { + liveLines: number; + replayLines: number; + duplicatesDropped: number; + // The median capture zero (epoch ms) of the live messages that carry a + // timestamp: `timestampUsec/1000 − videoOffsetTimeMsec`. Null with none. + captureZeroMs: number | null; +}; + +export type ParseLiveChatOptions = { + // The recording's zero, epoch ms (liveChatClockZero). Absent or null: live + // lines keep yt-dlp's capture-relative offsets. + liveZeroMs?: number | null; +}; + +type Entry = { + offsetMs: number; + live: boolean; + postedMs: number | null; + id: string | null; + text: string; + line: number; +}; + +/** Does this raw replay hold any line captured while live? (A cheap scan.) */ +export function hasLiveCapturedLines(src: string): boolean { + return /"isLive"\s*:\s*true/.test(src); +} + +function median(xs: number[]): number | null { + if (xs.length === 0) return null; + const s = [...xs].sort((a, b) => a - b); + return s[Math.floor(s.length / 2)]; +} + +export function parseLiveChatDetailed( + src: string, + opts: ParseLiveChatOptions = {}, +): { cues: Cue[]; stats: LiveChatParseStats } { const lines = src.split("\n"); - const cues: Cue[] = []; - for (const line of lines) { - const trimmed = line.trim(); + const entries: Entry[] = []; + let liveLines = 0; + let replayLines = 0; + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i].trim(); if (!trimmed) continue; let envelope: ReplayEnvelope; try { @@ -88,7 +158,9 @@ export function parseLiveChat(src: string): Cue[] { replay?.videoOffsetTimeMsec ?? envelope.videoOffsetTimeMsec; const offsetMs = offsetRaw ? Number(offsetRaw) : NaN; if (!Number.isFinite(offsetMs)) continue; - const start = offsetMs / 1000; + const live = envelope.isLive === true; + if (live) liveLines++; + else replayLines++; for (const action of replay?.actions ?? []) { const item = action.addChatItemAction?.item; if (!item) continue; @@ -98,15 +170,166 @@ export function parseLiveChat(src: string): Cue[] { const text = textOf(renderer).trim(); if (!text) continue; const author = authorOf(renderer); - cues.push({ - start, - end: start + 5, + const usec = renderer.timestampUsec ? Number(renderer.timestampUsec) : NaN; + entries.push({ + offsetMs, + live, + postedMs: Number.isFinite(usec) ? usec / 1000 : null, + id: typeof renderer.id === "string" && renderer.id ? renderer.id : null, text: author ? `${author}: ${text}` : text, + line: i, }); break; } } } + + // The capture zero of every timestamped live message, in file order. + const zeros: { line: number; zeroMs: number }[] = []; + for (const e of entries) { + if (e.live && e.postedMs !== null) zeros.push({ line: e.line, zeroMs: e.postedMs - e.offsetMs }); + } + const captureZeroMs = median(zeros.map((z) => z.zeroMs)); + + const replayIds = new Set<string>(); + for (const e of entries) if (!e.live && e.id) replayIds.add(e.id); + + const liveZeroMs = opts.liveZeroMs ?? null; + const cues: Cue[] = []; + let duplicatesDropped = 0; + let zi = 0; + let lastZero: number | null = null; + for (const e of entries) { + let start = e.offsetMs / 1000; + if (e.live) { + if (e.id && replayIds.has(e.id)) { + duplicatesDropped++; + continue; + } + while (zi < zeros.length && zeros[zi].line <= e.line) lastZero = zeros[zi++].zeroMs; + if (liveZeroMs !== null) { + if (e.postedMs !== null) start = (e.postedMs - liveZeroMs) / 1000; + else { + const zero = lastZero ?? zeros[0]?.zeroMs ?? null; + if (zero !== null) start = (e.offsetMs + zero - liveZeroMs) / 1000; + } + } + } + cues.push({ start, end: start + 5, text: e.text }); + } cues.sort((a, b) => a.start - b.start); - return cues; + return { cues, stats: { liveLines, replayLines, duplicatesDropped, captureZeroMs } }; +} + +export function parseLiveChat(src: string, opts: ParseLiveChatOptions = {}): Cue[] { + return parseLiveChatDetailed(src, opts).cues; +} + +// --- the recording's zero ------------------------------------------------------ + +export type LiveChatClockBasis = + // the broadcast's start (metadata `release_timestamp`): a from-start + // recording's zero, and the post-live VOD's + | "broadcast-start" + // a recording begun "from now": its landed part's own start + | "recording-start" + // no zero known: the live lines kept the capture's clock + | "capture-start" + // no line was captured live: nothing was moved + | "replay"; + +export type LiveChatZero = { + zeroMs: number | null; + basis: Exclude<LiveChatClockBasis, "replay">; + certain: boolean; +}; + +// The part of live-recording.json this reads (lib/liveCapture.ts +// LiveRecordingRecord), structurally, so this file stays import-free. +export type LiveRecordingLike = { + status?: string; + // The record's own mode, for a part the record cannot show. + fromStart?: boolean; + landedPart?: number; + parts?: { fromStart?: boolean; startedAt?: string }[]; + reach?: { fromStart?: boolean; missingSeconds?: number | null } | null; +}; + +/** + * The epoch ms the RECORDING's clock (the cues', the saved container's) is + * zero at, for a YouTube chat captured live. + * + * - The part that made the media — the landed one, or the latest while it is + * still recording (a chat can be normalized before the recording lands) — + * recorded from the start, or no recording at all (the media is the + * post-live VOD): the broadcast's start, `release_timestamp`, plus the + * stretch a recorded playlist reach said was no longer listed. Certain to + * the second (measured 20 Nov: four lines a streamer read aloud sat 6–14 s + * after it — the stream's latency and the reading, which stay). + * - A part recorded "from now": that part's start — yt-dlp's start-up and the + * live edge's lag are not known, so it is NOT certain. With no readable + * start, no zero: the broadcast's start is known to be wrong for it. + * - A failed or cancelled recording that landed nothing did not make the + * media: as if there were none. + * - Neither known: null (the capture's clock stays). + */ +export function liveChatClockZero( + meta: { release_timestamp?: unknown } | null | undefined, + record: LiveRecordingLike | null | undefined, +): LiveChatZero { + const parts = Array.isArray(record?.parts) ? record.parts : []; + // The recording made the media when it landed a part or is still recording. + const madeMedia = typeof record?.landedPart === "number" || record?.status === "recording"; + const picked = typeof record?.landedPart === "number" ? parts[record.landedPart] : madeMedia ? parts.at(-1) : undefined; + const part = picked && typeof picked === "object" ? picked : undefined; + // The part's own mode, else the record's (a part missing from the record). + const fromStart = part && typeof part.fromStart === "boolean" ? part.fromStart : madeMedia ? record?.fromStart : undefined; + if (fromStart === false) { + const startedMs = typeof part?.startedAt === "string" ? Date.parse(part.startedAt) : NaN; + if (Number.isFinite(startedMs)) return { zeroMs: startedMs, basis: "recording-start", certain: false }; + // A "from now" recording with no readable start: the broadcast's start is + // known to be the WRONG zero here, so there is none. + return { zeroMs: null, basis: "capture-start", certain: false }; + } + const release = meta?.release_timestamp; + if (typeof release === "number" && Number.isFinite(release) && release > 0) { + const reach = madeMedia ? record?.reach : null; + const missing = + reach && reach.fromStart === false && typeof reach.missingSeconds === "number" ? reach.missingSeconds : 0; + return { zeroMs: (release + missing) * 1000, basis: "broadcast-start", certain: true }; + } + return { zeroMs: null, basis: "capture-start", certain: false }; +} + +// What live_chat.cues.json records of the clock it was put on (version 2). +export type LiveChatClock = { + basis: LiveChatClockBasis; + certain: boolean; + // The recording's zero the live lines were placed against. + zeroAt?: string; + // The median capture start, and how far after the zero it was. + captureStartedAt?: string; + shiftSeconds?: number; + liveLines: number; + replayLines: number; + duplicatesDropped: number; +}; + +export function liveChatClockOf(zero: LiveChatZero, stats: LiveChatParseStats): LiveChatClock { + const counts = { + liveLines: stats.liveLines, + replayLines: stats.replayLines, + duplicatesDropped: stats.duplicatesDropped, + }; + if (stats.liveLines === 0) return { basis: "replay", certain: true, ...counts }; + const capture = stats.captureZeroMs; + const placed = zero.zeroMs !== null; + return { + basis: placed ? zero.basis : "capture-start", + certain: placed ? zero.certain : false, + ...(placed ? { zeroAt: new Date(zero.zeroMs as number).toISOString() } : {}), + ...(capture !== null ? { captureStartedAt: new Date(capture).toISOString() } : {}), + ...(capture !== null && placed ? { shiftSeconds: Math.round(capture - (zero.zeroMs as number)) / 1000 } : {}), + ...counts, + }; } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,20 @@ # Changelog ## [Unreleased] +- **A chat captured while the stream was live is on the recording's clock.** + - yt-dlp times a chat captured live from the moment its capture began, not from the broadcast's start. A chat + fetched while a from-start recording ran therefore showed every message as early as the capture was late: 37 + minutes early on the stream that showed it. + - The live chat's cues now place each message captured live by its own posting time against the recording's + zero. For a from-start recording, or the post-live video, that is the broadcast's start (`release_timestamp`). + For a recording begun "from now" it is the recording's own start, marked not certain. + - A chat that holds both a live capture and the replay after it keeps the replay's copy of a message. A line + with no id is never dropped. A chat fetched as a replay is not moved. + - `live_chat.cues.json` is now version 2 and says which clock it is on in `clock` (basis, zero, shift, counts). + A version-1 file stays fresh: no build re-reads the raw chats. + - To repair one video: `pnpm ops fetch-chat {"slug","id","renormalize":true}`. It parses the raw chat already + on disk again, with no network, and is refused when there is none. The index build's fallback for a stale + chat uses the same clock. - **A fetch the platform refused for one video now records why.** - The chat replay pass (`fetch-chat`, the chat backlog, find-clips) and `refresh-metadata` used to drop a refusal such as "Join this channel to get access to members-only content". A stream backfilled "public" while it was diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts @@ -1,9 +1,9 @@ import { fetchChatAction } from "../../../channels/[slug]/videos/[id]/mediaToolsActions"; -import { jobResponse, ops, optString, reqSlug, reqVideoId } from "../_lib"; +import { jobResponse, ops, optBool, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, queueKey? } -> { ok: true, jobId } +// POST { slug, id, queueKey?, renormalize? } -> { ok: true, jobId } // // ONE video's live chat replay, and nothing else (release 36, lane A; // controller/fetchLiveChat.ts): the chat-only yt-dlp pass the managed download @@ -16,8 +16,16 @@ export const dynamic = "force-dynamic"; // here and fresh, a video that was never live, a held platform or one in a // rate-limit cooldown. Refused: an id with no data/<id>/, a channel whose text // cannot be read. A pass that finds no replay ends `done` and says so. +// +// `renormalize: true` parses the raw chat already on disk again (fresh or +// not) onto the recording's clock, with no network: refused when no raw is +// here — it never fetches. export async function POST(request: Request) { - return ops(request, ["slug", "id", "queueKey"], async (body) => - jobResponse(await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"))), + return ops(request, ["slug", "id", "queueKey", "renormalize"], async (body) => + jobResponse( + await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"), { + renormalize: optBool(body, "renormalize") === true, + }), + ), ); } diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts @@ -53,7 +53,12 @@ export async function attachVideoMediaAction( }); } -export async function fetchChatAction(slug: string, videoId: string, queueKey?: string): Promise<StreamActionResult> { +export async function fetchChatAction( + slug: string, + videoId: string, + queueKey?: string, + opts: { renormalize?: boolean } = {}, +): Promise<StreamActionResult> { if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; const paths = getPaths(); const config = await readChannelConfig(paths, slug); @@ -65,6 +70,7 @@ export async function fetchChatAction(slug: string, videoId: string, queueKey?: channelConfig: config, cookiePolicy: resolveCookiePolicy(getSettings(), config), ...(queueKey !== undefined ? { queueKey } : {}), + ...(opts.renormalize ? { renormalize: true } : {}), afterRun: () => safeRevalidate([`/channels/${slug}/videos/${videoId}`]), }); } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -49,6 +49,7 @@ // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait +// pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait // pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}' // pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}' // pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait @@ -1878,7 +1879,12 @@ export function usage() { " that finds no replay ends done and says so. A pass the source refuses for", " the video as members-only or private records that in its", " availability.json (source fetch); a removal is recorded only by the", - " channel's Check availability.", + " channel's Check availability. A chat captured while the stream was live", + " is put on the recording's clock (the broadcast's start, or a recording", + ' begun "from now" its own start) and its cues say which in "clock".', + ' "renormalize": true parses the raw chat already on disk again, fresh or', + " not, with no network — for a chat normalized before that; refused when no", + " raw is here (it never fetches).", "", 'fetch-chat-backlog fetches a channel\'s stream chats after its downloads:', ' {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose',