// RECORD A LIVE STREAM FROM ITS START — `pnpm ops record-live`, "Record live" // on the channel and video pages (plans/live-capture.md; what the platforms' // playlists hold is lib/liveCapture.ts's header). // // ONE JOB PER STREAM, until it ends — hours — on its own queue // (`record-live::`), never a platform's download queue and never the // heavy slot (only the browser of path B takes it, briefly). In order: // // 1. The record: data// and one metadata-only pass (refreshVideoMetadata // — the channel's cookies, the platform's pace). A stream that is not // live (or upcoming) is refused: download it as a video. A Kick channel // URL is first resolved to its ongoing VOD (the livestream's uuid), which // is the id the archive keys Kick by. // 2. The recording, into a staging file beside the store dir (the store's // disk), MPEG-TS so a recording cut short is still a readable file: // rumble & the rest path A — yt-dlp (the fork) `--live-from-start`, the // channel's own args (Rumble's impersonation, // cookies). yt-dlp saying it cannot start at the // start → `--no-live-from-start` with ffmpeg told // `-live_start_index 0` (the same thing for any DVR // playlist, the fork or not). A refused extraction on // Rumble → path B: the page opened in a headed // Chromium under xvfb (liveSniff.mjs) for its // playlist, then ffmpeg records that from its first // listed segment. // youtube path A with SEPARATE streams (`separate`, the // platform's default): from its start YouTube offers // only DASH video and audio, so the video at the // height plus the best audio, `.f.` // while recording, merged by yt-dlp at the end; a // pair left unmerged (a cancel, a crash) is merged // here before the landing (resolvePart). // kick the ongoing VOD's EVENT playlist polled from segment // 0, each new segment appended (pollEventPlaylist), // and — the operator's by-hand workflow, as insurance // — the channel's live stream by yt-dlp beside it. // 3. When the stream ends (or on Cancel: the recorders get SIGINT, so the // files are finalized), the metadata is read once more (the ended // stream's duration), and the LONGEST part — with any part an earlier, // interrupted run left — is landed by landMediaFile, the landing // import-media uses: probe, keep the longer over a container already in // the store, `-c copy` remux to mp4, the store, audio., the archive // line, media-import.json. A part the landed one is known to contain (a // shorter part of this run, both from the start) is removed; every other // part that holds media — an earlier run's, one recorded from another // point of the stream, one that cannot be landed — is KEPT in staging and // listed on the record and the channel's row (keptParts) until a person // decides. Nothing removes those automatically. // 4. live-recording.json beside the record says what was recorded, how, and // what was landed; the "Do not clean" marker when asked; the hand-off to // the transcription lane (never lifting a pause). import path from "node:path"; import { spawn } from "node:child_process"; import { createWriteStream } from "node:fs"; import { link, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; import { uptime } from "node:os"; import { StringDecoder } from "node:string_decoder"; import { execa } from "execa"; import type { ChannelConfig } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { alwaysCookies, type ResolvedCookiePolicy } from "../lib/cookiePolicy"; import { BROWSER_FALLBACK_PLATFORMS, LIVE_DEFAULT_MAX_HEIGHT, LIVE_RATE_LIMIT_WAIT_MS, LIVE_RECOVERY_EVERY_MS, LIVE_RECOVERY_MAX_TRIES, LIVE_RESTART_CONFIRM_MS, LIVE_RESTART_WAIT_MS, LIVE_WATCH_MS, LIVE_INSURANCE_DELAY_MS, LIVE_INSURANCE_END_GRACE_MS, LIVE_INSURANCE_MARGIN_MS, LIVE_INSURANCE_MAX_STARTS, LIVE_INSURANCE_MAX_STARTS_PER_HOUR, LIVE_INSURANCE_BEHIND_SECONDS, parseFragProgress, catchUpTracker, insuranceDecision, restartWaitMs, classifyAttempt, extractionRefused, ffmpegLiveArgs, firstSequenceOf, formatUnavailable, lastErrorLine, liveAttemptSchedule, liveFailureClass, livePartFiles, mergeStreamsArgs, newSegments, parsePlaylist, pickVariant, playlistReach, separateStreamsDefault, spanWords, ytdlpLiveArgs, type KeptPart, type LiveVerification, type LiveBootRestartState, type LiveInsurance, type LiveJoinsRecord, type RemovedPart, type LiveFailureClass, type LivePart, type LivePartFiles, type LivePartMethod, type LiveRecordingRecord, type MediaPlaylist, type MediaSegment, type MissingStream, type PlaylistReach, type StartRecovery, type StreamCoverage, type LiveTranscriptRedo, } from "../lib/liveCapture"; import { WHISPER_FILENAME } from "../lib/videoStatus"; import { parseTranscriptJson } from "../lib/whisper"; import { readStoredText } from "../lib/storedText-server"; import { dropFragments, dropFragmentsAbove, fragmentGaps, fragNumbers, readYtdlIndex, reconcileStream, streamEqualsFragments } from "../lib/liveFragments-server"; import { verifyMerged, verifyScan } from "../lib/liveVerify-server"; import { liveJoinsSidecar, liveRecordingSidecar } from "../lib/mediaImport-server"; import { ffmpegJoinDeps, joinLiveParts, type JoinDeps } from "./liveJoin"; import { loadLiveRecordingRows, patchLiveRecordingRow, rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server"; import { liveInsuranceWhenBehind, liveRecordingCheckCommand, liveStallMinutes } from "./liveRecordings"; import { markLiveBootRestart } from "./liveRecordingBoot"; import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; import type { Paths } from "../lib/paths"; import { detectPlatform } from "../lib/platform"; import { savedVideoDir, savedVideoPath, savedVideoRoot } from "../lib/savedVideo"; import { loadSavedVideo, savedVideoPointerPath } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; import { applyPendingKeep, loadPendingKeep } from "../lib/pendingKeep-server"; import { mp4CanHold, type MediaProbe } from "../lib/mediaImport"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { channelExtraArgs, configForVideoUrl } from "../ytdlp/channelArgs"; import { browserUserAgentOr } from "../lib/browserUserAgent-server"; import { dataDirIdForUrl } from "../ytdlp/runYtdlp"; import { ensureStoreRoot, landMediaFile, probeMedia, readHandoffFacts, transcriptionHandoffLines, type LandMediaDeps, LAND_MEDIA_DISK_MARGIN_BYTES, } from "./landMedia"; import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; import { findVideoSourceUrl } from "./undownloadedVideos"; import { jitterYtdlpSleeps } from "../lib/jitter"; import { refuseInstagramYtdlp } from "../lib/instagram/ytdlp"; import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip"; import { jitterMs } from "../lib/jitter"; import "../lib/childKillGuard"; // What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits). import "../lib/childEnvGuard.mjs"; export const RECORD_LIVE_JOB_KIND = "record-live"; export const RECORD_LIVE_RESULT_MARKER = "@@record-live "; export const RECORD_LIVE_BODY_KEYS = [ "slug", "id", "url", "fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note", "dryRun", "preclip", "insurance", ] as const; // The user agent path B's ffmpeg and the playlist reads present: the Firefox on // this machine (lib/browserUserAgent-server.ts) — the one whose cookies and UA // the Rumble channels' yt-dlp spawns carry — else the module's fixed Firefox, // for a machine with none (the request still has to look like a browser). It // was a pinned Firefox 156 here, already behind the browser. export function liveFetchUserAgent(): string { return browserUserAgentOr(); } // Kick's VOD poller: how often the playlist is read, and how long it may stop // growing before the stream counts as over (shorter once the channel's live // stream has ended). export const VOD_POLL_MS = 20_000; export const VOD_IDLE_END_MS = 10 * 60_000; export const VOD_IDLE_AFTER_LIVE_END_MS = 2 * 60_000; // A recorder that ignores SIGINT this long is killed. export const RECORDER_GRACE_MS = 60_000; // After the recorder exits, how long its output may take to drain before a // process still holding it is killed (REVIEW-5 B4). export const RECORDER_EXIT_DRAIN_MS = 3_000; // DESIGN-4 3: the waits before a resume after a fragment could not be // fetched, at the same fragment; past them a fresh from-start part. export const FRAGMENT_ABORT_WAITS_MS: readonly number[] = [20_000, 60_000, 180_000]; // REVIEW-7 1: while the network is down, the waits between two reads (or two // resumes): then every 5 min, for as long as it takes. Never a restart spent. export const OFFLINE_READ_WAITS_MS: readonly number[] = [20_000, 60_000, 180_000, 300_000]; // The store's disk must have this much free before a recording starts (four // hours of 720p is ~6 GB, of 1080p ~9 GB). export const RECORD_LIVE_MIN_FREE_BYTES = 20 * 1024 ** 3; // Live-edge recorders in a row that capture nothing: the evidence a stream // that still reads live has ended (REVIEW-2 3.1 of live-guard-2). export const LIVE_EDGE_EMPTY_TO_END = 3; // A from-start part short of the live edge by more than max(this, 1 % of the // stream so far) leaves a span in no part: recovered beside the live edge. export const LIVE_GAP_TOLERANCE_SECONDS = 180; // yt-dlp's YouTube from-start generator holds 120 h (MAX_DURATION): past it // a saved fragment index no longer lines up. 119 h (REVIEW-5 note 8): an // hour's margin, as yt-dlp measures the age again after its extraction. export const LIVE_RESUME_MAX_AGE_MS = 119 * 3_600_000; // A restart after the editor's: the stream's state read again after these // waits when it could not be read (three reads over about ten minutes). export const LIVE_BOOT_STATE_READ_WAITS_MS: readonly number[] = [120_000, 480_000]; export type RecordLiveRequest = { slug: string; id?: string; url?: string; // Default true. fromStart?: boolean; // null = the tallest. Default LIVE_DEFAULT_MAX_HEIGHT. maxHeight?: number | null; // Separate video + audio streams, merged (true), or one muxed stream // (false). Default: the platform's (separateStreamsDefault — YouTube // separate, Rumble and Kick muxed). separate?: boolean; transcribe?: boolean; doNotClean?: boolean; note?: string; dryRun?: boolean; // LIVE PRE-CLIP (plans/live-preclip.md): transcribe and mine the recording // while it records — its own job (controller/livePreclip.ts), started once // the first part begins. Implies `transcribe` unless that is false. preclip?: PreclipOptions; // THE INSURANCE RECORDER (slice 4, lib/liveCapture.ts LiveInsurance): true // = the live edge beside the from-start recording until it catches up; // "whole" = the whole stream; false = none. Absent: on exactly when the // stream is marked keep before or when the recording starts. insurance?: boolean | "whole"; // INTERNAL (never a body key): the boot pass's restart of the interrupted // run that started at this time (controller/liveRecordingBoot.ts). The // run reads the stream's state first and records only if it is live. resumeOf?: string; }; export function parseRecordLiveRequest( body: Record, preclipDefaults?: Omit, ): RecordLiveRequest | { error: string } { const str = (k: string) => (typeof body[k] === "string" ? (body[k] as string).trim() : undefined); const slug = str("slug"); if (!slug) return { error: '"slug" is required' }; const url = str("url"); const id = str("id"); if (!url && !id) return { error: 'Give the stream\'s page as "url", or a record already here as "id"' }; if (url && !/^https?:\/\//i.test(url)) return { error: `"url" must be an http(s) URL: ${url}` }; if (id !== undefined && !/^[\w.-]+$/.test(id)) return { error: `"${id}" is not a record id` }; let maxHeight: number | null | undefined; if (body.maxHeight !== undefined) { if (body.maxHeight === null) maxHeight = null; else if (typeof body.maxHeight === "number" && Number.isInteger(body.maxHeight) && body.maxHeight >= 144) { maxHeight = body.maxHeight; } else return { error: '"maxHeight" is a height in pixels (≥ 144), or null for the tallest' }; } const out: RecordLiveRequest = { slug }; if (url) out.url = url; if (id) out.id = id; if (maxHeight !== undefined) out.maxHeight = maxHeight; for (const k of ["fromStart", "separate", "transcribe", "doNotClean", "dryRun"] as const) { const v = body[k]; if (v === undefined) continue; if (typeof v !== "boolean") return { error: `"${k}" must be true or false` }; out[k] = v; } const note = str("note"); if (note) out.note = note; if (body.insurance !== undefined) { if (body.insurance === true || body.insurance === false || body.insurance === "whole") out.insurance = body.insurance; else return { error: '"insurance" is true (until the start catches up), "whole" (the whole stream) or false' }; } const preclip = parsePreclipKnob(body.preclip, preclipDefaults); if (preclip && "error" in preclip) return preclip; if (preclip) { out.preclip = preclip; if (out.transcribe === undefined) out.transcribe = true; } return out; } // --- which stream ------------------------------------------------------------------ export type RecordLivePlan = { url: string; platform: string; // Null: a Kick channel URL, resolved to its ongoing VOD in the job. id: string | null; // Kick: the channel's slug on kick.com. kickChannel?: string; }; const KICK_VOD_RE = /^https?:\/\/(?:www\.)?kick\.com\/([\w-]+)\/videos\/([\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12})/i; const KICK_VIDEO_RE = /^https?:\/\/(?:www\.)?kick\.com\/video\/([\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12})/i; const KICK_CHANNEL_RE = /^https?:\/\/(?:www\.)?kick\.com\/([\w-]+)\/?(?:videos\/?)?(?:[?#].*)?$/i; export function planForUrl(url: string): RecordLivePlan | { error: string } { const platform = detectPlatform(url) ?? "unknown"; if (platform === "kick") { const vod = KICK_VOD_RE.exec(url); if (vod) return { url, platform, id: vod[2]!.toLowerCase(), kickChannel: vod[1]!.toLowerCase() }; // The canonical form (lib/platform.ts) names no channel: the record's // `uploader_id` does, once read. const video = KICK_VIDEO_RE.exec(url); if (video) return { url, platform, id: video[1]!.toLowerCase() }; const ch = KICK_CHANNEL_RE.exec(url); if (ch && !["video", "videos", "clips", "categories", "search"].includes(ch[1]!.toLowerCase())) { return { url, platform, id: null, kickChannel: ch[1]!.toLowerCase() }; } return { error: `${url} is not a Kick channel or VOD page` }; } const id = dataDirIdForUrl(url); if (!id) return { error: `No record id can be read from ${url}` }; return { url, platform, id }; } export async function resolveRecordLivePlan( paths: Paths, req: RecordLiveRequest, config: ChannelConfig, ): Promise { if (req.url) { const plan = planForUrl(req.url); if ("error" in plan) return plan; if (req.id && plan.id && req.id !== plan.id) { return { error: `"id" ${req.id} is not the id ${req.url} is archived by (${plan.id}); give one of them` }; } return plan; } const id = req.id!; const videoDir = path.join(paths.channelsDir, req.slug, "data", id); if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) { return { error: `${req.slug} has no record ${id}: give the stream's page as "url"` }; } const url = await findVideoSourceUrl(paths, req.slug, id, config); if (!url) return { error: `No source page is known for ${req.slug}/${id}: give it as "url"` }; const plan = planForUrl(url); if ("error" in plan) return plan; return { ...plan, id }; } // The command that answers for this recording (the record-live reply's // `check`): its id from the body's `id`, else the URL's; a Kick channel URL // (its VOD is found in the job) names the channel alone. export function recordLiveCheckCommand(slug: string, body: { id?: unknown; url?: unknown }): string { const id = typeof body.id === "string" && body.id.trim() ? body.id.trim() : null; const plan = !id && typeof body.url === "string" ? planForUrl(body.url.trim()) : null; const known = id ?? (plan && !("error" in plan) ? plan.id : null); return known ? liveRecordingCheckCommand(slug, known) : `pnpm ops get live-recordings ${slug}`; } export function recordLiveQueueKey(slug: string, id: string | null, kickChannel?: string): string { return `record-live:${slug}:${id ?? `kick-${kickChannel ?? "?"}`}`; } // --- the recorder process ---------------------------------------------------------- // `exitTail`: what the recorder printed (both streams) after its last // progress line — its last words near the exit, what a failure is classified // from (REVIEW-2 3.3 of live-guard-2); never a line from hours earlier. export type RecorderOutcome = { exitCode: number | null; stderrTail: string; signalled: boolean; exitTail?: string }; // The recorder's last words: its own exitTail, else (a stub's stderr) the // lines after the last progress line, at most the last 20. export function recentOutput(o: Pick): string { if (o.exitTail !== undefined) return o.exitTail; const lines = o.stderrTail.split(/[\r\n]+/).map((l) => l.trim()).filter(Boolean); let i = lines.length; while (i > 0 && !isProgressLine(lines[i - 1]!)) i--; return lines.slice(Math.max(i, lines.length - 20)).join("\n"); } export type RecorderSpawn = (opts: { bin: string; args: string[]; cwd: string; onLog: (s: string) => void; signal: AbortSignal; label: string; // Every line the recorder prints, progress included (before the thinning). onLine?: (line: string) => void; // The recorder's pid, once spawned (REVIEW-6 9: the stem lock names it). onSpawn?: (pid: number) => void; }) => Promise; // A progress line yt-dlp or ffmpeg repeats every second for hours. yt-dlp // numbers each of a separate-streams recording's lines (`1: [download] …`, // `2: [download] …`): those are progress too (20 Nov 2026: unthinned, they // wrote ~1 MB of job log a minute while a from-start download caught up). const PROGRESS_RE = /^(?:\d+:\s*)?(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/; const PROGRESS_EVERY_MS = 5 * 60_000; // REVIEW-6 1: a fragment's FINAL failure as yt-dlp prints it — the error // line (`ERROR: \r[download] Got error: …`, joined by the recorder's reader), // a "Giving up after N retries" on a fragment, or "fragment N not found, // unable to continue". Never a retry ("Retrying fragment N (k/10)"). export function isFragmentFatalLine(l: string): boolean { if (/Retrying fragment/i.test(l)) return false; return /^(?:\d+:\s*)?ERROR: \[download\] Got error|Got error: .*Giving up after \d+ retries|fragment \d+ not found, unable to continue/i.test(l); } // Never thinned (DESIGN-4 3): what says a fragment is missing, failed, or the // state is not trusted — each such line is in the job's log. const NEVER_THINNED_RE = /Skipping fragment|Got error|fragment \d+ not found|\.ytdl file is corrupt|Inconsistent state|Unable to resume/i; export function isProgressLine(line: string): boolean { return PROGRESS_RE.test(line) && !NEVER_THINNED_RE.test(line); } // The longest a fragment can be taken to be (YouTube's are 1, 2 or 5 s). export const FRAGMENT_SECONDS_CAP = 10; // REVIEW-7 4: one fragment's length, from a stream file's kept fragments and // the landed length (undefined when nothing tells it). export async function fragmentSecondsOf(dir: string, streams: readonly string[], seconds: number | null): Promise { if (!seconds || !streams.length) return undefined; const names = await readdir(dir).catch(() => [] as string[]); // REVIEW-8 3: the HIGHEST fragment number (or the state's index), never the // count of files left — a part whose fragments were dropped keeps a few. const nums = fragNumbers(streams[0]!, names); const idx = await readYtdlIndex(path.join(dir, streams[0]!)); const n = Math.max(nums.length ? nums[nums.length - 1]! : 0, typeof idx === "number" ? idx : 0); return n > 1 ? Math.min(FRAGMENT_SECONDS_CAP, seconds / (n - 1)) : undefined; } // A `.ytdl` state's fragment index, or null when it does not parse. function readYtdlRaw(raw: string): number | null { try { const idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index; return typeof idx === "number" && idx >= 0 ? idx : null; } catch { return null; } } // NOTE 5 (REVIEW-5) — THE STEM LOCK: `.rec.lock` in the store's staging // dir, made with O_EXCL while a recorder of that stem runs, removed when it // returns. STALE when the process that made it is gone (its pid answers no // signal) or it was made before the machine last booted (a pid may be // reused): a stale lock is taken over, said. Held by a live process (this // editor's or another's), the recorder is not started on that stem. export type StemLock = { ok: true; release: () => Promise; setRecorder: (pid: number) => Promise }; export async function takeStemLock(dir: string, stem: string): Promise { const file = path.join(dir, `${stem}.rec.lock`); const at = new Date().toISOString(); const body = (recorderPid?: number) => JSON.stringify({ pid: process.pid, ...(recorderPid ? { recorderPid } : {}), at }); for (let tries = 0; tries < 2; tries++) { // REVIEW-7 6: never a lock a reader can catch empty — written whole to a // temp file, then linked into place (fails if one is there) or renamed // over (its update). const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; try { await writeFile(tmp, body()); await link(tmp, file); await rm(tmp, { force: true }); return { ok: true, release: () => rm(file, { force: true }), // REVIEW-6 9: the RECORDER's pid too — it runs in its own process // group and outlives an editor killed outside the unit. setRecorder: async (pid: number) => { const t2 = `${file}.${pid}.tmp`; await writeFile(t2, body(pid)).catch(() => {}); await rename(t2, file).catch(() => {}); }, }; } catch (err) { await rm(tmp, { force: true }); if ((err as NodeJS.ErrnoException).code !== "EEXIST") return { ok: false, why: `its lock could not be made (${(err as Error).message})` }; } const held = await readFile(file, "utf8").then((t) => JSON.parse(t) as { pid?: number; recorderPid?: number; at?: string }, () => null); const bootMs = Date.now() - uptime() * 1000; const alive = (pid: unknown) => { if (typeof pid !== "number") return false; try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === "EPERM"; } }; // Stale only when NEITHER the editor nor the recorder it names is alive, // or it was made before the machine last booted (pids are reused). const stale = !held || (!alive(held.pid) && !alive(held.recorderPid)) || !held.at || Date.parse(held.at) < bootMs; if (!stale) { const who = alive(held!.recorderPid) ? `its recorder, pid ${held!.recorderPid}` : `pid ${held!.pid}`; return { ok: false, why: `another recorder holds ${path.basename(file)} (${who}, since ${held!.at})` }; } await rm(file, { force: true }); } return { ok: false, why: `its lock ${path.basename(file)} could not be taken` }; } // A stem's marks that outlive a run (DESIGN-4): its skipped fragments, and // that its kept fragments were dropped for want of disk. type StemMarks = { skipped?: { count: number; positions: number[] }; dropped?: string }; export async function readStemMarks(dir: string, stem: string): Promise { return readFile(path.join(dir, `${stem}.live-marks.json`), "utf8").then((t) => JSON.parse(t) as StemMarks, () => ({})); } async function writeStemMarks(dir: string, stem: string, patch: StemMarks): Promise { const cur = await readStemMarks(dir, stem); await writeFile(path.join(dir, `${stem}.live-marks.json`), JSON.stringify({ ...cur, ...patch })).catch(() => {}); } // ONE RECORDER: spawned in a process group of its own (REVIEW-5 B4), so a // stop reaches the whole tree — yt-dlp and the ffmpeg it starts with its own // stdout and stderr: SIGINT (yt-dlp asks its ffmpeg to quit, and ffmpeg // finishes its file on SIGINT itself), SIGTERM (a resumable part: nothing // finishes), then SIGKILL after RECORDER_GRACE_MS. Its output is in the job's // log with the per-second progress thinned to one line every five minutes. // It returns when yt-dlp EXITS: a grandchild still holding the pipes a few // seconds later is killed with the group, never waited on. export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, label, onLine, onSpawn }) => new Promise((resolve) => { onLog(`[${label}] $ ${bin} ${args.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ")}\n`); const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"], detached: true }); if (child.pid) onSpawn?.(child.pid); const killTree = (sig: NodeJS.Signals) => { try { if (child.pid) process.kill(-child.pid, sig); else child.kill(sig); } catch { child.kill(sig); } }; let tail = ""; let sinceProgress = ""; let lastProgress = 0; let signalled = false; let killTimer: NodeJS.Timeout | null = null; // REVIEW-6 1: lines are cut on "\n" ACROSS chunks (a line may arrive in // two), then on "\r" (a progress line rewrites itself). yt-dlp prints an // error as `ERROR: \r[download] Got error: …`: a bare `ERROR:` (or // `WARNING:`) segment is joined to the segment after it, so the line read // is the one yt-dlp meant. const pend = { out: "", err: "" }; const decoders = { out: new StringDecoder("utf8"), err: new StringDecoder("utf8") }; const segmentsOf = (line: string): string[] => { const segs = line.split("\r").map((x) => x.trim()).filter(Boolean); const out: string[] = []; for (let i = 0; i < segs.length; i++) { if (/^(?:\d+:\s*)?(?:ERROR|WARNING):$/.test(segs[i]!) && i + 1 < segs.length) { out.push(`${segs[i]} ${segs[i + 1]}`); i++; } else out.push(segs[i]!); } return out; }; const feedText = (text: string, isErr: boolean, flush = false) => { const key = isErr ? "err" : "out"; const all = pend[key] + text; const lines = all.split("\n"); let rest = flush ? "" : lines.pop()!; for (const line of lines) for (const l of segmentsOf(line)) emit(l); // A line that only ever rewrites itself (ffmpeg's `frame=` with "\r" // and no "\n"): its finished segments are read now; the last one, and // a bare `ERROR:` waiting for what follows it, stay pending. const cut = rest.lastIndexOf("\r"); if (cut >= 0) { let done = rest.slice(0, cut); let keep = rest.slice(cut + 1); const lastSeg = done.slice(done.lastIndexOf("\r") + 1); if (/^\s*(?:\d+:\s*)?(?:ERROR|WARNING):\s*$/.test(lastSeg)) { done = done.slice(0, done.length - lastSeg.length); keep = `${lastSeg}\r${keep}`; } for (const l of segmentsOf(done)) emit(l); rest = keep; } pend[key] = rest.slice(-64 * 1024); }; const feed = (chunk: Buffer, isErr: boolean) => { const text = decoders[isErr ? "err" : "out"].write(chunk); if (isErr) tail = (tail + text).slice(-32 * 1024); feedText(text, isErr); }; const emit = (l: string) => { { onLine?.(l); if (isProgressLine(l)) sinceProgress = ""; else sinceProgress = (sinceProgress + l + "\n").slice(-8 * 1024); if (isProgressLine(l)) { const now = Date.now(); if (now - lastProgress < PROGRESS_EVERY_MS) return; lastProgress = now; } onLog(`[${label}] ${l}\n`); } }; child.stdout?.on("data", (c: Buffer) => feed(c, false)); child.stderr?.on("data", (c: Buffer) => feed(c, true)); const onAbort = () => { if (signalled) return; signalled = true; // SIGTERM (DESIGN-3): yt-dlp installs no handler, so it ends without // finishing and a from-start download's `.ytdl` state stays. const how = signal.reason === "SIGTERM" ? "SIGTERM" : "SIGINT"; onLog(`[${label}] stopping: ${how === "SIGTERM" ? "SIGTERM, its state kept for a resume" : "SIGINT, so the recording is finalized"}\n`); killTree(how); killTimer = setTimeout(() => killTree("SIGKILL"), RECORDER_GRACE_MS); }; if (signal.aborted) onAbort(); else signal.addEventListener("abort", onAbort, { once: true }); child.on("error", (err) => { tail += `\n${err.message}`; }); let done = false; const finish = (code: number | null) => { if (done) return; done = true; if (killTimer) clearTimeout(killTimer); signal.removeEventListener("abort", onAbort); resolve({ exitCode: code, stderrTail: tail, signalled, exitTail: sinceProgress }); }; child.on("close", (code) => { // What is left without a final newline. feedText(decoders.out.end(), false, true); feedText(decoders.err.end(), true, true); finish(code); }); child.on("exit", (code) => { // Its output drains on `close`; a grandchild that keeps the pipes open // after yt-dlp is gone is killed with the group, and the recorder returns. setTimeout(() => { if (done) return; onLog(`[${label}] yt-dlp exited (${code ?? "signal"}); a process it started still holds its output: the group is killed.\n`); killTree("SIGKILL"); child.stdout?.destroy(); child.stderr?.destroy(); finish(code); }, RECORDER_EXIT_DRAIN_MS); }); }); // --- Kick: the ongoing VOD, polled ------------------------------------------------ export type FetchText = (url: string, signal: AbortSignal) => Promise; export type FetchBytes = (url: string, signal: AbortSignal) => Promise; function withTimeout(signal: AbortSignal, ms: number): AbortSignal { return AbortSignal.any([signal, AbortSignal.timeout(ms)]); } export const fetchText: FetchText = async (url, signal) => { const r = await fetch(url, { headers: { "user-agent": liveFetchUserAgent() }, signal: withTimeout(signal, 30_000) }); if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`); return r.text(); }; export const fetchBytes: FetchBytes = async (url, signal) => { const r = await fetch(url, { headers: { "user-agent": liveFetchUserAgent() }, signal: withTimeout(signal, 60_000) }); if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`); return new Uint8Array(await r.arrayBuffer()); }; function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (signal.aborted) return resolve(); const t = setTimeout(done, ms); function done() { clearTimeout(t); signal.removeEventListener("abort", done); resolve(); } signal.addEventListener("abort", done, { once: true }); }); } export type PollResult = { segments: number; seconds: number; gaps: number; firstSeq: number | null; ended: string }; // THE ONGOING VOD, RECORDED WHOLE: read the EVENT playlist every `pollMs`, // append each segment not yet taken (in order, three tries each — a segment // that never comes is a gap, counted), until the playlist has not grown for // `idleEndMs` — or for `idleAfterLiveEndMs` once `liveEnded()` says the // channel's stream is over — or the signal aborts. export async function pollEventPlaylist(opts: { playlistUrl: string; output: string; onLog: (s: string) => void; signal: AbortSignal; liveEnded?: () => boolean; pollMs?: number; idleEndMs?: number; idleAfterLiveEndMs?: number; fetchText?: FetchText; fetchBytes?: FetchBytes; now?: () => number; wait?: (ms: number, signal: AbortSignal) => Promise; }): Promise { const getText = opts.fetchText ?? fetchText; const getBytes = opts.fetchBytes ?? fetchBytes; const now = opts.now ?? Date.now; const wait = opts.wait ?? sleep; const pollMs = opts.pollMs ?? VOD_POLL_MS; const idleEnd = opts.idleEndMs ?? VOD_IDLE_END_MS; const idleAfterLive = opts.idleAfterLiveEndMs ?? VOD_IDLE_AFTER_LIVE_END_MS; const out = createWriteStream(opts.output, { flags: "a" }); const write = (b: Uint8Array) => new Promise((resolve, reject) => out.write(b, (err) => (err ? reject(err) : resolve()))); let lastSeq: number | null = null; let firstSeq: number | null = null; let segments = 0; let seconds = 0; let gaps = 0; let lastGrowth = now(); let ended = ""; let failures = 0; try { while (!opts.signal.aborted) { let pl: MediaPlaylist | null = null; try { const parsed = parsePlaylist(await getText(opts.playlistUrl, opts.signal), opts.playlistUrl); pl = parsed?.kind === "media" ? parsed : null; failures = 0; } catch (err) { if (opts.signal.aborted) break; failures += 1; opts.onLog(`[vod] the playlist read failed (${(err as Error).message})\n`); } const fresh: MediaSegment[] = pl ? newSegments(pl, lastSeq) : []; for (const seg of fresh) { if (opts.signal.aborted) break; let bytes: Uint8Array | null = null; for (let attempt = 1; attempt <= 3 && !bytes && !opts.signal.aborted; attempt++) { try { bytes = await getBytes(seg.uri, opts.signal); } catch (err) { if (attempt === 3) opts.onLog(`[vod] segment ${seg.seq} not fetched (${(err as Error).message}): a gap\n`); else await wait(2000 * attempt, opts.signal); } } if (bytes) { await write(bytes); segments += 1; seconds += seg.duration; if (firstSeq === null) firstSeq = seg.seq; } else if (!opts.signal.aborted) gaps += 1; lastSeq = seg.seq; lastGrowth = now(); } if (fresh.length) { opts.onLog(`[vod] ${segments} segment(s), ${Math.round(seconds)} s recorded (last ${lastSeq})\n`); } const idle = now() - lastGrowth; if (opts.liveEnded?.() && idle >= idleAfterLive) { ended = `the live stream ended and the VOD has not grown for ${Math.round(idle / 1000)} s`; break; } if (idle >= idleEnd) { ended = `the VOD has not grown for ${Math.round(idle / 1000)} s${failures ? ` (${failures} failed read(s))` : ""}`; break; } // Each read stretched by up to pacing.jitter (lib/jitter.mjs). await wait(jitterMs(pollMs), opts.signal); } } finally { await new Promise((resolve) => out.end(() => resolve())); } if (!ended) ended = "cancelled"; return { segments, seconds: Math.round(seconds * 1000) / 1000, gaps, firstSeq, ended }; } // --- path B: the page's own playlist ------------------------------------------------ export type SniffResult = { ok: boolean; playlists: string[]; status?: number | null; error?: string }; export type LiveSniffer = (opts: { paths: Paths; pageUrl: string; onLog: (s: string) => void; signal: AbortSignal }) => Promise; // liveSniff.mjs under `xvfb-run -a` (a headed Chromium is what passes // Rumble's Cloudflare), through the heavy slot when the checkout has the gate // — a browser for a few seconds is heavy enough to wait for the floor. export const sniffLivePlaylist: LiveSniffer = async ({ paths, pageUrl, onLog, signal }) => { const script = path.join(paths.monorepoRoot, "common", "ytdlp", "liveSniff.mjs"); const xvfb = await execa("which", ["xvfb-run"], { reject: false }).then((r) => (r.exitCode === 0 ? String(r.stdout).trim() : null)); const inner = xvfb ? [xvfb, "-a", process.execPath, script, paths.monorepoRoot, pageUrl] : [process.execPath, script, paths.monorepoRoot, pageUrl]; if (!xvfb) onLog("xvfb-run is not installed: the page is opened headless, which Rumble's Cloudflare refuses.\n"); const gate = path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs"); const gated = await stat(gate).then((s) => s.isFile(), () => false); // --urgent: a stream does not wait for a render in render mode — a few // seconds of browser now, or the recording misses its start. const [bin, ...args] = gated ? [process.execPath, gate, "--heavy", "--estimate", "1000", "--urgent", "--", ...inner] : inner; onLog(`Opening ${pageUrl} in a browser for its playlist${gated ? " (the heavy slot)" : ""}.\n`); const r = await execa(bin!, args, { reject: false, cancelSignal: signal, cwd: paths.monorepoRoot }); const line = String(r.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop(); if (!line) return { ok: false, playlists: [], error: `the browser printed nothing (exit ${r.exitCode}): ${String(r.stderr).slice(-300)}` }; try { return JSON.parse(line) as SniffResult; } catch { return { ok: false, playlists: [], error: `unreadable answer: ${line.slice(0, 200)}` }; } }; // The playlist to record out of what the page asked for: a variant of the // master (by height), else a DVR chunklist, else any chunklist, else the first. export async function choosePlaylist( sniffed: readonly string[], maxHeight: number | null, getText: FetchText, signal: AbortSignal, ): Promise { const master = sniffed.find((u) => /\/playlist\.m3u8/i.test(u) && !/chunklist/i.test(u)); if (master) { try { const parsed = parsePlaylist(await getText(master, signal), master); if (parsed?.kind === "master") { const v = pickVariant(parsed.variants, maxHeight); if (v) return v.url; } if (parsed?.kind === "media") return master; } catch { /* fall through to what the page itself chose */ } } return sniffed.find((u) => /chunklist.*_DVR\.m3u8/i.test(u)) ?? sniffed.find((u) => /chunklist/i.test(u)) ?? sniffed[0] ?? null; } // --- the run ------------------------------------------------------------------------- export type RecordLiveDeps = { spawn?: RecorderSpawn; sniff?: LiveSniffer; fetchText?: FetchText; fetchBytes?: FetchBytes; refresh?: RefreshRunner; land?: LandMediaDeps; handoff?: typeof readHandoffFacts; // Kick: the ongoing VOD of a channel (default: yt-dlp's listing of // kick.com//videos, its first entry). kickVod?: (channel: string, signal: AbortSignal) => Promise<{ id: string; url: string } | null>; poll?: typeof pollEventPlaylist; // ffmpeg over a separate-streams part left unmerged (mergeStreamsArgs). merge?: (args: string[], signal: AbortSignal) => Promise; freeBytes?: (dir: string) => Promise; now?: () => Date; // The wait between two recorder attempts (default: a sleep a Cancel ends), // and the stretch applied to it (default jitterMs, pacing.jitter). wait?: (ms: number, signal: AbortSignal) => Promise; // The wait before each start-recovery try beside a live-edge recording // (slice 2; default: `wait`). recoveryWait?: (ms: number, signal: AbortSignal) => Promise; jitter?: (ms: number) => number; // Whether the editor is shutting down (default: the job registry's): a run // stopped then is `interrupted`, never `cancelled`. shuttingDown?: () => boolean; // The stall watchdog's look (default LIVE_WATCH_MS) and how long without // growth is a stall (default settings.liveRecording.stallMinutes). watchMs?: number; stallMs?: number; // The insurance recorder's look for the from-start part's first bytes // (default 5 s), its margin after catch-up and its grace after the end // (defaults LIVE_INSURANCE_MARGIN_MS, LIVE_INSURANCE_END_GRACE_MS). insurancePollMs?: number; // settings.liveRecording.insuranceWhenBehind, for a test. insuranceWhenBehind?: boolean; // DESIGN-4 2: false — never a fresh from-start part (tests of the // live-edge path, as where from-start cannot reach the start). freshFromStart?: boolean; // DESIGN-4 4: the merged file against its stream files, and a file alone. verifyMerged?: (merged: string, streams: readonly string[], signal: AbortSignal) => Promise<{ ok: true } | { ok: false; why: string }>; // (The landing's fragmentSeconds is in the default; a test's own ignores it.) verifyScan?: (file: string, signal: AbortSignal) => Promise<{ ok: true } | { ok: false; why: string }>; insuranceMarginMs?: number; insuranceGraceMs?: number; // Joining parts at the landing (controller/liveJoin.ts; default ffmpeg's); // null never joins. join?: JoinDeps | null; // The free-space floor (default RECORD_LIVE_MIN_FREE_BYTES). minFreeBytes?: number; }; export type RecordLiveJobOpts = { paths: Paths; request: RecordLiveRequest; plan: RecordLivePlan; channelConfig: ChannelConfig; cookiePolicy: ResolvedCookiePolicy; // `replace`: transcribe again over an existing transcript (transcriptRedo). requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>; // The pre-clip job for this stream (request.preclip), asked for once the // first part begins. startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>; afterRun?: () => void | Promise; // The job running it: written into the record and the channel's row. jobId?: string; deps?: RecordLiveDeps; }; export type RecordLiveSummary = { slug: string; id: string; dryRun: boolean; parts: { method: LivePartMethod; seconds: number | null; fromStart: boolean }[]; landed: { kept: "new" | "existing"; seconds: number | null; container: string | null } | null; status: LiveRecordingRecord["status"]; reach?: PlaylistReach; }; type Meta = Record; async function readMeta(videoDir: string): Promise { try { const v = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")); return v && typeof v === "object" && !Array.isArray(v) ? (v as Meta) : null; } catch { return null; } } // The HLS format a recording of `meta` would take (the selector's choice). export function hlsFormatOf(meta: Meta, maxHeight: number | null): { url: string; height: number | null } | null { const formats = Array.isArray(meta.formats) ? (meta.formats as Meta[]) : []; const hls = formats .filter((f) => typeof f.url === "string" && /m3u8/.test(String(f.protocol ?? ""))) .map((f) => ({ url: String(f.url), height: typeof f.height === "number" ? f.height : null })); if (!hls.length) return null; const v = pickVariant( hls.map((f) => ({ url: f.url, height: f.height, width: null, bandwidth: null })), maxHeight, ); return v ? { url: v.url, height: v.height } : null; } const LIVE_STATES = new Set(["is_live", "is_upcoming", "post_live"]); async function defaultKickVod( paths: Paths, channel: string, cfg: ChannelConfig, cookies: string | undefined, signal: AbortSignal, ): Promise<{ id: string; url: string } | null> { const listing = `https://kick.com/${channel}/videos`; const r = await execa( paths.ytdlpBin, jitterYtdlpSleeps(["--ignore-config", "--flat-playlist", "--playlist-items", "1", "-J", ...channelExtraArgs(cfg, cookies), "--", listing]), { reject: false, cancelSignal: signal }, ); if (r.exitCode !== 0) return null; try { const j = JSON.parse(String(r.stdout)) as { entries?: Meta[] }; const e = j.entries?.[0]; const url = typeof e?.url === "string" ? e.url : null; const plan = url ? planForUrl(url) : null; return url && plan && !("error" in plan) && plan.id ? { id: plan.id, url } : null; } catch { return null; } } // ffmpeg through the heavy slot when the checkout has the gate (a stream copy // of hours of video, as the landing's remux is). // `strict`: any line ffmpeg writes (it runs at -loglevel error) is a failure — // the editor's own merge of a recording's streams (REVIEW-6 3); the heavy // slot's own waiting lines are not ffmpeg's. export async function runFfmpegHeavy(paths: Paths, args: string[], signal?: AbortSignal, o: { strict?: boolean } = {}): Promise { const gate = paths.monorepoRoot ? path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs") : null; const gated = gate !== null && (await stat(gate).then((s) => s.isFile(), () => false)); const r = await execa(gated ? process.execPath : paths.ffmpegBin, gated ? [gate, "--heavy", "--", paths.ffmpegBin, ...args] : args, { ...(signal ? { cancelSignal: signal } : {}), }); if (o.strict) { const said = String(r.stderr ?? "") .split(/\r?\n/) .map((l) => l.trim()) .filter((l) => l && !/^(?:queue-lock|heavy)[:\s]/i.test(l)); if (said.length) throw new Error(`ffmpeg's merge reported: ${said.slice(0, 3).join(" | ").slice(0, 400)}`); } } export type ResolvedPart = { file: string; seconds: number | null; merged?: boolean } | { error: string }; // WHAT ONE PART LANDS AS (null: it holds nothing). A finished file ffprobe // reads, with audio — the longest when there are several. Else its separate // streams, left unmerged by a cancel or a crash: a stream with video and audio // as it is; a video stream and an audio stream merged by ffmpeg (`-c copy`, // mp4 +faststart when the codecs fit, else mkv) into `.merged.`; // an audio stream alone as it is. Video with no audio is not landable. export async function resolvePart( g: LivePartFiles, dir: string, io: { probe: (file: string) => Promise; merge: (args: string[]) => Promise; say: (s: string) => void; }, ): Promise { const read = async (names: readonly string[]) => { const out: { file: string; probe: MediaProbe }[] = []; for (const n of names) { const file = path.join(dir, n); if ((await stat(file).then((s) => s.size, () => 0)) === 0) continue; const p = await io.probe(file); if (p) out.push({ file, probe: p }); } return out.sort((a, b) => (b.probe.seconds ?? -1) - (a.probe.seconds ?? -1)); }; const finishedAll = await read(g.finished); const finished = finishedAll.filter((f) => f.probe.audioCodec); if (finished.length) return { file: finished[0]!.file, seconds: finished[0]!.probe.seconds }; const streams = await read(g.streams); if (!streams.length) { if (finishedAll.length) return { error: `${path.basename(finishedAll[0]!.file)} holds no audio: nothing to transcribe` }; const bytes = await Promise.all([...g.finished, ...g.streams].map((n) => stat(path.join(dir, n)).then((s) => s.size, () => 0))); return bytes.some((b) => b > 0) ? { error: "ffprobe cannot read what it holds" } : null; } const both = streams.find((s) => s.probe.videoCodec && s.probe.audioCodec); if (both) return { file: both.file, seconds: both.probe.seconds }; const video = streams.find((s) => s.probe.videoCodec); const audio = streams.find((s) => s.probe.audioCodec); if (video && audio) { const mp4 = mp4CanHold(video.probe.videoCodec, audio.probe.audioCodec); const output = path.join(dir, `${g.stem}.merged.${mp4 ? "mp4" : "mkv"}`); io.say( `${g.stem}: its video and audio streams were left unmerged (${path.basename(video.file)}, ${path.basename(audio.file)}); ` + `merging them (stream copy) into ${path.basename(output)}.`, ); await rm(output, { force: true }); try { await io.merge(mergeStreamsArgs({ video: video.file, audio: audio.file, output, mp4 })); } catch (err) { // REVIEW-7 5: never left at a name the next run lands as finished. const aside = path.join(dir, `${g.stem}.merge-failed-${Date.now()}.${mp4 ? "mp4" : "mkv"}`); await rename(output, aside).catch(() => {}); throw new Error( `${(err as Error).message} — the merge's output is set aside as ${path.basename(aside)}; the streams are kept as they are: merge them again by hand, or land the longest stream`, ); } const p = await io.probe(output); if (!p?.audioCodec) return { error: `the merge of its streams (${path.basename(output)}) cannot be read` }; return { file: output, seconds: p.seconds, merged: true }; } if (audio) { io.say(`${g.stem}: only its audio stream holds anything (${path.basename(audio.file)}); landed as it is.`); return { file: audio.file, seconds: audio.probe.seconds }; } return { error: `video with no audio (${streams.map((s) => path.basename(s.file)).join(", ")}): nothing to transcribe` }; } // What the run tells its wrapper (recordLiveRun) as it goes, so a failure the // run did not record itself — a refusal before the recording, a throw in the // middle of it — still ends in the record and the channel's row. type RunHooks = { startedAt: string; id?: string; url?: string; platform?: string; record?: LiveRecordingRecord; save?: () => Promise; // The failure is said on the interrupted run's row (a restart that found // the stream's state unreadable): no row of its own. quiet?: boolean; }; const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note); // A stopped run: by the editor shutting down (`interrupted`, which needs a // person: the stream may still be live and nobody chose to stop it), else by a // person's Cancel (`cancelled`). function stopOf(deps: RecordLiveDeps | undefined): { status: "interrupted" | "cancelled"; by: "shutdown" | "operator" } { let down = false; try { down = deps?.shuttingDown ? deps.shuttingDown() : getRegistry().isShuttingDown?.() === true; } catch { down = false; } return down ? { status: "interrupted", by: "shutdown" } : { status: "cancelled", by: "operator" }; } // The request's recording keys, as the channel's row keeps them (what "Record // again" asks again): from the start or not, the quality, separate streams, // transcribe, keep (doNotClean) and its note, and the live pre-clip. export function recordAgainRequest(req: RecordLiveRequest): Record { const out: Record = {}; for (const k of ["fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note", "preclip", "insurance"] as const) { if (req[k] !== undefined) out[k] = req[k]; } return out; } const rowExtra = (req: RecordLiveRequest) => ({ ...(req.note ? { note: req.note } : {}), request: recordAgainRequest(req) }); // DOES THE LANDED RECORDING HOLD THE WHOLE STREAM — what supersedes an // earlier failure of the same id (lib/liveRecordings-server.ts). The stream's // length is the ended stream's own `duration` when its record has one, else // the clock: the last part's end minus the stream's start. The clock can only // OVERSTATE it (a recorder exits after the stream's last segment, and a // scheduled start may precede the real one), so a whole recording may read // "does not cover" by the clock — the safe direction: the earlier failure // then stays until a person acknowledges it. // The tolerance, max(60 s, 1 %): a recording from the start misses only // seconds at its two ends (the first fragment, the live edge's last few // segments of 2-6 s each, the container's rounding); 1 % absorbs probe and // rounding drift on a stream of many hours. A recording short by more than // that is missing content a person should hear about. export const COVERAGE_MIN_TOLERANCE_SECONDS = 60; export const COVERAGE_TOLERANCE_FRACTION = 0.01; export function streamCoverage(o: { capturedSeconds: number | null; endMeta: Record | null; streamStartedAt: string | null; lastEndedAt: string | null; // From its start as asked, with both streams, not a live-edge fallback. wholeFromStart: boolean; }): StreamCoverage { const ls = typeof o.endMeta?.live_status === "string" ? o.endMeta.live_status : null; const duration = typeof o.endMeta?.duration === "number" && o.endMeta.duration > 0 && ls !== "is_live" && ls !== "is_upcoming" ? (o.endMeta.duration as number) : null; const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN; const endMs = o.lastEndedAt ? Date.parse(o.lastEndedAt) : NaN; const clock = Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs ? (endMs - startMs) / 1000 : null; const streamSeconds = duration ?? clock; const basis = duration !== null ? "duration" : clock !== null ? "clock" : null; const toleranceSeconds = Math.round(Math.max(COVERAGE_MIN_TOLERANCE_SECONDS, (streamSeconds ?? 0) * COVERAGE_TOLERANCE_FRACTION)); const covers = o.wholeFromStart && o.capturedSeconds !== null && streamSeconds !== null && o.capturedSeconds + toleranceSeconds >= streamSeconds; return { capturedSeconds: o.capturedSeconds, streamSeconds: streamSeconds !== null ? Math.round(streamSeconds) : null, basis, toleranceSeconds, covers }; } // THE RUN, AND ITS FAILURE RECORDED. Every way a recording can end without a // landing leaves a row in channels//live-recordings.json that says why // (lib/liveRecordings-server.ts): the run's own saves write it; a throw the // run did not record (a refusal before any recorder started, a failure in the // middle) is written here, and the record, when there is one, says `failed`. export async function recordLiveRun( opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal }, ): Promise { const now = opts.deps?.now ?? (() => new Date()); const hooks: RunHooks = { startedAt: now().toISOString() }; try { return await recordLiveRunInner(opts, hooks); } catch (err) { const message = (err as Error).message; const stopped = opts.signal.aborted ? stopOf(opts.deps) : null; try { if (hooks.record && hooks.save) { if (hooks.record.status === "recording") { hooks.record.status = stopped?.status ?? "failed"; if (stopped) hooks.record.stoppedBy = stopped.by; hooks.record.endedAt = now().toISOString(); hooks.record.error = message; await hooks.save(); } } else if (hooks.id && !opts.request.dryRun && !hooks.quiet) { const failureClass = stopped ? undefined : liveFailureClass(message); await upsertLiveRecordingRow(opts.paths, opts.request.slug, { ...rowOfRecord( hooks.id, { status: stopped?.status ?? "failed", ...(stopped ? { stoppedBy: stopped.by } : {}), ...(failureClass && failureClass !== "unknown" ? { failureClass } : {}), url: hooks.url ?? opts.plan.url, platform: hooks.platform ?? opts.plan.platform, fromStart: opts.request.fromStart !== false, startedAt: hooks.startedAt, endedAt: now().toISOString(), parts: [], error: `nothing was recorded: ${message}`, attempts: 0, mustKeep: isMustKeep(opts.request), ...(opts.jobId ? { jobId: opts.jobId } : {}), }, rowExtra(opts.request), ), }); } } catch (e) { opts.onLog(`The failure could not be recorded in the channel's live recordings (${(e as Error).message}).\n`); } throw err; } } async function recordLiveRunInner( opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal }, hooks: RunHooks, ): Promise { const { paths, request: req, onLog, signal } = opts; const say = (s: string) => onLog(s.endsWith("\n") ? s : `${s}\n`); const deps = opts.deps ?? {}; const now = deps.now ?? (() => new Date()); const waitFor = deps.wait ?? sleep; const stretch = deps.jitter ?? ((ms: number) => jitterMs(ms)); const runRecorder = deps.spawn ?? spawnRecorder; const getText = deps.fetchText ?? fetchText; const watchMs = deps.watchMs ?? LIVE_WATCH_MS; // The free-space floor (tests set a small one). const minFree = deps.minFreeBytes ?? RECORD_LIVE_MIN_FREE_BYTES; const stallMs = deps.stallMs ?? liveStallMinutes() * 60_000; const fromStart = req.fromStart !== false; const maxHeight = req.maxHeight === undefined ? LIVE_DEFAULT_MAX_HEIGHT : req.maxHeight; const cookies = alwaysCookies(opts.cookiePolicy); let plan = opts.plan; // A Kick channel: its ongoing VOD is the record. if (plan.platform === "kick" && plan.id === null) { const cfg = configForVideoUrl(opts.channelConfig, plan.url); const vod = await (deps.kickVod ?? ((ch, s) => defaultKickVod(paths, ch, cfg, cookies, s)))(plan.kickChannel!, signal); if (!vod) throw new Error(`kick.com/${plan.kickChannel} has no ongoing VOD to record (is it live?)`); say(`Kick: the ongoing VOD of ${plan.kickChannel} is ${vod.url}`); plan = { ...plan, url: vod.url, id: vod.id }; } const id = plan.id!; hooks.id = id; hooks.url = plan.url; hooks.platform = plan.platform; const separate = req.separate ?? separateStreamsDefault(plan.platform); const cfg = configForVideoUrl(opts.channelConfig, plan.url); const channelDir = path.join(paths.channelsDir, req.slug); const videoDir = path.join(channelDir, "data", id); const summary: RecordLiveSummary = { slug: req.slug, id, dryRun: req.dryRun === true, parts: [], landed: null, status: "recording" }; say( `Record ${plan.url} into ${req.slug}/${id} — ${fromStart ? "from its start" : "from now"}, ` + `${maxHeight === null ? "the tallest" : `≤ ${maxHeight}p`}` + `${separate ? ", separate video + audio streams merged" : ", one muxed stream"}` + `${req.dryRun ? " (dry run: nothing is fetched or written)" : ""}`, ); if (req.dryRun) { say( plan.platform === "kick" ? "Would record the ongoing VOD's playlist from its first segment, and the channel's live stream beside it." : `Would record with yt-dlp ${fromStart ? "--live-from-start" : ""}${BROWSER_FALLBACK_PLATFORMS.has(plan.platform) ? ", the page's own playlist by ffmpeg if yt-dlp is refused" : ""}.`, ); say("Then the longest part is landed as the video's source (the store, audio, the archive line) and handed to the transcription lane."); if (req.preclip) { say( `Live pre-clip: every ${req.preclip.everyMinutes} min the new span is transcribed (at most ${req.preclip.maxChunkMinutes} min a tick)` + `${req.preclip.mine ? " and mined into a umtool project" : ""}, while it records.`, ); } summary.status = "landed"; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); return summary; } // 1. The record. const created = !(await stat(videoDir).then((s) => s.isDirectory(), () => false)); await mkdir(videoDir, { recursive: true }); // A record this run made and recorded nothing into is not left behind: a // data// with metadata is what every enumerator reads as "fetched". const RECORD_ONLY = new Set(["metadata.info.json", "metadata.history.json", "live-recording.json"]); // By name, then an rmdir that fails on anything else: a file another job // (the live chat) writes into the dir meanwhile is never removed with it. const abandon = async () => { if (!created) return; const left = await readdir(videoDir).catch(() => [] as string[]); if (!left.every((n) => RECORD_ONLY.has(n))) return; for (const n of RECORD_ONLY) await rm(path.join(videoDir, n), { force: true }); await rmdir(videoDir).catch(() => {}); }; let extractionError: string | null = null; let extractionErrObj: Error | null = null; const refresh = () => refreshVideoMetadata({ paths, slug: req.slug, videoId: id, videoUrl: plan.url, channelConfig: cfg, cookiePolicy: opts.cookiePolicy, onLog, signal, requestedBy: RECORD_LIVE_JOB_KIND, ...(deps.refresh ? { run: deps.refresh } : {}), }); // Is the stream still live? One metadata read (slice 3's restarts): a // read that says it ended is the end read the landing would make. let endRead = false; let endedByRefusal = false; // REVIEW-7: what the LAST state read said (its live_status), or the class // of its failure — `post_live` and a network failure decide what follows. const lastRead: { status: string | null; failClass: LiveFailureClass | null; goodStatus: string | null } = { status: null, failClass: null, goodStatus: null }; const liveNow = async (confirm = true): Promise<"live" | "ended" | "unknown"> => { try { await refresh(); } catch (err) { const msg = (err as Error).message; // A read refused because the stream is over, private or removed is the // platform's word — once CONFIRMED by a second read a minute later // (REVIEW-4 5.1: "Video unavailable" is also what a geo refusal says). // Confirmed, the row says the stream went private or was removed while // it was recorded, and what is held: never a quiet landing. const c = liveFailureClass(msg); if (c === "ended" || c === "private") { if (confirm) { say(`The stream's metadata was refused (${msg.split("\n")[0]}): read again in ${spanWords(LIVE_RESTART_CONFIRM_MS / 1000)} before the recording ends.`); await waitFor(stretch(LIVE_RESTART_CONFIRM_MS), signal); const again = await liveNow(false); if (again !== "ended" || !endedByRefusal) return again; return "ended"; } endRead = true; endedByRefusal = true; hooks.record!.endedBy = { class: c, message: msg.split("\n")[0]!.slice(0, 300), at: now().toISOString() }; // DESIGN-5 (c): its fragments answered 403 before this read: it went // private while it was recorded. if (c === "private") { for (const p of hooks.record!.parts) { if ((p.fragment403 ?? 0) > 0) { p.failureClass = "went-private"; p.error = `its fragment requests were answered 403 Forbidden, and the stream reads private or removed: it went private while it was recorded`; } } if (hooks.record!.parts.some((p) => p.failureClass === "went-private")) hooks.record!.failureClass = "went-private"; } await hooks.save?.(); say(`The stream ${c === "ended" ? "is over" : "went private or was removed"} while it was recorded (${msg.split("\n")[0]}): what is held lands, and the row needs a person.`); return "ended"; } say(`The stream's metadata could not be read (${msg.split("\n")[0]}).`); lastRead.status = null; lastRead.failClass = c; return "unknown"; } const ls = (await readMeta(videoDir))?.live_status; lastRead.status = typeof ls === "string" ? ls : null; lastRead.failClass = null; if (lastRead.status) lastRead.goodStatus = lastRead.status; if (ls === "is_live") return "live"; if (ls === "was_live" || ls === "post_live" || ls === "not_live") { endRead = true; return "ended"; } return "unknown"; }; // A RESTART BY THE BOOT PASS (req.resumeOf): what it found goes on the // interrupted run's row. // Only a run the boot pass asked for (its row marked starting/asked) is // one: a stray resumeOf is ignored. let resumeOf: string | null = null; if (req.resumeOf) { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const r = rows.find((x) => x.id === id && x.startedAt === req.resumeOf); if (r && (r.restart?.state === "starting" || r.restart?.state === "asked")) resumeOf = req.resumeOf; else say(`"resumeOf" ${req.resumeOf} names no run the boot pass is restarting: recorded as an ordinary run.`); } const markResume = async (state: LiveBootRestartState, extra: { reason?: string } = {}) => { if (!resumeOf) return; await markLiveBootRestart(paths, req.slug, id, resumeOf, { state, ...(opts.jobId ? { jobId: opts.jobId } : {}), ...extra }, now).catch( (e: Error) => say(`The interrupted run's row could not be updated (${e.message}).`), ); }; // The boot's landing of what was left: the old row says what it did. const bootLandingDone = async (landedIt: boolean, why = "") => { if (!resumeOf || !bootLanding) return; await markResume(landedIt ? "landed" : "failed", { reason: landedIt ? bootLanding : `${bootLanding}: what was left was NOT landed — ${why}` }); }; // REVIEW-5 B3: what the interrupted run left in staging has a way into the // store whatever the boot's run finds — the stream ended, removed, or its // state not readable: the landing takes it (the only copy) by its rules. const leftInStaging = async () => livePartFiles(id, await readdir(path.dirname(savedVideoDir(paths, opts.channelConfig, req.slug, id))).catch(() => [] as string[])).length; let bootUnread: string | null = null; // REVIEW-6 12: private or removed while the editor was down — said on the // new record as when it happens while recording (endedBy). let bootGone: { class: LiveFailureClass; message: string; at: string } | null = null; try { await refresh(); } catch (err) { extractionError = (err as Error).message; extractionErrObj = err as Error; if (resumeOf) { // Never a recording on a guess: the stream's state is not known. A // reboot or a network drop is the commonest boot, so the read is made // three times over about ten minutes (REVIEW-1 3.3 of live-guard-2) — // not after a rate limit, members-only or the disk, which another read // does not change. let lastErr = err as Error; let read = false; const cls0 = liveFailureClass(lastErr.message); if (cls0 !== "rate-limited" && cls0 !== "members" && cls0 !== "disk") { for (const w of LIVE_BOOT_STATE_READ_WAITS_MS) { say(`Restart after the editor restart: the stream's state could not be read (${lastErr.message.split("\n")[0]!.slice(0, 200)}); read again in ${spanWords(w / 1000)}.`); await waitFor(stretch(w), signal); if (signal.aborted) break; try { await refresh(); read = true; break; } catch (e) { lastErr = e as Error; const c = liveFailureClass(lastErr.message); if (c === "rate-limited" || c === "members" || c === "disk") break; } } } if (read) extractionError = null; else { const reads = 1 + LIVE_BOOT_STATE_READ_WAITS_MS.length; const gone = liveFailureClass(lastErr.message) === "private"; const first = lastErr.message.split("\n")[0]!.slice(0, 240); if (await leftInStaging()) { // Never a recording on a guess — but what is left lands. // (Gone is the platform's word: the stream is confirmed done.) if (gone) { endedByRefusal = true; bootGone = { class: "private", message: first, at: now().toISOString() }; } bootUnread = gone ? `the stream was made private or removed while the editor was down (${first})` : `the stream's state could not be read (${reads} reads: ${first}) — it may still be live and is NOT being recorded: Record again if it is`; say(`Restart after the editor restart: ${bootUnread}; what the interrupted run left in staging is landed.`); extractionError = null; } else { const reason = `${first} — the stream may still be live and is NOT being recorded`; say(`Restart after the editor restart: the stream's state could not be read (${reason}); nothing is recorded or landed — Record again if it is still live.`); await markResume("unknown", { reason: `${reads} reads failed: ${reason}` }); hooks.quiet = true; await abandon(); throw lastErr; } } } } if (extractionError !== null) { const canFallBack = BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(extractionError); if (!canFallBack) { await abandon(); throw extractionErrObj ?? new Error(extractionError); } say(`yt-dlp could not read the stream (${extractionError.split("\n")[0]}); recording from the page's own playlist.`); } const meta = await readMeta(videoDir); const liveStatus = typeof meta?.live_status === "string" ? meta.live_status : null; // (The run's first read is the first "last read".) lastRead.status = liveStatus; lastRead.goodStatus = liveStatus; // A restart of a stream that has ended records nothing: what the // interrupted run left in staging lands (the slice-1 landing), or, with // nothing there, the row says so. let resumeEnded = false; // The words the interrupted run's row gets once the landing is done. let bootLanding: string | null = null; if (resumeOf && bootUnread) { resumeEnded = true; endRead = true; bootLanding = bootUnread; await markResume("landing", { reason: bootUnread }); } else if (resumeOf) { if (!meta || !liveStatus) { say("Restart after the editor restart: the stream's record says nothing of its state — nothing is recorded or landed."); await markResume("unknown", { reason: "the metadata names no live_status" }); hooks.quiet = true; await abandon(); throw new Error(`${plan.url}: its live state is not known; not restarted`); } if (!LIVE_STATES.has(liveStatus)) { const stage = path.dirname(savedVideoDir(paths, opts.channelConfig, req.slug, id)); const left = livePartFiles(id, await readdir(stage).catch(() => [] as string[])); if (!left.length) { say(`Restart after the editor restart: the stream has ended (${liveStatus}) and nothing is left in staging — nothing more to record or land.`); await markResume("ended"); summary.status = "interrupted"; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); return summary; } say(`Restart after the editor restart: the stream has ended (${liveStatus}); the ${left.length} part(s) left in staging are landed.`); bootLanding = `the stream had ended by the restart (${liveStatus})`; await markResume("landing", { reason: bootLanding }); resumeEnded = true; endRead = true; } else { say(`Restart after the editor restart: the stream is ${liveStatus}; recording again.`); await markResume("restarted"); } } if (!resumeEnded && meta && liveStatus && !LIVE_STATES.has(liveStatus)) { await abandon(); throw new Error( `${plan.url} is not live (live_status ${liveStatus}): download it as a video, or import a recording of it`, ); } // The recording is written on the store's disk. Its root must be there (an // unmounted drive is never materialised by a mkdir), not mid-move, and have // room for hours of video. const storeDir = savedVideoDir(paths, opts.channelConfig, req.slug, id); const slugStore = path.dirname(storeDir); const storeRoot = savedVideoRoot(paths, opts.channelConfig); try { await ensureStoreRoot(paths, storeRoot, "nothing recorded"); await assertSavedVideosStoreWritable(paths, storeDir); const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot); if (free < minFree) { throw new Error( `the store's disk has ${formatBytes(free)} free; a live recording needs ${formatBytes(minFree)} — nothing recorded`, ); } } catch (err) { await abandon(); throw err; } await mkdir(slugStore, { recursive: true }); const stamp = now().toISOString().replace(/[:.]/g, "-"); // A part's stem (lib/liveCapture.ts livePartFiles); a muxed part is // `.ts`, a separate-streams one the files yt-dlp names for it. const stemPath = (tag: string) => path.join(slugStore, `.${id}.live-${stamp}.${tag}`); const partPath = (tag: string) => `${stemPath(tag)}.ts`; const leftovers = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed, and the others are kept.`); // When the stream started, as its record says (what a live-edge fallback // has lost is measured from it). const streamStartSec = typeof meta?.release_timestamp === "number" ? (meta.release_timestamp as number) : typeof meta?.timestamp === "number" ? (meta.timestamp as number) : null; const record: LiveRecordingRecord = { ...(bootGone ? { endedBy: bootGone } : {}), status: "recording", url: plan.url, platform: plan.platform, fromStart, separate, startedAt: hooks.startedAt, parts: [], attempts: 0, mustKeep: isMustKeep(req), ...(opts.jobId ? { jobId: opts.jobId } : {}), ...(streamStartSec !== null ? { streamStartedAt: new Date(streamStartSec * 1000).toISOString() } : {}), ...(resumeOf ? { resumeOf } : {}), }; // The record beside the video, and the channel's row (which outlives it). let rowWarned = false; const save = async () => { await liveRecordingSidecar.write(videoDir, record); try { await upsertLiveRecordingRow(paths, req.slug, rowOfRecord(id, record, rowExtra(req))); } catch (err) { if (!rowWarned) say(`The channel's live recordings could not be written (${(err as Error).message}).`); rowWarned = true; } }; hooks.record = record; hooks.save = save; // How far back the playlist reaches (best effort, one read). // (Not for separate streams from the start: YouTube's DASH from the start is // not the HLS playlist the record lists, which holds only the live edge.) const fmt = meta ? hlsFormatOf(meta, maxHeight) : null; if (fmt && !resumeEnded && plan.platform !== "kick" && !(separate && fromStart)) { try { const pl = parsePlaylist(await getText(fmt.url, signal), fmt.url); if (pl?.kind === "media") { const startedMs = typeof meta?.timestamp === "number" ? (meta.timestamp as number) * 1000 : null; const reach = playlistReach(pl, plan.platform, startedMs); record.reach = reach; summary.reach = reach; say( `The live playlist lists ${Math.round(reach.heldSeconds)} s from segment ${reach.firstSeq}: ` + (reach.fromStart ? "the broadcast from its start." : `NOT the start${reach.missingSeconds !== null ? ` (about ${Math.round(reach.missingSeconds / 60)} min before it is gone)` : ""}.`), ); } } catch (err) { say(`The live playlist could not be read ahead (${(err as Error).message}); recording anyway.`); } } await save(); // Each part by its stem's name (the files on disk are read back by it). const parts: { part: LivePart; stem: string }[] = []; let preclipAsked = false; const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => { const stem = path.basename(file).replace(/\.ts$/, ""); record.attempts = (record.attempts ?? 0) + 1; const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem, attempt: record.attempts }; record.parts.push(part); parts.push({ part, stem }); if (req.preclip && !preclipAsked && opts.startPreclip) { preclipAsked = true; // After the save that lists this part (the pre-clip reads the record). setImmediate(() => { void opts.startPreclip!(req.slug, id, req.preclip!).then( (r) => say(r.ok ? `Live pre-clip: job ${r.jobId} (every ${req.preclip!.everyMinutes} min)` : `Live pre-clip was not started: ${r.error ?? "no job"}`), (e: Error) => say(`Live pre-clip was not started: ${e.message}`), ); }); } return part; }; const finish = (part: LivePart, note: string) => { part.endedAt = now().toISOString(); part.note = note; }; // 2. The recording. // What the attempts came to when none recorded anything (the failure's words). let attemptsSummary: string | null = null; // "from-start": yt-dlp `--live-from-start` (and ffmpeg told index 0 too, // the same thing for a DVR playlist); "index0": `--no-live-from-start` with // ffmpeg told index 0 — for an extractor that does not mark a format from // the start; "now": the live edge. // YouTube (REVIEW-LF-3 1): a `--live-from-start` run there either fails // "no formats that can be downloaded from the start" (→ index 0, never // marked) or downloads only the extractor's own fragment generator, which // begins at fragment 0 for a stream under 120 h old (YoutubeDL.py's // is_from_start format filter; extractor/youtube/_video.py MAX_DURATION). // So the proof is the platform plus the age — not the metadata read's // formats, which never carry the generator protocol (that read passes no // --live-from-start: a real live record lists HLS formats only). const youtube = plan.platform === "youtube" || /^youtube/i.test(String(meta?.extractor ?? "")); const startProvable = (first: boolean): boolean => { if (youtube) { // Its age: from its start time, else (an ended stream) its duration. const age = streamStartSec !== null ? now().getTime() / 1000 - streamStartSec : typeof meta?.duration === "number" ? (meta.duration as number) : null; // (119 h: an hour's margin, REVIEW-5 note 8.) return age !== null && age * 1000 < LIVE_RESUME_MAX_AGE_MS; } return first && record.reach?.fromStart === true; }; const ytdlpPart = async ( url: string, tag: string, mode: "from-start" | "index0" | "now", extraNote = "", // recovery: a slice-2 try. noWait: never `--wait-for-video` (a restart or // a try is of a stream already live). watch: the stall watchdog (off for // Kick's channel recorder, which its VOD poll ends). // insurance: slice 4's part. stop: a stop of this recorder alone (the // insurance's, once caught up). onStart: its stem, once begun. onLine: // every line it prints. opts: { recovery?: boolean; restart?: number; noWait?: boolean; watch?: boolean; insurance?: boolean; stop?: AbortSignal; onStart?: (stem: string) => void; onLine?: (line: string) => void; // DESIGN-3: RESUME IN PLACE — this stem's files and state again (same // `-o`), the format pinned to the ids on disk; this run's part of that // stem, or a new entry for it (a boot restart of an earlier run's part). resume?: { stem: string; formats: string; provenStart?: boolean; lock?: StemLock }; // The run's first attempt, made with no wait before it (main's proof). firstAttempt?: boolean; // DESIGN-4 3: the last resort — this run of the part may skip a // fragment that cannot be fetched (the part is marked, never proven). allowSkip?: boolean; } = {}, ): Promise => { const file = opts.resume ? path.join(slugStore, separate ? opts.resume.stem : `${opts.resume.stem}.ts`) : separate ? stemPath(tag) : partPath(tag); const known = opts.resume ? parts.find((p) => p.stem === opts.resume!.stem)?.part : undefined; const part = known ?? begin("ytdlp", url, file, mode !== "now"); if (opts.resume) { part.resumes = (part.resumes ?? 0) + 1; delete part.endedAt; delete part.stalled; if (known) record.attempts = (record.attempts ?? 0) + 1; } if (opts.recovery) part.recovery = true; if (opts.restart) part.restart = opts.restart; if (opts.insurance) part.insurance = true; if (mode === "index0") part.index0 = true; // PROVEN from the stream's start (main's rule, REVIEW-LF-2/3): by what is // recorded — a YouTube `--live-from-start` part on a stream under 120 h // old; another platform's only on the first attempt whose playlist read // listed the start. A RESUME continues the same file from its saved // fragment, so it keeps the mark the ORIGINAL run earned (this run's part, // or the earlier run's by its row) and never earns one itself; a // recovery try or a live-edge part never gets one. if (opts.resume) { if (!known && opts.resume.provenStart) part.provenStart = true; } else if (mode === "from-start" && !opts.recovery && startProvable(opts.firstAttempt === true)) part.provenStart = true; const stem = part.stem!; opts.onStart?.(stem); await save(); const waitForVideo = !opts.noWait && liveStatus === "is_upcoming" && tag !== "channel"; const args = ytdlpLiveArgs({ url, output: file, fromStart: mode === "from-start", maxHeight, separate, waitForVideo, ...(opts.resume ? { format: opts.resume.formats } : {}), ...(opts.allowSkip ? { allowSkip: true } : {}), channelArgs: [ ...channelExtraArgs(cfg, cookies), "--downloader-args", `ffmpeg_i:${mode !== "now" ? "-live_start_index 0 " : ""}-m3u8_hold_counters 180 -seg_max_retry 10`, ], }); // The recorder's argv does not pass jitterYtdlpSleeps: asked here. refuseInstagramYtdlp(args); // SLICE 3 — THE STALL WATCHDOG: this recorder's own stop, besides the // job's. Every watchMs the part's files (all of them) are summed; no // change for stallMs stops this recorder only. An upcoming stream's // recorder waiting for it with nothing written is not stalled. // HOW IT IS STOPPED (DESIGN-3): a from-start recorder stopped by the // watchdog or an editor shutdown gets SIGTERM — yt-dlp then does not // finish, and its `.ytdl` state stays for the resume; a person's Cancel // (and every other recorder) SIGINT, which finishes the file. // REVIEW-5 B4: SIGTERM only for a part that CAN be resumed at the moment // of the stop (separate streams, each with its state); every other // recorder — a muxed ffmpeg download keeps no state — gets SIGINT, which // finishes its file. const resumable = mode === "from-start"; const stopHow = async (): Promise<"SIGTERM" | "SIGINT"> => resumable && separate && (await resumeStateOf(stem, { accounting: false }).catch(() => ({ ok: false }))).ok ? "SIGTERM" : "SIGINT"; const own = new AbortController(); const onJobAbort = () => { if (!(resumable && stopOf(deps).by === "shutdown")) return own.abort("SIGINT"); void stopHow().then((how) => own.abort(how)); }; const onOwnStop = () => own.abort("SIGINT"); if (signal.aborted) onJobAbort(); else if (opts.stop?.aborted) onOwnStop(); else { signal.addEventListener("abort", onJobAbort, { once: true }); opts.stop?.addEventListener("abort", onOwnStop, { once: true }); } // DESIGN-4 1 / DESIGN-5 7 — THE KEPT FRAGMENTS, once a watch tick: every // fragment stays until the stream is confirmed done (the platform says it // is over AND the landed file is verified) — the bytes a restart reuses. // The stream files plus their fragments are twice the stream on disk. // Short of disk (under the floor) the recorder goes on and the fragments // go — resumability lost, said, the row loud — never the reverse, never // silently. A fragment number missing among the kept ones is a skip. const keptFragmentsTick = async () => { const g = await filesOf(stem); if (!g) return; const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => Infinity); for (const f of g.streams) { if (part.fragmentsDropped) { await dropFragments(slugStore, f).catch(() => 0); continue; } if (free < minFree) { part.fragmentsDropped = `the store's disk had ${formatBytes(free)} free (under ${formatBytes(minFree)})`; await writeStemMarks(slugStore, stem, { dropped: part.fragmentsDropped }); say(`[${tag}] the store's disk is short (${formatBytes(free)} free): the recording goes on, but its kept fragments are dropped — this part can no longer be resumed in place.`); await save(); await dropFragments(slugStore, f).catch(() => 0); continue; } // DESIGN-5 7: NO prune while recording — every fragment stays until // the stream is confirmed done; a number missing among them is a skip. const names = await readdir(slugStore).catch(() => [] as string[]); const idx = await readYtdlIndex(path.join(slugStore, f)); const kept = fragNumbers(f, names).filter((n) => typeof idx !== "number" || n <= idx); const gaps = kept.length ? fragmentGaps(kept, 1) : []; if (gaps.length) { const sf = (part.skippedFragments ??= { count: 0, positions: [] }); for (const n of gaps) { if (sf.positions.includes(n)) continue; sf.positions.push(n); sf.count += 1; } await writeStemMarks(slugStore, stem, { skipped: sf }); } } }; let stalled = false; let timer: NodeJS.Timeout | null = null; // The watch tick in flight: awaited before the recorder's part is handed // back, so no prune or checkpoint write races the landing. let inFlight: Promise = Promise.resolve(); if (opts.watch !== false) { let last = -1; let lastGrowth = now().getTime(); let busy = false; // REVIEW-5 note 1: EACH stream file of a separate from-start part must // grow, not their sum — one format's thread may end alone (yt-dlp) while // the other goes on for hours. const perStream = new Map(); timer = setInterval(() => { if (busy || own.signal.aborted) return; busy = true; inFlight = (async () => { if (separate && mode === "from-start") await keptFragmentsTick(); const b = await allBytesOf(stem); const t = now().getTime(); let still: string | null = null; if (separate && mode !== "now") { const g = await filesOf(stem); for (const f of g?.streams ?? []) { const size = await sizeOf(path.join(slugStore, f)); const was = perStream.get(f); if (!was || size !== was.size) perStream.set(f, { size, at: t }); else if (t - was.at >= stallMs && b > 0 && !(waitForVideo && b === 0)) still = f; } } if (still === null && (b !== last || (waitForVideo && b === 0))) { last = b; lastGrowth = t; return; } if (b !== last) { last = b; lastGrowth = t; } const since = still !== null ? t - perStream.get(still)!.at : t - lastGrowth; if (since >= stallMs && !own.signal.aborted) { stalled = true; const how = await stopHow(); say( (still !== null ? `[${tag}] stalled: its stream ${still} has not grown for ${spanWords(since / 1000)} while the part's files did` : `[${tag}] stalled: its files have not grown for ${spanWords(since / 1000)} (${formatBytes(b)})`) + `; stopping this recorder (${how === "SIGTERM" ? "SIGTERM: its state is kept for the resume" : "SIGINT"}); its part is kept.`, ); own.abort(how); } })() .catch(() => {}) .finally(() => { busy = false; }); }, watchMs); } const streamBefore = opts.resume ? await streamBytesOf(stem) : 0; // NOTE 5 (REVIEW-5) — ONE RECORDER PER STEM: a lock file held while the // recorder runs. yt-dlp would let a second writer append to the same file. const lock = opts.resume?.lock ?? (await takeStemLock(slugStore, stem)); if (!lock.ok) { if (timer) clearInterval(timer); signal.removeEventListener("abort", onJobAbort); opts.stop?.removeEventListener("abort", onOwnStop); part.error = `not started: ${lock.why}`; finish(part, `${extraNote}not started (${lock.why})`); say(`[${tag}] NOT started: ${lock.why}.`); await save(); return { exitCode: null, stderrTail: lock.why, signalled: false, part, stem, stalled: false, locked: lock.why }; } // DESIGN-4 3: a fragment that cannot be fetched ends that stream's thread // (--abort-on-unavailable-fragments) while yt-dlp records the other on: // the error line stops the whole recorder, for a resume from the saved // fragment. Every skipped fragment (the last resort) is counted. let fragAbort: { index: number | null } | undefined; // This run's own failed URL refresh (the part's class may be an earlier run's). let urlRefreshHere = false; const lineHook = (l: string) => { opts.onLine?.(l); if (mode === "now") return; const skip = /Skipping fragment (\d+)/i.exec(l); if (skip) { const sf = (part.skippedFragments ??= { count: 0, positions: [] }); sf.count += 1; if (sf.positions.length < 200) sf.positions.push(Number(skip[1])); void writeStemMarks(slugStore, stem, { skipped: sf }); } // DESIGN-5 2: the URL could not be refreshed — said in plain words, on // the part, as it is printed (the last lines before the exit are the // merge's, not this). const refresh = /Cannot find refreshed url for format (\S+?)[;,]/i.exec(l); if (refresh) urlRefreshHere = true; if (refresh || (/Giving up after \d+ retries/i.test(l) && part.failureClass === "url-refresh")) { if (part.failureClass !== "url-refresh") { part.failureClass = "url-refresh"; part.error = `yt-dlp could not refresh the stream's URL for format ${refresh?.[1] ?? "?"}: the platform stopped serving it (its DVR switched off?); yt-dlp then ends by itself`; say(`[${tag}] ${part.error}.`); } } if (/HTTP Error 403: Forbidden/i.test(l) && /fragment/i.test(l)) part.fragment403 = (part.fragment403 ?? 0) + 1; if (isFragmentFatalLine(l)) { part.fragmentErrors = (part.fragmentErrors ?? 0) + 1; if (!fragAbort && !own.signal.aborted) { const m = /fragment (\d+)/i.exec(l); fragAbort = { index: m ? Number(m[1]) : null }; say(`[${tag}] a fragment could not be fetched (${l.slice(0, 200)}): its stream stopped; the recorder is stopped for a resume from the saved fragment.`); void stopHow().then((how) => own.abort(how)); } } }; let o: RecorderOutcome; try { o = await runRecorder({ bin: paths.ytdlpBin, args, cwd: channelDir, onLog, signal: own.signal, label: tag, onLine: lineHook, onSpawn: (pid) => void lock.setRecorder(pid), }); } finally { if (timer) clearInterval(timer); await inFlight; signal.removeEventListener("abort", onJobAbort); opts.stop?.removeEventListener("abort", onOwnStop); await lock.release(); } if (stalled) part.stalled = true; finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? (stalled ? " (stopped: stalled)" : " (stopped)") : ""}`); // REVIEW-5 B5: a stream that recorded nothing is said at once, when its // recorder stops, not at the landing. if (separate && mode !== "now") { const miss = await missingStreamOf(stem).catch(() => null); if (miss) { part.missingStream = miss; record.missingStream = miss; say(`[${tag}] its ${miss === "unknown" ? "video or audio" : miss} stream has recorded nothing so far: it needs a person if no resume fills it.`); } else if (part.missingStream && (await bytesOf(stem)) > 0) { // A resume filled it. delete part.missingStream; } } if (fragAbort && part.fragmentErrors) await save(); // REVIEW-7 2 / REVIEW-8 2: after a resume that wrote, each stream file // must still be what its fragments prove — with its state, the equation // (fragments 1..index, a torn tail the repair allows, sizes and the last // fragment's bytes: cheap); finished (no state), byte for byte. Said, and // the part loud, when it is not; the mark clears when a later check holds. if (opts.resume && separate && !part.fragmentsDropped && (await streamBytesOf(stem)) > streamBefore) { let damaged: string | null = null; const g = await filesOf(stem); for (const f of g?.streams ?? []) { const idx = await readYtdlIndex(path.join(slugStore, f)); if (typeof idx === "number") { const r = await reconcileStream(slugStore, f, false).catch((e: Error) => ({ ok: false as const, why: e.message })); if (!r.ok) damaged = r.why; } else if (idx === "absent") { const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message })); if (eq && !eq.ok) damaged = eq.why; } if (damaged) break; } if (damaged) { part.resumeDamaged = damaged; say(`[${tag}] after the resume, ${damaged}: the file is kept as it is and never removed; the row needs a person.`); } else delete part.resumeDamaged; } await save(); return { ...o, part, stem, stalled, ...(fragAbort ? { fragAbort } : {}), ...(urlRefreshHere ? { urlRefresh: true } : {}) }; }; const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0); const filesOf = async (stem: string): Promise => livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).find((g) => g.stem === stem) ?? null; const streamBytesOf = async (stem: string) => { const g = await filesOf(stem); let n = 0; for (const f of g?.streams ?? []) n += await sizeOf(path.join(slugStore, f)); return n; }; const bytesOf = async (stem: string) => { const g = await filesOf(stem); let n = 0; for (const f of g ? [...g.finished, ...g.streams] : []) n += await sizeOf(path.join(slugStore, f)); return n; }; // THE FLOOR BEFORE EVERY SPAWN (REVIEW-1 2.3 of live-guard-2): a recorder, // a try, a restart or the insurance starts only with // RECORD_LIVE_MIN_FREE_BYTES free on the store's disk; one that would breach // it does not start, and the row says so (spaceHeld, needing a person). // The floor scales with the stream (REVIEW-2 3.4): max(the floor, twice the // largest part of this run so far) — a new part may grow as large, and a // landing's merge needs as much again. // REVIEW-6 7: before a resume in place, the floor plus the stream files' // size (the files continue; the kept fragments and merges are not new). const roomFor = async (what: string, o: { resumeStem?: string } = {}): Promise => { let largest = 0; for (const p of parts) largest = Math.max(largest, await allBytesOf(p.stem)); const need = o.resumeStem ? minFree + (await streamBytesOf(o.resumeStem)) : Math.max(minFree, 2 * largest); const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0); if (free >= need) return true; (record.spaceHeld ??= []).push({ what, at: now().toISOString(), freeBytes: free }); say(`${what}: NOT started — the store's disk has ${formatBytes(free)} free, at least ${formatBytes(need)} are needed.`); await save(); return false; }; // DESIGN-3: can this stem be resumed in place? Every stream file with bytes // has yt-dlp's `.ytdl` beside it with a readable fragment index // (downloader/fragment.py), the stream is under 120 h old (past that the // from-start generator starts later and the saved index would misalign, // extractor/youtube/_video.py), and the ids on disk pin the format. // `accounting` false: the structure only (the stop signal's choice, made // while the recorder still writes — the byte equation is for a stopped file). const resumeStateOf = async (stem: string, o: { accounting?: boolean } = {}): Promise<{ ok: true; formats: string; fragment: number } | { ok: false; why: string }> => { const g = await filesOf(stem); if (!g) return { ok: false, why: "its files are gone" }; // EVERY stream file of the stem, an empty one included (REVIEW-5 B5): // yt-dlp opens both and writes their state before any fragment, and // resumes an empty one from 0 — pinning only the ones with bytes would // record the rest of the stream without that stream. const streams = [...g.streams]; if (!streams.length) return { ok: false, why: g.finished.length ? "it was finished (merged)" : "nothing to resume" }; if (!(await bytesOf(stem))) return { ok: false, why: "nothing to resume" }; let fragment = Infinity; for (const f of streams) { let raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null); // REVIEW-6 11: a state caught mid-rewrite is read again once. if (raw !== null && readYtdlRaw(raw) === null) { await new Promise((r) => setTimeout(r, 50)); raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null); } if (raw === null) { // An empty stream file with no state yet is resumed from 0. if ((await sizeOf(path.join(slugStore, f))) === 0) { fragment = Math.min(fragment, 0); continue; } return { ok: false, why: `${f} has no .ytdl state (finished, or never kept)` }; } let idx: unknown; try { idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index; } catch { idx = null; } if (typeof idx !== "number" || idx < 0) return { ok: false, why: `${f}.ytdl does not read` }; fragment = Math.min(fragment, idx); } const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; // An unknown start is not provable (REVIEW-5 note 8): no resume. if (!Number.isFinite(startMs)) return { ok: false, why: "the stream's start time is not known" }; if (now().getTime() - startMs > LIVE_RESUME_MAX_AGE_MS) return { ok: false, why: "the stream is over 119 h old" }; const ids = streams.map((f) => /\.f([^.]+)\.[a-z0-9]+$/i.exec(f)?.[1]).filter((x): x is string => !!x); if (ids.length !== streams.length) return { ok: false, why: "its format ids cannot be read from its files" }; if (separate) { // A separate recording is a picture and a sound: fewer than two, or two // of one kind, is not that recording. if (new Set(ids).size < 2) return { ok: false, why: `only one stream (${ids.join(", ")}) of a separate recording` }; const kinds: string[] = []; for (const [k, f] of streams.entries()) { const fm = Array.isArray(meta?.formats) ? (meta!.formats as Array>).find((x) => String(x.format_id) === ids[k]) : undefined; let kind: string | null = fm ? (fm.vcodec === "none" ? "audio" : fm.acodec === "none" ? "video" : "both") : null; if (!kind && (await sizeOf(path.join(slugStore, f))) > 0) { const pv = await probe(path.join(slugStore, f)).catch(() => null); kind = pv ? (pv.videoCodec && pv.audioCodec ? "both" : pv.videoCodec ? "video" : pv.audioCodec ? "audio" : null) : null; } if (kind) kinds.push(kind); } if (kinds.filter((x) => x === "video").length > 1 || kinds.filter((x) => x === "audio").length > 1) { return { ok: false, why: `two streams of one kind (${ids.join(", ")})` }; } } // DESIGN-4 1: only a file the byte accounting proves (read only here; the // one repair is made just before the resume, reconcileForResume). const marks = await readStemMarks(slugStore, stem); const mine = parts.find((p) => p.stem === stem)?.part; const dropped = marks.dropped ?? mine?.fragmentsDropped; if (dropped) return { ok: false, why: `its kept fragments were dropped (${dropped})` }; const skipped = marks.skipped?.count ?? mine?.skippedFragments?.count ?? 0; if (skipped > 0) return { ok: false, why: `it skipped ${skipped} fragment(s)` }; if (o.accounting !== false) { for (const f of streams) { const r = await reconcileStream(slugStore, f, false); if (!r.ok) return { ok: false, why: r.why }; } } return { ok: true, formats: ids.join("+"), fragment: Number.isFinite(fragment) ? fragment : 0 }; }; // DESIGN-5 7 — REUSE AFTER A SELF-EXIT: yt-dlp finished the part (merged, // its `.ytdl` removed) while the stream went on. Measured (LOG, point 7): // the same -o reuses what is on disk only with a state whose index is right // and the merged copy NOT at its final name (else "already downloaded" and // nothing is recorded). So each kept stream file must equal its kept // fragments 1..N exactly (contiguous); then its state is written at N and // the merged copies are moved aside (scratch, until confirmed done). // `apply` false: whether it can be. const restoreForReuse = async (stem: string, apply: boolean): Promise<{ ok: true; fragments: number } | { ok: false; why: string }> => { const g = await filesOf(stem); if (!g || g.streams.length < (separate ? 2 : 1)) return { ok: false, why: "its stream files were not kept" }; const names = await readdir(slugStore).catch(() => [] as string[]); const counts: number[] = []; for (const f of g.streams) { const file = path.join(slugStore, f); const idx = await readYtdlIndex(file); // REVIEW-6 13: per stream — one that still has its state is resumed as // it is (its accounting is checked before the resume); one without is // rebuilt from its kept fragments. if (typeof idx === "number") { counts.push(-1); continue; } if (idx === null) return { ok: false, why: `${f}.ytdl does not read` }; const kept = fragNumbers(f, names); const k = kept.length && kept[kept.length - 1] === kept.length ? kept.length : 0; if (!k) return { ok: false, why: `${f}: its kept fragments are not 1..N without a gap` }; let sum = 0; for (let n = 1; n <= k; n++) sum += await sizeOf(path.join(slugStore, `${f}-Frag${n}`)); const size = await sizeOf(file); if (sum !== size) return { ok: false, why: `${f} is ${size} bytes, its ${k} kept fragments ${sum}` }; counts.push(k); } if (!counts.some((c) => c >= 0)) return { ok: false, why: "every stream still has its state (a resume, not a reuse)" }; if (apply) { for (const [i, f] of g.streams.entries()) { if (counts[i]! < 0) continue; await writeFile(path.join(slugStore, `${f}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: counts[i] } } })); } const stamp = Date.now(); // REVIEW-6 8: one moved-aside merge at a time (each self-exit would // leave another full copy of the stream so far). for (const f of g.scratch) if (/\.premerge-\d+\.[a-z0-9]+$/i.test(f)) await rm(path.join(slugStore, f), { force: true }); for (const f of g.finished) { const m = /^(.*)\.([a-z0-9]+)$/i.exec(f); if (m) await rename(path.join(slugStore, f), path.join(slugStore, `${m[1]}.premerge-${stamp}.${m[2]}`)).catch(() => {}); } say(`${stem}: yt-dlp had finished it while the stream went on; its state is rebuilt at the ${Math.min(...counts.filter((c) => c >= 0))} fragments its kept files prove, the merged copy moved aside — resumed, reusing what is on disk.`); } return { ok: true, fragments: Math.min(...counts.filter((c) => c >= 0)) }; }; // The one repair (DESIGN-4 1), made just before a resume: a torn last // append truncated back, logged with both lengths. Anything it cannot // prove: no resume in place. // REVIEW-7 6: the stem's lock is taken FIRST — never a repair under a // recorder that still writes those files — and handed to the resume. const reconcileForResume = async (stem: string): Promise<{ ok: true; lock: StemLock } | { ok: false; why: string }> => { const lock = await takeStemLock(slugStore, stem); if (!lock.ok) return { ok: false, why: lock.why }; const fail = async (why: string) => { await lock.release(); return { ok: false as const, why }; }; const g = await filesOf(stem); for (const f of g?.streams ?? []) { const r = await reconcileStream(slugStore, f, true, say); if (!r.ok) return fail(r.why); // REVIEW-6 2: no kept fragment past the index may meet the resume. const idx = await readYtdlIndex(path.join(slugStore, f)); if (typeof idx !== "number") return fail(`${f}.ytdl does not read`); const gone = await dropFragmentsAbove(slugStore, f, idx); if (gone.length) say(`${f}: fragment(s) ${gone.join(", ")} past its state (${idx}) removed before the resume (a complete one would be refused, 416, and the resume would record nothing).`); } return { ok: true, lock }; }; // The longest a part's files play (its streams' probes), 0 when unread. // The stream-level length a part holds: a finished file's, else the // SHORTEST of its separate streams (REVIEW-4 2.1(a): the picture may lag // the sound) — 0 when unread. const secondsOf = async (stem: string): Promise => { const g = await filesOf(stem); if (!g) return 0; let fin = 0; for (const f of g.finished) fin = Math.max(fin, (await probe(path.join(slugStore, f)).catch(() => null))?.seconds ?? 0); if (fin > 0) return fin; let min = Infinity; for (const f of g.streams) { if ((await sizeOf(path.join(slugStore, f))) === 0) continue; min = Math.min(min, (await probe(path.join(slugStore, f)).catch(() => null))?.seconds ?? 0); } return Number.isFinite(min) ? min : 0; }; // Every file of the part, scratch too (the watchdog's growth). const allBytesOf = async (stem: string) => { const g = await filesOf(stem); let n = 0; for (const f of g ? [...g.finished, ...g.streams, ...g.scratch] : []) n += await sizeOf(path.join(slugStore, f)); return n; }; const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s)); // A separate-streams part where only one stream wrote bytes: which is // missing (null: both wrote, or a finished file holds them). const missingStreamOf = async (stem: string): Promise => { const g = await filesOf(stem); if (!g) return null; for (const f of g.finished) if ((await sizeOf(path.join(slugStore, f))) > 0) return null; const withBytes: string[] = []; for (const f of g.streams) if ((await sizeOf(path.join(slugStore, f))) > 0) withBytes.push(f); if (withBytes.length !== 1) return null; const p = await probe(path.join(slugStore, withBytes[0]!)).catch(() => null); if (p?.videoCodec && p.audioCodec) return null; return p?.videoCodec ? "audio" : p?.audioCodec ? "video" : "unknown"; }; if (resumeEnded) { // Nothing to record: straight to the landing. } else if (plan.platform === "kick") { const vodFmt = fmt; const channel = plan.kickChannel ?? (typeof meta?.uploader_id === "string" ? meta.uploader_id : null); let liveDone = channel === null; if (channel === null) say("The record names no Kick channel: only the VOD is recorded."); const live = channel ? (async () => { const o = await ytdlpPart(`https://kick.com/${channel}`, "channel", "now", "", { watch: false }); liveDone = true; return o; })() : Promise.resolve(); let poll: Promise = Promise.resolve(); if (vodFmt) { const file = partPath("vod"); const part = begin("vod-poll", vodFmt.url, file, true); await save(); poll = (deps.poll ?? pollEventPlaylist)({ playlistUrl: vodFmt.url, output: file, onLog, signal, liveEnded: () => liveDone, ...(deps.fetchText ? { fetchText: deps.fetchText } : {}), ...(deps.fetchBytes ? { fetchBytes: deps.fetchBytes } : {}), }).then(async (r) => { finish(part, `${r.segments} segment(s) from ${r.firstSeq ?? "?"}, ${r.gaps} gap(s); ${r.ended}`); // Proven from the start only when the poll's first segment is the // platform's first (REVIEW-LF-2 2). if (r.firstSeq !== null && r.firstSeq <= firstSequenceOf("kick")) part.provenStart = true; await save(); }); } else { say("The VOD offers no HLS playlist to poll: only the channel's live stream is recorded (from now)."); } await Promise.all([live, poll]); } else { let pathB = false; if (extractionError === null) { // THE ATTEMPTS (lib/liveCapture.ts liveAttemptSchedule): from its start // at 0, +60 and +180 s, then from the live edge at 0, +60 and +180 s — // each wait stretched by pacing.jitter, ended by a Cancel. An attempt // that recorded NOTHING (or, for separate streams, only one of the two) // is retried when another try may not meet the same failure: the // failure's class (liveFailureClass) decides — // ended, private, members-only, the disk not retried // 429 / the bot check ONE more try, the same // mode, after 15 min; then // not again // empty, network, unknown, one stream the schedule // A part with bytes in both streams (whatever yt-dlp's exit: a normal // stream end often exits 1), a Cancel and an argv no try can fix end the // attempts. const schedule = liveAttemptSchedule(fromStart); // SLICE 4 — THE INSURANCE RECORDER (lib/liveCapture.ts LiveInsurance): // the live edge beside the from-start recording while it catches up. // On by default when the stream is marked keep before or when the // recording starts; the request's `insurance` overrides. Not for an // upcoming stream (its from-start recording is never behind). const keepMarked = req.doNotClean === true || (await isDoNotClean(videoDir).catch(() => false)) || (await loadPendingKeep(paths, req.slug).catch(() => [])).some((e) => e.id === id); let decided = fromStart && liveStatus !== "is_upcoming" ? insuranceDecision({ asked: req.insurance, keepMarked }) : null; if (!decided && req.insurance) say("No insurance recorder: it runs only beside a from-start recording of a stream already live."); // The insurance's stop: replaced when a from-start restart re-arms it. let insureStop = new AbortController(); const mainDoneCtl = new AbortController(); let insuranceStopFor: "caught-up" | "ended" | "fallback" | null = null; let mainStem: string | null = null; let mainFromStart = false; const tracker = catchUpTracker(); // The main from-start part's own catch-up (its frag N/M), and the stem // that last showed it caught up. const mainTracker = catchUpTracker(); let caughtUpStem: string | null = null; let caughtUpTimer: NodeJS.Timeout | null = null; let graceTimer: NodeJS.Timeout | null = null; let rearm: (() => void) | null = null; const margin = deps.insuranceMarginMs ?? LIVE_INSURANCE_MARGIN_MS; // The main recorder's parts: which one records now, and its progress. // A from-start RESTART is behind the live edge again: the catch-up is // read afresh and a stopped insurance is re-armed (REVIEW-1 3.2 of // live-guard-2). A fall back to the live edge stops the insurance. // Re-arm a stopped insurance (within its bound) beside a from-start // capture that is behind again: a recovery try (REVIEW-3 3.2). // True when a start follows (REVIEW-7 3: never "re-armed" in the log // when nothing starts). const rearmInsurance = (): boolean => { // Not while a live-edge main records already (REVIEW-4 1.2). if (!record.insurance || !mainFromStart) return false; if (caughtUpTimer) clearTimeout(caughtUpTimer); caughtUpTimer = null; if (insureStop.signal.aborted && insuranceStopFor === "caught-up") { insureStop = new AbortController(); insuranceStopFor = null; } const r = rearm; r?.(); return r !== null; }; // A RESTART never stops a working insurance recorder (REVIEW-3 3.2 of // live-guard-2): only the schedule's own fall back to the live edge does. const onMainStart = (mode: "from-start" | "index0" | "now", restart = false) => (stem: string) => { // REVIEW-7 7: a from-start part that printed no `frag N/M` line could // not be judged behind or not — said on its part. if (mainStem && mainStem !== stem && mainFromStart && !behindChecked.has(mainStem)) { const prev = parts.find((x) => x.stem === mainStem)?.part; if (prev && (prev.bytes ?? 0) > 0) prev.behindUnknown ??= "it printed no frag N/M line"; } if (stem !== mainStem) mainTracker.reset(); mainStem = stem; mainFromStart = mode !== "now"; tracker.reset(); if (!record.insurance) return; if (mode === "now" && !restart && !insureStop.signal.aborted) { insuranceStopFor = "fallback"; insureStop.abort(); } // (No re-arm on every restart or resume: DESIGN-5 point 5 — the // behind check below starts or re-arms it when a part is far behind.) void restart; }; // DESIGN-5 POINT 5 (the orchestrator's go, settings.liveRecording. // insuranceWhenBehind): a from-start main part's FIRST `frag N/M` shows // how far behind the live edge it is — the stream's age × (1 − N/M). // More than 10 min: the live-edge insurance starts beside it (or is // re-armed), whatever the keep mark, so the tail is held while it // catches up. Once per part. const behindChecked = new Set(); const behindCheck = (l: string) => { if (!mainFromStart || !mainStem || behindChecked.has(mainStem)) return; const fp = parseFragProgress(l); if (!fp || fp.total <= 0) return; behindChecked.add(mainStem); const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; const mainPart = parts.find((x) => x.stem === mainStem)?.part; if (!Number.isFinite(startMs)) { if (mainPart) mainPart.behindUnknown = "the stream's start time is not known"; say(`${mainStem}: how far behind the live edge it is cannot be told (the stream's start time is not known): no live-edge insurance by the behind rule.`); return; } const behind = ((now().getTime() - startMs) / 1000) * (1 - fp.frag / fp.total); if (behind <= LIVE_INSURANCE_BEHIND_SECONDS) return; // REVIEW-7 7: a live-edge recorder only beside a stream that reads LIVE // (a boot run on a post_live stream behind must not start one) — by the // last read that READ (REVIEW-8 1: a failed one says nothing), and said. if (lastRead.goodStatus !== "is_live") { say(`${mainStem} is about ${spanWords(behind)} behind, but the stream did not last read live (${lastRead.goodStatus ?? "unknown"}): no live-edge recorder beside it.`); return; } if (req.insurance === false) return; if (!(deps.insuranceWhenBehind ?? liveInsuranceWhenBehind())) { say(`${mainStem} is about ${spanWords(behind)} behind the live edge; no live-edge recorder beside it (settings.liveRecording.insuranceWhenBehind is off).`); return; } if (!insurance || insuranceReturned) { // (REVIEW-7 3: also when an earlier insurance loop has returned.) decided = decided ?? { mode: "catch-up", by: "behind" }; if (insuranceReturned) { insureStop = new AbortController(); insuranceStopFor = null; } say(`${mainStem} is about ${spanWords(behind)} behind the live edge: a live-edge recorder (the insurance) starts beside it, so the tail is held while it catches up.`); startInsuranceLoop(); } else if (rearmInsurance()) { say(`${mainStem} is about ${spanWords(behind)} behind the live edge: the insurance is re-armed beside it.`); } else { say(`${mainStem} is about ${spanWords(behind)} behind the live edge; the insurance recorder is already recording beside it.`); } }; const onMainLine = (l: string) => { behindCheck(l); if (mainFromStart && mainTracker.feed(l)) caughtUpStem = mainStem; if (record.insurance?.mode !== "catch-up" || caughtUpTimer || insureStop.signal.aborted || !mainFromStart) return; if (!tracker.feed(l)) return; say(`The from-start recording has caught up with the live edge; the insurance recorder stops in ${spanWords(margin / 1000)}.`); const stopping = insureStop; caughtUpTimer = setTimeout(() => { caughtUpTimer = null; if (stopping !== insureStop) return; insuranceStopFor = "caught-up"; stopping.abort(); }, margin); }; // True when re-armed; false when the main recording ended or a Cancel. const waitRearm = () => new Promise((resolve) => { if (mainDoneCtl.signal.aborted || signal.aborted) return resolve(false); const end = () => resolve(false); mainDoneCtl.signal.addEventListener("abort", end, { once: true }); signal.addEventListener("abort", end, { once: true }); rearm = () => { rearm = null; resolve(true); }; }); // THE INSURANCE (slice 4), re-armed within LIVE_INSURANCE_MAX_STARTS: // after it died early (REVIEW-1 3.1: an exit before the catch-up or the // stream's end is `died`, never "to the end"), and after a from-start // restart put the main behind again. const insureLoop = async (): Promise => { const ins: LiveInsurance = { mode: decided!.mode, by: decided!.by, state: "waiting", starts: 0 }; let insLimited = false; let rateWait: number | null = null; record.insurance = ins; await save(); const notStarted = async (reason: string) => { if (!ins.starts) ins.state = "not-started"; ins.reason = reason; await save(); }; for (;;) { const stopNow = insureStop; const waitStop = AbortSignal.any([signal, stopNow.signal, mainDoneCtl.signal]); // The from-start part's first bytes (its extraction is done). while (!waitStop.aborted && !record.fallback) { if (mainStem && mainFromStart && (await bytesOf(mainStem)) > 0) break; if (recoveryStem && (await bytesOf(recoveryStem)) > 0) break; await sleep(deps.insurancePollMs ?? 5_000, waitStop); } if (record.fallback) return notStarted("the run fell back to the live edge"); if (signal.aborted) return notStarted("stopped"); if (mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); if (stopNow.signal.aborted) { if (!ins.starts) await notStarted("the from-start recording caught up before it began"); if (!(await waitRearm())) return; continue; } // After a rate limit: ONE more start after LIVE_RATE_LIMIT_WAIT_MS // (REVIEW-2 4.1), never the 60 s pause. await waitFor(stretch(rateWait ?? LIVE_INSURANCE_DELAY_MS), waitStop); rateWait = null; if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); if (stopNow.signal.aborted) continue; if ((ins.starts ?? 0) >= LIVE_INSURANCE_MAX_STARTS) { ins.reason = `not started again: at most ${LIVE_INSURANCE_MAX_STARTS} starts a run`; await save(); return; } // At most LIVE_INSURANCE_MAX_STARTS_PER_HOUR an hour: the hour is // waited out, not an end. { const t = now().getTime(); const recent = (ins.startTimes ?? []).map((x) => Date.parse(x)).filter((x) => t - x < 3_600_000).sort((a, b) => a - b); if (recent.length >= LIVE_INSURANCE_MAX_STARTS_PER_HOUR) { const ms = Math.max(1_000, recent[0]! + 3_600_000 - t); say(`The insurance recorder has started ${recent.length} times in the last hour: the next start waits ${spanWords(ms / 1000)}.`); await waitFor(ms, waitStop); if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); // (REVIEW-7 7: stopped while it waited — no start spent on it.) if (stopNow.signal.aborted) continue; } } if (!(await roomFor("the insurance recorder"))) return notStarted("the store's disk is under the free-space floor"); ins.starts = (ins.starts ?? 0) + 1; (ins.startTimes ??= []).push(now().toISOString()); ins.state = "recording"; delete ins.reason; say( `The insurance recorder records the live edge beside the from-start recording` + `${ins.mode === "whole" ? " for the whole stream" : " until it catches up"} (${ins.by === "default" ? "the stream is marked keep" : ins.by === "behind" ? "the from-start part is far behind" : "asked"})` + `${ins.starts > 1 ? `, start ${ins.starts} (at most ${LIVE_INSURANCE_MAX_STARTS_PER_HOUR} an hour)` : ""}.`, ); const tag = ins.starts === 1 ? "ytdlp-insure" : `ytdlp-insure-r${ins.starts}`; const o = await ytdlpPart(plan.url, tag, "now", "insurance; ", { insurance: true, noWait: true, stop: stopNow.signal }); const bytes = await bytesOf(o.stem); const last = recentOutput(o); const errLine = lastErrorLine(last); const cls = !o.signalled && o.exitCode !== 0 ? liveFailureClass(last) : null; if (signal.aborted) ins.state = "stopped"; else if (insuranceStopFor === "fallback") { ins.state = "stopped"; ins.reason = "the run fell back to the live edge"; } else if (insuranceStopFor === "caught-up") ins.state = "caught-up"; else if (insuranceStopFor === "ended" || (mainDoneCtl.signal.aborted && endRead)) ins.state = "ended"; // REVIEW-7 3: an exit 0 while the from-start part still records and // has not caught up is not the stream's end — it died (an ingest // pause ends a live-edge recorder too): started again. else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0 && !mainDoneCtl.signal.aborted && caughtUpStem !== mainStem) { ins.state = "died"; ins.reason = "it ended by itself while the from-start recording was still behind"; } else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0) ins.state = "ended"; // the live edge ended: the stream is over else if (cls === "ended" || cls === "private" || cls === "members" || cls === "disk") { ins.state = bytes > 0 ? "ended" : "failed"; ins.reason = errLine ?? `yt-dlp exit ${o.exitCode ?? "null"}`; } else if (cls === "rate-limited") { if (insLimited) { ins.state = "stopped"; ins.reason = `rate-limited again after the ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)} wait (${errLine ?? "429"}): not started again`; } else { insLimited = true; rateWait = LIVE_RATE_LIMIT_WAIT_MS; ins.state = "died"; ins.reason = `rate-limited (${errLine ?? "429"}): ONE more start after ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}`; } } else { ins.state = "died"; ins.reason = o.stalled ? "it stalled and was stopped" : `it ${bytes > 0 ? "exited" : "recorded nothing and exited"} (${errLine ?? `yt-dlp exit ${o.exitCode ?? "null"}`}) before the from-start recording caught up`; } await save(); if (ins.state === "died") { say(`The insurance recorder died early (${ins.reason}); ${(ins.starts ?? 0) < LIVE_INSURANCE_MAX_STARTS ? "it is started again" : "not started again"}.`); continue; } if (ins.state === "caught-up") { if (!(await waitRearm())) return; continue; } return; } }; let insurance: Promise | null = null; let insuranceReturned = false; const insuranceLoops: Promise[] = []; const startInsuranceLoop = () => { insuranceReturned = false; const p = insureLoop().finally(() => { insuranceReturned = true; }); insuranceLoops.push(p); insurance = p; }; if (decided) startInsuranceLoop(); let index0 = false; let fromStartFailures = 0; let edgeFailures = 0; let lastReason: string | null = null; let rateLimitRetried = false; // SLICE 2 — THE START, TRIED AGAIN BESIDE THE LIVE EDGE (lib/liveCapture.ts // LIVE_RECOVERY_*): one from-start try every 15 min (jittered), one at a // time, at most 8, each its own part (`ytdlp-recover-r`); the // live-edge recorder is never signalled by it. It stops when the // live-edge recording ends (a try still waiting is not made), on a // failure no try can help, on a second rate limit, on a Cancel, or when // the tries are spent. A try that records and ends while the live edge // still records died mid-stream: the next try follows, inside the bound. // The main recording's last attempt (what the restarts below look at). // `partial`: only one of its two streams wrote (never restarted here: // the schedule above already tried). let lastMain: { o: Awaited>; bytes: number; mode: "from-start" | "index0" | "now"; partial: boolean } | null = null; let recovery: Promise | null = null; let recoveryRunning = false; // The recovery try recording now (the insurance's re-arm watches it). let recoveryStem: string | null = null; // A GAP recovery (REVIEW-3 3.1): its tries stop once a from-start part // reaches this stream second (where the newest live-edge part begins). let gapTarget: number | null = null; // The newest live-edge restart's stem (a gap recovery waits for its bytes). let edgeRestartStem: string | null = null; const recoveryStop = new AbortController(); let edgeDone = false; const recoverStart = async (useIndex0: boolean, ro: { gap?: boolean } = {}): Promise => { recoveryRunning = true; try { await recoverLoop(useIndex0, ro); } finally { recoveryRunning = false; recoveryStem = null; } }; const recoverLoop = async (useIndex0: boolean, ro: { gap?: boolean }): Promise => { // The tries of the run are one bound across every recovery (8). const rs: StartRecovery = record.startRecovery && record.startRecovery.state !== "recovered" ? record.startRecovery : { tries: record.startRecovery?.tries ?? 0, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS, state: "waiting" }; rs.state = "waiting"; record.startRecovery = rs; const waitStop = AbortSignal.any([signal, recoveryStop.signal]); say( ro.gap ? `From its start is fetched again beside the live edge, at once, until it reaches where the live-edge part begins: ` + `one try at a time, at most ${LIVE_RECOVERY_MAX_TRIES} a run, every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}.` : `From its start is tried again beside the live edge: every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}, ` + `at most ${LIVE_RECOVERY_MAX_TRIES} times, one at a time; the live-edge recording is not touched.`, ); let limited = false; let first = true; // A try that recorded from its start and stopped while the stream was // live: the loop's later stop does not make that "stopped" (the // order of the live edge's end and that try's end is not the point). let recordedOne = false; while (rs.tries < rs.max) { if (!(ro.gap && first)) await (deps.recoveryWait ?? waitFor)(stretch(LIVE_RECOVERY_EVERY_MS), waitStop); first = false; if (waitStop.aborted || edgeDone) { rs.state = recordedOne ? "recorded" : "stopped"; say(`Start recovery: the live-edge recording ${signal.aborted ? "was stopped" : "ended"} before try ${rs.tries + 1}; no more tries.`); break; } if (!(await roomFor(`start recovery try ${rs.tries + 1}`))) { rs.state = "gave-up"; rs.failureClass = "disk"; rs.lastError = "the store's disk is under the free-space floor"; break; } rs.tries++; rs.state = "trying"; // A gap's try is stopped once it reaches the live-edge part's start // (plus a minute's overlap for the join), then the span is held. const reached = new AbortController(); let covered = false; let watcher: NodeJS.Timeout | null = null; const tag = `ytdlp-recover-r${rs.tries}`; // Also stopped on the stream's own clock: its frag N/M caught up, then // a minute (REVIEW-4 2.1(c)). const tryTracker = catchUpTracker(); let caughtTimer: NodeJS.Timeout | null = null; const o = await ytdlpPart(plan.url, tag, useIndex0 ? "index0" : "from-start", `start recovery ${rs.tries}/${rs.max}; `, { recovery: true, stop: reached.signal, onLine: (l) => { if (!ro.gap || caughtTimer || reached.signal.aborted || !tryTracker.feed(l)) return; caughtTimer = setTimeout(() => { covered = true; say(`Start recovery: try ${rs.tries} has caught up with the live edge (its own fragments): the span is held; it is stopped.`); reached.abort(); }, LIVE_RESTART_CONFIRM_MS); }, onStart: (stem) => { recoveryStem = stem; rearmInsurance(); if (!ro.gap) return; let busy = false; watcher = setInterval(() => { if (busy || reached.signal.aborted || gapTarget === null) return; // An index-0 try begins at the playlist's first LISTED segment: // its length is no stream position (REVIEW-4 2.1(b)). if (useIndex0 && record.reach?.fromStart !== true) return; busy = true; void secondsOf(stem) .then((sec) => { if (gapTarget !== null && sec >= gapTarget + 60) { covered = true; say(`Start recovery: try ${rs.tries} holds the stream to ${spanWords(sec)}, past where the live-edge part begins: the span is held; it is stopped.`); reached.abort(); } }) .finally(() => { busy = false; }); }, watchMs); }, }); if (watcher) clearInterval(watcher); if (caughtTimer) clearTimeout(caughtTimer); recoveryStem = null; if (covered) { rs.state = "recovered"; await save(); break; } const bytes = await bytesOf(o.stem); const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(o.stem) : null; // A try the watchdog stopped with nothing written failed; one with // bytes died mid-stream like one that exited. const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted; const cls = stalledEmpty ? "nothing" : o.stalled && !signal.aborted ? "recorded" : classifyAttempt({ ...o, bytes, partial: missing !== null }); if (cls === "recorded") { if (edgeDone || signal.aborted) { rs.state = "recorded"; say(`Start recovery: try ${rs.tries} recorded from its start to the stream's end.`); break; } say(`Start recovery: try ${rs.tries} recorded from its start and stopped while the stream is live; its part is kept, the next try follows.`); recordedOne = true; rs.state = "waiting"; await save(); continue; } if (cls === "stopped") { rs.state = "stopped"; break; } const errLine = stalledEmpty ? `stalled: nothing written for ${spanWords(stallMs / 1000)}` : (lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`); const failure: LiveFailureClass = stalledEmpty ? "stalled" : cls === "partial" ? "partial" : cls === "argv" ? "argv" : cls === "unsupported" ? "unsupported" : liveFailureClass(o.stderrTail); o.part.error = missing !== null ? `the ${missing === "unknown" ? "video or audio" : missing} stream recorded nothing (${errLine})` : errLine; o.part.failureClass = failure; if (missing !== null) o.part.missingStream = missing; rs.lastError = o.part.error; rs.failureClass = failure; if (cls === "final" || cls === "argv" || cls === "unsupported" || (cls === "rate-limited" && limited)) { rs.state = "gave-up"; say(`Start recovery: try ${rs.tries} recorded nothing (${o.part.error}) [${failure}]: no more tries.`); break; } if (cls === "rate-limited") limited = true; rs.state = "waiting"; say( `Start recovery: try ${rs.tries} of ${rs.max} recorded nothing (${o.part.error})` + (rs.tries < rs.max ? `; the next in ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}.` : "."), ); await save(); } const endState = rs.state as StartRecovery["state"] as string; if (endState === "waiting" || endState === "trying") { rs.state = "exhausted"; say(`Start recovery: all ${rs.max} tries made; the stream's start is NOT recorded.`); } await save(); }; for (let slot = 0; slot < schedule.length && !signal.aborted; ) { const step = schedule[slot]!; const n = (record.attempts ?? 0) + 1; const mode = step.mode === "live-edge" ? "now" : index0 ? "index0" : "from-start"; const tag = `ytdlp${mode === "index0" ? "-index0" : ""}${mode === "now" && fromStart ? "-edge" : ""}${n > 1 && !(mode === "index0" && n === 2) ? `-a${n}` : ""}`; // SLICE 2: the first live-edge attempt after a fallback starts the // from-start tries beside it (their first is 15 min away). if (mode === "now" && fromStart && record.fallback === "live-edge" && recovery === null) recovery = recoverStart(index0); // DESIGN-3: a restart after the editor's resumes the interrupted run's // from-start part in place when its state is there. let bootResume: { stem: string; formats: string; provenStart?: boolean; lock?: StemLock } | null = null; let bestLock: StemLock | null = null; let reusedFragments: number | null = null; // DESIGN-5 7: ANY run's first from-start attempt (a Record again too) // reuses a part an earlier run left in staging when it can be proven. if (slot === 0 && mode === "from-start" && n === 1 && (resumeOf || separate)) { // REVIEW-5 B3: of every row of the id, the LONGEST resumable // from-start part — a stem any row lists as waiting, or a from-start // part of the interrupted row. The others are released to the landing. const rows = (await loadLiveRecordingRows(paths, req.slug).catch(() => [])).filter((r) => r.id === id); const partOfStem = new Map(rows.flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); const inStaging = new Set(livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).map((g) => g.stem)); const stems = new Set([ ...rows.flatMap((r) => r.awaitingResume ?? []), ...(rows.find((r) => r.startedAt === resumeOf)?.parts ?? []).filter((x) => x.stem && x.fromStart && !x.index0).map((x) => x.stem!), // Every proven from-start part of the id still in staging. ...(separate ? rows.flatMap((r) => r.parts).filter((x) => x.stem && x.provenStart && x.fromStart && !x.index0 && inStaging.has(x.stem)).map((x) => x.stem!) : []), ]); let best: { stem: string; formats: string; fragment: number; bytes: number; reuse?: boolean } | null = null; for (const stem of stems) { const st = await resumeStateOf(stem); const ru = st.ok || !separate ? null : await restoreForReuse(stem, false); if (!st.ok && !ru?.ok) continue; const b = await allBytesOf(stem); if (!best || b > best.bytes) best = { stem, formats: st.ok ? st.formats : "", fragment: st.ok ? st.fragment : ru!.ok ? ru!.fragments : 0, bytes: b, ...(st.ok ? {} : { reuse: true }) }; } if (best?.reuse) { const ru = await restoreForReuse(best.stem, true); const st = ru.ok ? await resumeStateOf(best.stem) : null; if (st?.ok && ru.ok) { best = { ...best, formats: st.formats, fragment: st.fragment }; reusedFragments = ru.fragments; } else best = null; } if (best) { // The one repair (DESIGN-4 1) before the resume; not provable: a // fresh from-start part (this attempt, a new stem) instead. const rc = await reconcileForResume(best.stem); if (!rc.ok) { say(`${best.stem} is not resumed in place (${rc.why}); a fresh part from the stream's start records instead.`); best = null; } else bestLock = rc.lock; } if (best) { const p = partOfStem.get(best.stem); // The mark the interrupted run earned travels with its file. bootResume = { stem: best.stem, formats: best.formats, ...(p?.provenStart ? { provenStart: true } : {}), ...(bestLock ? { lock: bestLock } : {}) }; say(`${resumeOf ? "Restart after the editor restart: " : ""}${best.stem}, an earlier part, is resumed in place from fragment ${best.fragment}${reusedFragments !== null ? " (its state rebuilt from its kept fragments: they are reused, not fetched again)" : ""}.`); // This run holds it now: no row lists it as waiting. const resumed = best.stem; for (const r of rows.filter((x) => x.awaitingResume?.includes(resumed))) { await patchLiveRecordingRow(paths, req.slug, id, r.startedAt, (x) => { if (!x.awaitingResume?.includes(resumed)) return false; x.awaitingResume = x.awaitingResume.filter((y) => y !== resumed); if (!x.awaitingResume.length) delete x.awaitingResume; }).catch((e: Error) => say(`The interrupted row could not be updated (${e.message}).`)); } } } const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "", { onStart: onMainStart(mode), onLine: onMainLine, firstAttempt: n === 1, ...(bootResume ? { resume: bootResume, noWait: true } : {}), }); if (bootResume && reusedFragments !== null) { o.part.reused = { fragments: reusedFragments, at: now().toISOString() }; await save(); } // This attempt's own part (a try beside it may have begun one since). const last = { part: o.part, stem: o.stem }; const bytes = await bytesOf(last.stem); const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(last.stem) : null; lastMain = { o, bytes, mode, partial: missing !== null }; // Stopped by the watchdog with nothing written: an attempt that // recorded nothing (the schedule goes on). With bytes: the restarts // below decide. const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted; const cls = stalledEmpty ? "nothing" : classifyAttempt({ ...o, bytes, partial: missing !== null }); if (cls === "recorded" || cls === "stopped" || signal.aborted) { // (A stream the part has not recorded stays said: REVIEW-5 B5.) if (!last.part.missingStream) delete record.missingStream; delete record.failureClass; break; } const errLine = stalledEmpty ? `stalled: nothing written for ${spanWords(stallMs / 1000)}` : (lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`); const failure: LiveFailureClass = stalledEmpty ? "stalled" : cls === "partial" ? "partial" : cls === "argv" ? "argv" : cls === "unsupported" ? "unsupported" : liveFailureClass(o.stderrTail); const reason = missing !== null ? `${missing === "unknown" ? "one of its two streams" : `the ${missing} stream`} recorded nothing (${errLine})` : errLine; last.part.error = reason; last.part.failureClass = failure; if (missing !== null) last.part.missingStream = missing; record.failureClass = failure; if (missing !== null) record.missingStream = missing; else if (!last.part.missingStream) delete record.missingStream; await save(); lastReason = reason; if (o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) { say( 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.', ); } if (bytes === 0 && o.exitCode !== 0 && BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(o.stderrTail)) { say("yt-dlp was refused; recording from the page's own playlist."); pathB = true; break; } if (cls === "unsupported" && !index0) { say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment."); index0 = true; continue; } if (cls === "argv") { say(`Attempt ${n} recorded nothing (${reason}); the same command would fail the same way: not retried.`); break; } if (cls === "final") { const why = failure === "ended" ? "the stream is over" : failure === "private" ? "the stream is private, removed or unavailable" : failure === "members" ? "the stream is members-only or needs a login" : "the store's disk cannot take it"; say(`Attempt ${n} recorded nothing (${reason}); ${why} (${failure}): not retried.`); break; } if (step.mode === "from-start") fromStartFailures++; else edgeFailures++; if (cls === "rate-limited") { if (rateLimitRetried) { say( `Attempt ${n} was refused again (${reason}) after a ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)} wait: a rate limit or the bot check — stopping, not retried again.`, ); break; } rateLimitRetried = true; say( `Attempt ${n} was refused (${reason}): a rate limit or the bot check — ONE more try ${step.mode === "live-edge" ? "from the live edge" : "from its start"} in ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}, then no more.`, ); await waitFor(stretch(LIVE_RATE_LIMIT_WAIT_MS), signal); continue; } slot++; const next = schedule[slot]; if (!next) break; if (next.mode === "live-edge" && step.mode === "from-start") { const lostTo = streamStartSec !== null ? Math.max(0, Math.round(now().getTime() / 1000 - streamStartSec)) : null; record.fallback = "live-edge"; record.lost = { fromSeconds: 0, toSeconds: lostTo }; await save(); say( `${plan.url} from its start failed ${fromStartFailures} times (${reason}); recording from the live edge` + (lostTo !== null ? ` since ${spanWords(lostTo)} into the stream — the first ${spanWords(lostTo)} are NOT recorded.` : ` — the stream before now (its start is not known) is NOT recorded.`), ); } else { say(`Attempt ${n} recorded nothing (${reason}); attempt ${n + 1} ${next.mode === "live-edge" ? "from the live edge" : "from its start"} in ${spanWords(next.waitMs / 1000)}.`); } await waitFor(stretch(next.waitMs), signal); } // SLICE 3 — THE RESTARTS (lib/liveCapture.ts LiveRestarts). The main // recording's last part stalled with bytes, or its recorder exited with // bytes: is the stream still live? One metadata read (the read the job // makes at its end anyway; an exit is read twice, a minute apart, as a // stream just ended may read live a moment). Live → a new part in the // same mode after a pause, the old part kept for the landing; ended → // land; unreadable → a stall restarts (the recorder's own exit says // when a stream is over), an exit lands. Bounded: 3 in any hour, 12 in // the run, and the store's disk must have room. let cur = lastMain; // SLICE 3 as REVIEW-2 of live-guard-2 ruled: A STREAM THAT READS LIVE IS // NEVER LEFT UNRECORDED QUIETLY, and a restart never re-downloads what // a kept part already holds. A recorder that exited or stalled is // followed by a LIVE-EDGE recorder (its own stem; the earlier part kept // for the landing and the join): an earlier part holds the past. (When // no part holds the stream's START, the slice-2 tries beside the live // edge are the from-start path, with their own bound.) The stream is // taken as ended only on evidence: the state read says so, or three // live-edge recorders in a row capture nothing. Bounds: 6 restarts in // any hour and 24 in the run; past them, or when the state cannot be // read after an exit, the row says the stream may be live and NOT // recorded, and needs a person. let restartLimited = false; let emptyInRow = 0; // Stems whose resume was impossible or wrote nothing (not tried again). const resumeFailed = new Set(); // DESIGN-4 3: aborts per stem at one fragment; where a fresh part's // predecessor could not get past; whether the last fresh part wrote nothing. const abortTries = new Map(); // Why the last resume was not made (the fresh part says it, only when known). let noResumeWhy: string | null = null; const netTries = new Map(); let endResumed = false; let freshAbortAt: number | null = null; let freshFailedLast = false; while (cur && !signal.aborted && !pathB) { const stalledWithBytes = cur.o.stalled && cur.bytes > 0; // (A partial exit too — one stream missing — DESIGN-5 1: while the // stream is live it restarts; a fresh or resumed part asks for both.) const exitedWithBytes = !cur.o.signalled && cur.bytes > 0; const fragAborted = cur.o.fragAbort !== undefined && cur.bytes > 0 && !signal.aborted; const failedRestart = cur.o.part.restart !== undefined && cur.bytes === 0 && !(cur.o.signalled && !cur.o.stalled); if (!stalledWithBytes && !exitedWithBytes && !fragAborted && !failedRestart) break; if (cur.bytes > 0) freshFailedLast = false; const why = cur.o.stalled ? "stalled" : fragAborted ? "a fragment could not be fetched" : exitedWithBytes ? "exited while the stream was live" : "recorded nothing"; // What the recorder said LAST (its output after its last progress // line), classified — also for a part with bytes (REVIEW-2 3.3). const said = recentOutput(cur.o); const cls: LiveFailureClass | null = !cur.o.signalled && cur.o.exitCode !== 0 ? liveFailureClass(said) : null; if (cls && cls !== "unknown") { cur.o.part.failureClass = cls; cur.o.part.error ??= lastErrorLine(said) ?? `yt-dlp exit ${cur.o.exitCode ?? "null"}`; await save(); } const restarts = (record.restarts ??= { count: 0, at: [] }); const refuse = async (r: string, words: string) => { restarts.refused = `${why}; ${r}`; await save(); say(words); }; if (cls === "disk") { await refuse("the store's disk cannot take it", "NOT restarted: the store's disk cannot take it; what was recorded lands, and the row needs a person."); break; } if (emptyInRow >= LIVE_EDGE_EMPTY_TO_END) { const st = await liveNow(); if (st !== "ended") { await refuse( "three live-edge recorders in a row captured nothing", "Three live-edge recorders in a row captured nothing: the stream is taken as ended, though it still reads live — it may be live and NOT recorded; the row needs a person.", ); } break; } // The state is ALWAYS read before a conclusion (never stderr text // alone): the platform's word decides. let state = await liveNow(); if (state === "live" && exitedWithBytes && cls !== "rate-limited") { // DESIGN-4 5: a from-start recorder that ended by itself (yt-dlp's // own end after ~35 s with no fragment: an ingest pause) — the live // edge is held at once (the insurance re-armed) before the read. // (No re-arm here — REVIEW-6 / DESIGN-5 point 5: the same files // continue, reused, in seconds; a part found far behind starts the // insurance by its first frag N/M.) say(`${cur.o.part.stem}: its recorder exited while the stream reads live; read again in ${spanWords(LIVE_RESTART_CONFIRM_MS / 1000)} before restarting.`); await waitFor(stretch(LIVE_RESTART_CONFIRM_MS), signal); if (signal.aborted) break; state = await liveNow(); } // REVIEW-7 1 — OFFLINE: while the state read fails for the NETWORK, // nothing is spawned and no restart is spent: the read is made again // on a paced wait (20 s, 60 s, 180 s, then every 5 min) for as long as // it takes, said on the row; once it reads again, the part is resumed // in place first. if (state === "unknown" && lastRead.failClass === "network") { const since = now().toISOString(); let k = 0; while (state === "unknown" && lastRead.failClass === "network" && !signal.aborted) { const w = OFFLINE_READ_WAITS_MS[Math.min(k, OFFLINE_READ_WAITS_MS.length - 1)]!; k++; record.offline = { since, reads: k }; await save(); say(`The stream's state cannot be read (the network?): nothing is started; read again in ${spanWords(w / 1000)} (read ${k}).`); await waitFor(stretch(w), signal); if (signal.aborted) break; state = await liveNow(); } delete record.offline; await save(); if (signal.aborted) break; } if (state === "ended") { // REVIEW-6 4: the stream ended while its from-start part may still // be behind — an ended stream is still served from its start (the // generator runs once more, post_live): resumed ONCE to its end. // (Not after a recorder that reached the stream's end by itself: // exit 0 with no fragment it could not fetch, no failed URL // refresh, and not seen caught up — yt-dlp ends a from-start // download at the stream's end.) const mayBeBehind = cur.o.signalled || cur.o.stalled || cur.o.exitCode !== 0 || cur.o.fragAbort !== undefined || cur.o.urlRefresh === true; // REVIEW-7 2: ONLY on `post_live` — a was_live stream's formats are // ordinary files, and the same output name would have yt-dlp append // foreign bytes to the stream files (measured). Otherwise it lands // (short of the ended duration: "download the VOD now"). if (mayBeBehind && !endResumed && lastRead.status !== "post_live" && cur.mode === "from-start" && !endedByRefusal) { say(`The stream has ended (${lastRead.status ?? "its state"}): ${cur.o.part.stem} is NOT resumed (only a post_live stream is still served from its start); what is held lands — if it is short of the stream, download the VOD now.`); } if (!endResumed && mayBeBehind && lastRead.status === "post_live" && caughtUpStem !== cur.o.stem && !endedByRefusal && cur.mode === "from-start" && separate && !signal.aborted) { endResumed = true; let st = await resumeStateOf(cur.o.stem); if (!st.ok) { const ru = await restoreForReuse(cur.o.stem, true); if (ru.ok) st = await resumeStateOf(cur.o.stem); } const rc = st.ok ? await reconcileForResume(cur.o.stem) : null; if (st.ok && rc?.ok) { say(`The stream has ended: ${cur.o.part.stem} is resumed once from fragment ${st.fragment} to the stream's end (an ended stream is still served from its start).`); const o = await ytdlpPart(plan.url, "resume", "from-start", "resume to the end; ", { resume: { stem: cur.o.stem, formats: st.formats, ...(rc?.ok ? { lock: rc.lock } : {}) }, noWait: true, onStart: onMainStart("from-start", true), onLine: onMainLine, }); cur = { o, bytes: await bytesOf(o.stem), mode: "from-start", partial: false }; continue; } } if (cur.o.stalled) say(`The stream has ended: what was recorded lands (no restart).`); break; } // A state that cannot be read never ends the recording (REVIEW-3 1.1): // the live edge is restarted meanwhile; the next reads come after // each recorder, paced (2 and 8 min after an empty one); only the // evidence (ended, or three empty recorders in a row) ends it. if (state === "unknown") say("The stream's state could not be read: restarted at the live edge meanwhile; it is read again after the recorder."); if (cls === "ended" || cls === "private" || cls === "members") { say(`The recorder said the stream is ${cls === "ended" ? "over" : cls === "private" ? "private or removed" : "members-only"}, but it reads live: restarted.`); } // At once after a recorder that held bytes; after an empty one, 30 s // (2 and 8 min while the state cannot be read). let pause = emptyInRow === 0 ? 0 : state === "unknown" ? (LIVE_BOOT_STATE_READ_WAITS_MS[emptyInRow - 1] ?? LIVE_RESTART_WAIT_MS) : LIVE_RESTART_WAIT_MS; if (cls === "rate-limited") { if (restartLimited) { await refuse( "rate-limited again after the 15 min wait", "NOT restarted: rate-limited again after the 15 min wait — the stream reads live and is NOT recorded; the row needs a person.", ); break; } restartLimited = true; say(`${cur.o.part.stem}: refused by a rate limit or the bot check, and the stream reads live — ONE restart after ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}, then no more.`); await waitFor(stretch(LIVE_RATE_LIMIT_WAIT_MS), signal); if (signal.aborted) break; pause = 0; } // THE BOUNDS ARE WAITED OUT (REVIEW-5 note 3): on a stream that reads // live the recording does not end at the bound — it waits until the // hour frees a restart, said on the row, and goes on. const bound = restartWaitMs(restarts, now().getTime()); if (bound) { restarts.waiting = { until: new Date(now().getTime() + bound.ms).toISOString(), why: bound.why }; restarts.waited = (restarts.waited ?? 0) + 1; await save(); say(`The restart bound is reached (${bound.why}) while the stream reads live: it waits ${spanWords(bound.ms / 1000)} before restart ${restarts.count + 1} — the stream is NOT recorded meanwhile.`); await waitFor(bound.ms, signal); delete restarts.waiting; await save(); if (signal.aborted) break; // (REVIEW-7 2: an end found after the wait goes through the same // decision as any other — the loop reads again at its top.) if ((await liveNow()) === "ended") continue; } // (A resume in place, when one is possible, needs only the floor plus // its stream files: REVIEW-6 7.) const resumable = cur.mode === "from-start" && separate && ((await resumeStateOf(cur.o.stem, { accounting: false })).ok || (await restoreForReuse(cur.o.stem, false)).ok); if (!(await roomFor(`restart ${restarts.count + 1}`, resumable ? { resumeStem: cur.o.stem } : {}))) { await refuse("not enough room on the store's disk: the stream reads live and is NOT recorded", "NOT restarted for want of disk: the stream reads live and is NOT recorded; the row needs a person."); break; } if (pause) await waitFor(stretch(pause), signal); if (signal.aborted) break; // DESIGN-3 — RESUME IN PLACE. A from-start part whose files keep // yt-dlp's `.ytdl` state (it died, or was stopped without finishing) // is continued: the same stem, its format pinned, from the saved // fragment — no new part, no gap, no second download, no live edge, // no recovery. Only when that is impossible (no state, an unreadable // one, a stream past 120 h, or the resume writes nothing) does the // live-edge fallback below run. // (REVIEW-8 1: a read that failed for anything but the network — a 429, // the bot check, an extractor error — does not abandon the part: it is // resumed in place as before, its files checked after the resume. A // network failure never gets here: it waits offline above.) const resumeRead = state === "live" || (state === "unknown" && lastRead.failClass !== "network"); if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem) && !resumeRead) noResumeWhy = `the last state read says ${lastRead.status ?? "nothing"}`; if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem) && resumeRead) { let st = await resumeStateOf(cur.o.stem); // DESIGN-5 7: finished by yt-dlp itself (exit 0, merged) while live — // reuse what is downloaded, not fragment 0 again. if (!st.ok && separate) { const ru = await restoreForReuse(cur.o.stem, true); if (ru.ok) { cur.o.part.reused = { fragments: ru.fragments, at: now().toISOString() }; await save(); st = await resumeStateOf(cur.o.stem); } else say(`${cur.o.part.stem}: no reuse of what it downloaded (${ru.why}).`); } // DESIGN-4 3 — A FRAGMENT THAT COULD NOT BE FETCHED: resumed after // 20 s, 60 s and 180 s at the same fragment; still failing there, a // fresh from-start part; that one failing at the same place, the // fragment is gone: ONE run of it that may skip (marked, loud). let allowSkip = false; if (st.ok && cur.o.fragAbort) { const a = abortTries.get(cur.o.stem); const n = a && a.fragment === st.fragment ? a.n + 1 : 1; abortTries.set(cur.o.stem, { fragment: st.fragment, n }); if (cur.o.part.fresh !== undefined && freshAbortAt !== null && st.fragment === freshAbortAt && n > FRAGMENT_ABORT_WAITS_MS.length) { allowSkip = true; say(`${cur.o.part.stem}: fragment ${st.fragment + 1} cannot be fetched by a fresh part either — the fragment is gone; one run that may SKIP it (the part is marked, never proven, and the row stays loud).`); } else if (n <= FRAGMENT_ABORT_WAITS_MS.length) { const w = FRAGMENT_ABORT_WAITS_MS[n - 1]!; say(`${cur.o.part.stem}: fragment ${st.fragment + 1} could not be fetched; resumed in ${spanWords(w / 1000)} (try ${n} of ${FRAGMENT_ABORT_WAITS_MS.length} at that fragment).`); await waitFor(stretch(w), signal); if (signal.aborted) break; } else { freshAbortAt = st.fragment; st = { ok: false, why: `fragment ${st.fragment + 1} could not be fetched after ${FRAGMENT_ABORT_WAITS_MS.length} resumes` }; } } let heldLock: StemLock | null = null; if (st.ok) { const rc = await reconcileForResume(cur.o.stem); if (!rc.ok) st = { ok: false, why: rc.why }; else heldLock = rc.lock; } if (st.ok) { restarts.count += 1; restarts.at.push(now().toISOString()); // (REVIEW-6 8: the stream files' bytes only — a re-merge is no progress.) const before = await streamBytesOf(cur.o.stem); say(`Resume ${(cur.o.part.resumes ?? 0) + 1} of ${cur.o.part.stem} (${why}): the same files from fragment ${st.fragment}, format ${st.formats}.`); const o = await ytdlpPart(plan.url, "resume", "from-start", `resume (${why}); `, { resume: { stem: cur.o.stem, formats: st.formats, ...(heldLock ? { lock: heldLock } : {}) }, noWait: true, onStart: onMainStart("from-start", true), onLine: onMainLine, ...(allowSkip ? { allowSkip: true } : {}), }); // Media bytes only (REVIEW-5 note 12: a rewritten state is no progress). const bytes = await bytesOf(o.stem); const grew = (await streamBytesOf(o.stem)) > before; // A resume stopped again by a fragment it cannot fetch is one more // try at that fragment (DESIGN-4 3), not "wrote nothing". if (grew || (o.fragAbort && !signal.aborted)) { emptyInRow = 0; if (grew) { netTries.delete(o.stem); delete record.offline; } const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false; cur = { o, bytes, mode: "from-start", partial }; continue; } const last = recentOutput(o); o.part.resumeError = o.locked ?? lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; await save(); say(`The resume wrote nothing (${o.part.resumeError}).`); if (o.signalled && signal.aborted) break; // REVIEW-6 5: a resume that failed for the network is tried again // (20 s, 60 s, 180 s), not given up after one try. const rcls = liveFailureClass(last); if (rcls === "network" && bytes > 0) { // REVIEW-7 1: a resume that failed for the network spends no // restart, never gives the stem up, and is tried again on the // paced waits (then every 5 min) for as long as it takes. restarts.count = Math.max(0, restarts.count - 1); restarts.at.pop(); const nt = (netTries.get(o.stem) ?? 0) + 1; netTries.set(o.stem, nt); const w = OFFLINE_READ_WAITS_MS[Math.min(nt, OFFLINE_READ_WAITS_MS.length) - 1]!; record.offline = { since: record.offline?.since ?? now().toISOString(), reads: nt }; await save(); say(`${o.stem}: the resume failed for the network (no restart spent); tried again in ${spanWords(w / 1000)} (try ${nt}).`); await waitFor(stretch(w), signal); if (signal.aborted) break; cur = { o, bytes, mode: "from-start", partial: false }; continue; } resumeFailed.add(o.stem); } else { say(`${cur.o.part.stem} cannot be resumed in place (${st.why}).`); noResumeWhy = st.why; resumeFailed.add(cur.o.stem); } } // DESIGN-4 2 — THE FIRST FALLBACK IS A FRESH FROM-START PART (a new // stem) wherever from-start still reaches the start: YouTube, its // start known and under 119 h (the proof's rule). The earlier part // stays (a copy); the fresh whole covers it at the landing. A // catching-up fresh part re-arms the insurance (onMainStart). Live // edge plus recovery only when it cannot, or it wrote nothing. if (fromStart && separate && deps.freshFromStart !== false && !freshFailedLast && startProvable(false) && (await roomFor(`fresh part ${restarts.count + 1}`))) { restarts.count += 1; restarts.at.push(now().toISOString()); const k = restarts.count; const sm = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; const age = Number.isFinite(sm) ? (now().getTime() - sm) / 1000 : null; say( `Restart ${k} (${why}): ${noResumeWhy ? `no resume in place (${noResumeWhy}) — ` : ""}a FRESH part from the stream's start (a new stem: YouTube serves it whole under 119 h)` + (age !== null ? `; the stream is ${spanWords(age)} old: about ${spanWords(age)} of it is fetched again from fragment 0 before the live edge` : "") + `; the earlier part is kept for the landing.`, ); const o = await ytdlpPart(plan.url, `ytdlp-f${k}`, "from-start", `fresh ${k} (${why}); `, { restart: k, noWait: true, onStart: onMainStart("from-start", true), onLine: onMainLine, }); o.part.fresh = k; await save(); const bytes = await bytesOf(o.stem); if (bytes > 0) { emptyInRow = 0; const partial = separate && !o.signalled ? (await missingStreamOf(o.stem)) !== null : false; cur = { o, bytes, mode: "from-start", partial }; continue; } freshFailedLast = true; if (o.signalled && signal.aborted) break; say(`The fresh from-start part wrote nothing (${lastErrorLine(recentOutput(o)) ?? `yt-dlp exit ${o.exitCode ?? "null"}`}): the live-edge fallback.`); } // NO SPAN OF A LIVE STREAM IN NO PART WHILE IT CAN BE FETCHED (REVIEW-3 // 3.1): where do the kept parts reach on the stream's clock? From-start // parts from 0, live-edge parts from their recorder's start; their // union from 0. Short of now by more than max(180 s, 1 %) — the live // edge's own lag (up to a minute) plus the minute the exit and the read // take, which a whole-stream download is not spent on — the span is // said lost-so-far (loud) and a from-start recovery runs beside the // live-edge recorder until a from-start part reaches it. if (fromStart) { const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; const elapsed = Number.isFinite(startMs) ? (now().getTime() - startMs) / 1000 : null; const spans: [number, number][] = []; for (const p of parts) { const sec = await secondsOf(p.stem); if (sec <= 0) continue; if (p.part.fromStart && !p.part.index0) spans.push([0, sec]); else if (Number.isFinite(startMs)) { const at0 = (Date.parse(p.part.startedAt) - startMs) / 1000; spans.push([at0, at0 + sec]); } } spans.sort((a, b) => a[0] - b[0]); // A flat 180 s (REVIEW-4 3.1): a fraction of a long stream would hide minutes. const tol = LIVE_GAP_TOLERANCE_SECONDS; let reach = 0; for (const [a, b] of spans) if (a <= reach + tol) reach = Math.max(reach, b); // A from-start part whose own progress (frag N/M) showed it caught // up has no gap behind it, whatever the clock says (REVIEW-4 2.2). const caughtUp = caughtUpStem !== null && caughtUpStem === cur.o.stem; if (!caughtUp && (elapsed === null || elapsed - reach > tol)) { const hm = (x: number) => `${Math.floor(x / 3600)}:${String(Math.floor((x % 3600) / 60)).padStart(2, "0")}`; record.lost = { fromSeconds: Math.round(reach), toSeconds: elapsed !== null ? Math.round(elapsed) : null }; if (elapsed !== null) gapTarget = Math.max(gapTarget ?? 0, elapsed); await save(); say( elapsed !== null ? `Hours ${hm(reach)}-${hm(elapsed)} of the stream are in no part yet: fetched again from its start beside the live edge.` : "The stream's start time is not known: what lies before the live edge may be in no part; fetched again from its start beside the live edge.", ); if (!recoveryRunning && (record.startRecovery?.tries ?? 0) < LIVE_RECOVERY_MAX_TRIES) { recoveryRunning = true; const prev = recovery; // Its first try only once the live-edge restart holds bytes, then a // jittered pause (REVIEW-4 1.1/6.1): never two extractions at once, // and an ended stream's empty live edge starts none. recovery = (async () => { await prev; const stop = AbortSignal.any([signal, recoveryStop.signal]); while (!stop.aborted && !(edgeRestartStem && (await bytesOf(edgeRestartStem)) > 0)) await sleep(deps.insurancePollMs ?? 5_000, stop); if (stop.aborted) { recoveryRunning = false; if (record.startRecovery && record.startRecovery.state !== "recovered") record.startRecovery.state = "stopped"; else record.startRecovery ??= { tries: 0, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS, state: "stopped" }; await save(); return; } await waitFor(stretch(LIVE_INSURANCE_DELAY_MS), stop); await recoverStart(index0, { gap: true }); })(); } else if (!recoveryRunning) { // No try is left: the new span stays loud (REVIEW-4 2.3). record.startRecovery = { ...(record.startRecovery ?? { tries: LIVE_RECOVERY_MAX_TRIES, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS }), state: "exhausted" }; await save(); } } } restarts.count += 1; restarts.at.push(now().toISOString()); const k = restarts.count; say(`Restart ${k} (${why}, the stream ${state === "live" ? "is live" : "state unknown"}): a new part from the live edge; the earlier part is kept for the landing.`); const o = await ytdlpPart(plan.url, `ytdlp-r${k}`, "now", `restart ${k} (${why}); `, { restart: k, noWait: true, onStart: (stem) => { edgeRestartStem = stem; onMainStart("now", true)(stem); }, onLine: onMainLine, }); const bytes = await bytesOf(o.stem); const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false; if (bytes === 0 && !o.signalled) { // REVIEW-6 5: while the state cannot be read (offline), an empty // recorder is not evidence that the stream ended. if (state !== "unknown") emptyInRow += 1; else say(`Restart ${k} recorded nothing while the stream's state cannot be read (offline?): not counted toward "taken as ended".`); const last = recentOutput(o); o.part.error = lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; o.part.failureClass = liveFailureClass(last); await save(); if (classifyAttempt({ ...o, stderrTail: last, bytes }) === "argv") { await refuse("the live-edge command cannot work (argv)", `Restart ${k} recorded nothing (${o.part.error}): the command cannot work — the stream may be live and NOT recorded; the row needs a person.`); break; } } else if (bytes > 0) emptyInRow = 0; cur = { o, bytes, mode: "now", partial }; } // REVIEW-8 4: the outage is over with the recording, whatever ended it. if (record.offline) { delete record.offline; await save(); } // The main recording is over. The insurance: with the stream read as // ended, it is stopped after a grace (its live edge is at the end too); // otherwise it runs on by itself — it may be the only recorder left. mainDoneCtl.abort(); if (insurance) { if (endRead && !endedByRefusal && !insureStop.signal.aborted) { graceTimer = setTimeout(() => { insuranceStopFor ??= "ended"; insureStop.abort(); }, deps.insuranceGraceMs ?? LIVE_INSURANCE_END_GRACE_MS); } await Promise.all(insuranceLoops); } if (caughtUpTimer) clearTimeout(caughtUpTimer); if (graceTimer) clearTimeout(graceTimer); // The live-edge recording is over: a recovery try still WAITING stops // (the stream ended, or the live edge failed); one in flight is awaited, // never stopped — it may hold the only copy. edgeDone = true; recoveryStop.abort(); if (recovery) await recovery; if (lastReason !== null && record.failureClass !== undefined) { const tries = (record.attempts ?? 0) - (record.startRecovery?.tries ?? 0); const split = fromStartFailures && edgeFailures ? ` (${fromStartFailures} from its start, ${edgeFailures} from the live edge)` : ""; attemptsSummary = `${tries} attempt${tries === 1 ? "" : "s"}${split}: ${lastReason}`; } } else pathB = true; if (pathB && !signal.aborted) { const sniffed = await (deps.sniff ?? sniffLivePlaylist)({ paths, pageUrl: plan.url, onLog, signal }); if (!sniffed.ok || sniffed.playlists.length === 0) { throw new Error(`the page gave no playlist: ${sniffed.error ?? "none requested"}`); } const chosen = await choosePlaylist(sniffed.playlists, maxHeight, getText, signal); if (!chosen) throw new Error("the page's playlists could not be read"); const file = partPath("browser"); const part = begin("browser", chosen, file, fromStart); await save(); const o = await runRecorder({ bin: paths.ffmpegBin, args: ffmpegLiveArgs({ url: chosen, output: file, fromStart, userAgent: liveFetchUserAgent(), referer: "https://rumble.com/" }), cwd: channelDir, onLog, signal, label: "browser", }); finish(part, `ffmpeg exit ${o.exitCode ?? "null"}${o.signalled ? " (stopped)" : ""}`); await save(); } } // 3. The stream is over (or the recording was stopped): land the longest. // A stop by the editor's shutdown is `interrupted` (it needs a person: the // stream may still be live), a person's Cancel `cancelled`. const stopped = signal.aborted ? stopOf(deps) : null; const cancelled = stopped !== null; const landSignal = new AbortController().signal; // (Read already when the restarts asked whether the stream is still live.) if (!endRead) { try { await refresh(); } catch (err) { say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`); } } const endMeta = await readMeta(videoDir); // DESIGN-5 3/4: does the platform's LAST word say the stream is over? Not // over (is_live, upcoming, a read that failed, a record with no state): no // landing now is "the whole stream", nothing reusable goes, and the row says // it landed while live. Over: was_live / post_live / not_live, or a refusal // as private or removed confirmed by the second read. const lsEnd = typeof endMeta?.live_status === "string" ? endMeta.live_status : null; const stillLive = !endedByRefusal && !(lsEnd === "was_live" || lsEnd === "post_live" || lsEnd === "not_live"); const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s, { strict: true })); const at = (n: string) => path.join(slugStore, n); // Every part on disk now — this run's and an earlier run's — by its stem. // WHAT THE STORE HOLDS for this id, failing CLOSED: a pointer that does not // read, a stored file that cannot be reached, or a source-media file no // pointer names is "stored, not proven" — never an empty store. const storeState = async (): Promise<{ kind: "empty" } | { kind: "stored"; path: string } | { kind: "unknown"; why: string }> => { const pointerFile = savedVideoPointerPath(videoDir); const pst = await stat(pointerFile).then( () => "there" as const, (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? ("absent" as const) : ("error" as const)), ); if (pst === "error") return { kind: "unknown", why: "the store's pointer cannot be read" }; const pointer = pst === "there" ? await loadSavedVideo(videoDir).catch(() => null) : null; if (pst === "there" && !pointer) return { kind: "unknown", why: "the store's pointer does not read" }; if (pointer) { const sp = savedVideoPath(pointer); const st = await stat(sp).then( (x) => (x.isFile() ? ("file" as const) : ("other" as const)), (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? ("absent" as const) : ("error" as const)), ); if (st === "file") return { kind: "stored", path: sp }; if (st !== "absent") return { kind: "unknown", why: `the stored file ${path.basename(sp)} cannot be reached` }; } const names = await readdir(storeDir).then( (x) => x, (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? [] : null), ); if (names === null) return { kind: "unknown", why: "the store's folder cannot be read" }; const sm = names.find((n) => n.startsWith("source-media.")); return sm ? { kind: "unknown", why: `${sm} is in the store with no pointer naming it (a landing stopped between the file and its record?) — ` + "compare it with the staged parts and land or remove it by hand; until then nothing of this stream lands", } : { kind: "empty" }; }; // With a container stored, no file of a part is removed before the landing // decides (the zero-byte files, a fragments-only group's state). const storeHeld = (await storeState()).kind !== "empty"; const groups = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); const partOf = new Map(parts.map((p) => [p.stem, p.part])); // video: it holds a picture; merged: record-live merged it from separate // streams here (its length is the longer stream's). type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles; video: boolean | null; merged: boolean }; const candidates: Candidate[] = []; const unlandable: string[] = []; const unlandableGroups: { group: LivePartFiles; why: string; part?: LivePart }[] = []; const empty: LivePartFiles[] = []; // DESIGN-3: at an editor shutdown a part that can be resumed is not landed // (a landing would merge its streams and end its state): it waits in // staging, as it is, for the boot's restart to resume it. const waitsForResume = new Set(); if (stopped?.by === "shutdown") { for (const g of groups) if ((await resumeStateOf(g.stem)).ok) waitsForResume.add(g.stem); // REVIEW-5 note 4: with a part waiting the run is not over — NOTHING // lands at this shutdown; every part waits for the restart's landing. if (waitsForResume.size) { for (const g of groups) waitsForResume.add(g.stem); say(`A part waits to be resumed: nothing lands at this shutdown; all ${groups.length} part(s) stay in staging for the restart.`); } } // A part an earlier run left waiting (its row's awaitingResume) that this // run did not resume is RELEASED (REVIEW-5 B3): no later resume comes for it // (the boot pass restarts only the newest row), so it is an ordinary part // of this landing — merged, landed or kept by the rules, never left as the // only copy in staging. Only a run itself stopped by a shutdown leaves it // waiting (above), listed on its own row for the next boot. if (stopped?.by !== "shutdown") { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); for (const r of rows.filter((x) => x.id === id && x.startedAt !== record.startedAt && x.awaitingResume?.length)) { say(`${r.awaitingResume!.join(", ")}: left waiting by the run of ${r.startedAt}, not resumed — landed by the rules with this run's parts.`); await patchLiveRecordingRow(paths, req.slug, id, r.startedAt, (x) => { if (!x.awaitingResume?.length) return false; delete x.awaitingResume; }).catch((e: Error) => say(`That row could not be updated (${e.message}).`)); } } for (const g of groups) { const part = partOf.get(g.stem); if (waitsForResume.has(g.stem)) { (record.awaitingResume ??= []).push(g.stem); say(`${g.stem}: kept as it is, for the restart (resumed in place when it can be, else landed by its rules).`); continue; } let got: ResolvedPart | null = null; try { got = await resolvePart(g, slugStore, { probe: (f) => probe(f, landSignal), merge: (a) => merge(a, landSignal), say }); } catch (err) { unlandable.push(`${g.stem}: ${(err as Error).message}`); unlandableGroups.push({ group: g, why: (err as Error).message, ...(part ? { part } : {}) }); } if (part) { part.bytes = 0; for (const f of [...g.finished, ...g.streams]) part.bytes += await sizeOf(at(f)); part.seconds = got && !("error" in got) ? got.seconds : null; if (got && !("error" in got) && got.merged) part.merged = true; } if (got && "error" in got) { unlandable.push(`${g.stem}: ${got.error}`); unlandableGroups.push({ group: g, why: got.error, ...(part ? { part } : {}) }); } else if (got) { // null: the probe failed — not known, so never "contained" (REVIEW-LF-2 4). const pv = await probe(got.file, landSignal).catch(() => null); const video = pv ? Boolean(pv.videoCodec) : null; candidates.push({ file: got.file, seconds: got.seconds, group: g, video, merged: got.merged === true, ...(part ? { part } : {}) }); } else { empty.push(g); if (!storeHeld) for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true }); } } for (const u of unlandable) say(`Not landable: ${u}`); summary.parts = record.parts.map((p) => ({ method: p.method, seconds: p.seconds ?? null, fromStart: p.fromStart })); // WHAT STAYS ON DISK. A part that holds captured media and is not known to // be inside the landed file is never removed: it is kept in staging and // listed (record.keptParts, the channel's row), needing a person. const kept: KeptPart[] = []; const keep = async (g: LivePartFiles, why: string, o: { seconds?: number | null; part?: LivePart; extra?: string[] } = {}) => { const names = [...new Set([...g.finished, ...g.streams, ...g.scratch, ...(o.extra ?? []).map((f) => path.basename(f))])]; const files: { name: string; bytes: number }[] = []; for (const name of names) { const b = await sizeOf(at(name)); if (b > 0) files.push({ name, bytes: b }); } if (!files.length) return; kept.push({ stem: g.stem, files, bytes: files.reduce((n, f) => n + f.bytes, 0), seconds: o.seconds ?? null, fromStart: o.part ? o.part.fromStart : null, run: o.part ? "this" : "earlier", why, }); }; // Every part that is not the landed one, and why it would be kept. // video: what the candidate holds (undefined: not a candidate, not probed). type Other = { group: LivePartFiles; why: string; seconds?: number | null; part?: LivePart; extra?: string[]; video?: boolean | null }; const others: Other[] = []; for (const u of unlandableGroups) others.push({ group: u.group, why: `not landable as it is: ${u.why}`, ...(u.part ? { part: u.part } : {}) }); for (const g of empty) { // Fragments a recorder left hold media too; yt-dlp's resume state does not. if (!storeHeld) for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true }); const part = partOf.get(g.stem); others.push({ group: g, why: "fragments a recorder left, not landable as they are", ...(part ? { part } : {}) }); } const removed: RemovedPart[] = []; // DECIDED BEFORE THE LANDING, DONE AFTER IT: a part is removed only once the // landed file is in the store (landMediaFile returned and the stored file is // there with its size). A landing that fails removes nothing. const toRemove: { group: LivePartFiles; why: string; extra: string[]; o: Other }[] = []; const removeGroup = async (g: LivePartFiles, why: string, extra: string[] = []) => { let bytes = 0; for (const f of [...new Set([...extra.map((e) => path.basename(e)), ...g.finished, ...g.streams, ...g.scratch])]) { bytes += await sizeOf(at(f)); await rm(at(f), { force: true }); } if (bytes > 0) removed.push({ stem: g.stem, bytes, why }); }; const sayKept = () => { for (const k of kept) { say(`Kept, not landed: ${k.stem} (${formatBytes(k.bytes)}, ${k.files.length} file${k.files.length === 1 ? "" : "s"}) — ${k.why}.`); } if (kept.length) say(`${kept.length} part${kept.length === 1 ? " is" : "s are"} kept in staging, listed in pnpm ops get live-recordings ${req.slug}/${id}; nothing removes them.`); for (const r of removed) say(`Removed: ${r.stem} (${formatBytes(r.bytes)}) — ${r.why}.`); }; if (candidates.length === 0) { for (const o of others) await keep(o.group, o.why, o); const error = [ unlandable.length ? `nothing landable was recorded (${unlandable.join("; ")})` : null, attemptsSummary ? `${unlandable.length ? "" : "nothing was recorded — "}${attemptsSummary}` : null, ] .filter(Boolean) .join(" — ") || "nothing was recorded"; record.status = stopped?.status ?? "failed"; if (stopped) record.stoppedBy = stopped.by; record.endedAt = now().toISOString(); record.error = error; if (kept.length) record.keptParts = kept; sayKept(); await save(); if (!unlandable.length && !kept.length) await abandon(); await bootLandingDone(false, error); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); if (!cancelled) throw new Error(error); return summary; } candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1)); let best = candidates[0]!; // Inside the landed file without asking how long the stream is: a shorter // part of THIS run, both from the start (both begin where the stream's // record begins). // PROVEN from the start (main's rule): a part marked so when it was // recorded. An index-0 part, the browser path, a recovery try or a // live-edge part, and a part of a row written before the mark are not // proven, whatever `fromStart` says. And never a restart's sibling or a // stalled part (REVIEW-1 1.4 of live-guard-2): those go by coverage only. // (DESIGN-4 3: never a part with a skipped fragment.) const proven = (p: Pick | undefined) => p?.fromStart === true && p.provenStart === true && !(p.skippedFragments && p.skippedFragments.count > 0); const sure = (p: LivePart) => p.restart === undefined && !p.stalled; const contained = (c: Candidate) => c !== best && c.part !== undefined && best.part !== undefined && proven(c.part) && proven(best.part) && sure(c.part) && sure(best.part) && // Same kind only, as per-stream lengths are not known: a picture part // inside a picture part not merged here; an audio-only part only inside // an audio-only one (a part with both may hold less sound than its // container's length, which is its longer stream's). c.video !== null && best.video !== null && ((c.video && best.video && !best.merged) || (!c.video && !best.video)) && c.seconds !== null && best.seconds !== null && c.seconds <= best.seconds; const where = (p?: LivePart) => (p ? (p.fromStart ? "from its start" : "from the live edge") : "by an earlier run"); for (const c of candidates) { say(`part ${path.basename(c.file)}: ${c.seconds !== null ? `${Math.round(c.seconds)} s` : "length unknown"}${c === best ? " — landed" : ""}`); if (c === best) continue; if (contained(c)) { toRemove.push({ group: c.group, why: "a shorter part of this run from its start: inside the landed part", extra: [c.file], o: { group: c.group, why: `recorded ${where(c.part)}, not landed`, seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file] }, }); continue; } others.push({ group: c.group, why: c.part && best.part ? `recorded ${where(c.part)}, the landed part ${where(best.part)}: it may hold time the landed part does not` : `recorded ${where(c.part)}; the landed part was recorded ${where(best.part)}: it may hold time the landed part does not`, seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file], video: c.video, }); } if (separate && !record.missingStream) { const bp = await probe(best.file, landSignal).catch(() => null); if (bp && !bp.videoCodec) record.missingStream = "video"; } // DOES THE LANDED FILE HOLD THE WHOLE STREAM (streamCoverage, the rule that // also decides superseding). Its own record says whether it was from the // start: this run's part, or an earlier run's by the channel's rows (a part // no row names is not known to be). // Proven, not merely marked fromStart (REVIEW-LF-1 1): this run's part, or // an earlier run's by its row. let landedFromStart: boolean | null = best.part ? proven(best.part) : null; if (landedFromStart === null) { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const p = rows.filter((r) => r.id === id).flatMap((r) => r.parts).find((x) => x.stem === best.group.stem); landedFromStart = p ? proven(p) : null; } record.coverage = streamCoverage({ capturedSeconds: best.seconds, endMeta, streamStartedAt: record.streamStartedAt ?? null, lastEndedAt: record.parts.reduce((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null), wholeFromStart: landedFromStart === true && !record.missingStream, }); let cov = record.coverage; // SLICE 5 — PARTS JOINED (controller/liveJoin.ts): the longest does not hold // the stream, and two or more parts with a known place together hold more. // The joined file lands only once PROVEN (its length, its sound at every // join); its parts are removed only after it has landed. Unproven: the // longest lands and the rest are kept, as before. let joinsRecord: Omit | null = null; // WHAT THE STORE ALREADY HOLDS for this id (REVIEW-1 1.2 of live-guard-2): // it is replaced only by a file that holds the whole stream from its start, // or by a proven join that holds it. Its place is known only when the run // that stored it says it landed a part from the start. const STORED = ""; const pointer = await loadSavedVideo(videoDir).catch(() => null); const storedPath = pointer ? savedVideoPath(pointer) : null; const storedSeconds = storedPath && (await stat(storedPath).then((x) => x.isFile(), () => false)) ? ((await probe(storedPath, landSignal).catch(() => null))?.seconds ?? null) : null; const stored = storedPath && storedSeconds !== null ? { file: storedPath, seconds: storedSeconds } : null; let storedInJoin = false; // Never while the run is being stopped (REVIEW-1 1.7): land the longest, // keep the rest; the next run joins. if (!cov.covers && (candidates.length >= 2 || stored) && !record.missingStream && deps.join !== null && !stopped && !signal.aborted) { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const earlier = new Map(rows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); const placed = candidates.flatMap((c) => { const p = c.part ?? earlier.get(c.group.stem); // "From the start" in a join only on proof (main's rule). return p && c.seconds !== null ? [{ c, jp: { stem: c.group.stem, file: c.file, seconds: c.seconds, fromStart: proven(p), startedAt: p.startedAt ?? null } }] : []; }); if (stored) { const by = rows .filter((r) => r.id === id && r.kept === "new" && r.landedPart !== undefined && r.startedAt !== record.startedAt) .sort((a, b) => Date.parse(b.endedAt ?? b.startedAt) - Date.parse(a.endedAt ?? a.startedAt))[0]; const lp = by?.parts[by.landedPart!]; if (proven(lp) && !lp!.restart && !lp!.stalled) { placed.push({ c: null as unknown as Candidate, jp: { stem: STORED, file: stored.file, seconds: stored.seconds, fromStart: true, startedAt: lp.startedAt ?? null } }); } } // The joined file needs as much room again as its parts (staging is the // store's disk). let room = true; if (placed.length >= 2) { let need = 0; for (const x of placed) need += await sizeOf(x.jp.file); const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0); if (free < need + minFree) { room = false; (record.spaceHeld ??= []).push({ what: "the join of the parts", at: now().toISOString(), freeBytes: free }); say(`Not joined: the store's disk has ${formatBytes(free)} free, a join of these parts needs ${formatBytes(need + minFree)}. The longest lands; the rest are kept.`); } } if (placed.length >= 2 && room) { const joinStem = stemPath("joined"); const r = await joinLiveParts({ parts: placed.map((x) => x.jp), streamStartedAt: record.streamStartedAt ?? null, outStem: joinStem, // The cut and the concat are stream copies of hours: the heavy slot, // as the landing's remux. deps: deps.join ?? ffmpegJoinDeps({ ffmpegBin: paths.ffmpegBin, ffprobeBin: paths.ffprobeBin, run: (args) => runFfmpegHeavy(paths, args, landSignal) }, landSignal), say, }).catch((err: Error) => ({ ok: false as const, why: err.message })); if (r.ok) { const inJoin = new Set(r.stems); const gaps = r.joins.filter((j) => j.kind === "gap"); say( `Joined ${r.stems.length} parts into one (${spanWords(r.seconds)}): ` + r.joins .map((j) => j.kind === "overlap" ? `at ${spanWords(j.at)} an overlap of ${spanWords(j.seconds)} found by their sound${j.duplicatedSeconds ? ` (${j.duplicatedSeconds} s heard twice)` : ""}` : `at ${spanWords(j.at)} a GAP of about ${spanWords(j.seconds)} by the clock — not recorded`, ) .join("; ") + ". Each join was checked.", ); // Every joined part is inside the joined file (proven): removed // after it lands. The rest keep the coverage rule below. storedInJoin = inJoin.has(STORED); // (The stored container is replaced by the landing itself, never removed here.) for (const c of placed.filter((x) => x.jp.stem !== STORED).map((x) => x.c).filter((c) => inJoin.has(c.group.stem))) { const i = others.findIndex((o) => o.group.stem === c.group.stem); if (i >= 0) others.splice(i, 1); if (toRemove.some((t) => t.group.stem === c.group.stem)) continue; toRemove.push({ group: c.group, why: "inside the joined file (its length and its sound at each join checked)", extra: [c.file], o: { group: c.group, why: `joined into ${path.basename(r.file)}`, seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file] }, }); } const base = r.segments[0]!; const jp = await probe(r.file, landSignal).catch(() => null); best = { file: r.file, seconds: r.seconds, group: { stem: path.basename(joinStem), finished: [path.basename(r.file)], streams: [], scratch: [] }, video: jp ? Boolean(jp.videoCodec) : null, merged: false, }; landedFromStart = base.streamFromBasis === "start"; record.joins = r.joins; joinsRecord = { seconds: r.seconds, segments: r.segments, joins: r.joins }; const dup = r.joins.reduce((n, j) => n + (j.duplicatedSeconds ?? 0), 0); record.coverage = streamCoverage({ capturedSeconds: Math.round((r.seconds - dup) * 1000) / 1000, endMeta, streamStartedAt: record.streamStartedAt ?? null, lastEndedAt: record.parts.reduce((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null), // A join with a gap never holds the whole stream. wholeFromStart: landedFromStart && gaps.length === 0, }); cov = record.coverage; } else { say(`Not joined: ${r.why}. The longest lands; the rest are kept.`); } } } // (SLICE 2: a from-start try beside the live edge never carries the proof of // start — main's rule — so its landing never "recovers" the start by the // coverage rule: the live-edge part stays and a person decides.) // Covered: every other part of the stream, this run's or an earlier one's, // is inside the landed file, and goes (recorded, with why) — except a part // that may hold the stream's END: one not from the start (a live-edge part, // one no row describes), which goes only when the landed file is from the // start and, on the media's own length, at least the ENDED stream's own // duration less 60 s; never on a coverage by the clock, nor on a live or // unknown-length stream. // Not covered — a live-edge landing, a partial, a stream whose length is // not known — every other part with bytes is kept and needs a person. const placeRows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const placeOf = new Map(placeRows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); const endedDuration = cov.basis === "duration" ? cov.streamSeconds : null; const mayHoldEnd = (o: Other): boolean => { // An audio-only part beside a landed file with a picture: that file's // own sound may be shorter than its length (REVIEW-LF-2 4) — kept. if (o.video === false && best.video !== false) return true; if (o.video === null) return true; const p = o.part ?? placeOf.get(o.group.stem); if (proven(p)) return false; return !(landedFromStart === true && best.seconds !== null && endedDuration !== null && best.seconds >= endedDuration - 60); }; for (const o of others) { if (cov.covers && !mayHoldEnd(o)) { toRemove.push({ group: o.group, why: stillLive ? `inside the landed file, which holds the stream from its start SO FAR (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)} by the clock; the stream still reads live)` : `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`, extra: o.extra ?? [], o, }); } else { await keep(o.group, o.why, o); } } const bestBytes = await sizeOf(best.file); // The landing failed (it threw, or its stored file is not there as it // should be): nothing is removed, and every part with bytes — the one that // was to land included — is kept and listed; the run failed. const landingFailed = async (why: string): Promise => { await keep(best.group, `the landing failed (${why}): not landed`, { seconds: best.seconds, ...(best.part ? { part: best.part } : {}), extra: [best.file], }); for (const r of toRemove) await keep(r.group, `${r.o.why}; kept because the landing failed`, r.o); record.status = "failed"; record.endedAt = now().toISOString(); record.error = `the landing failed: ${why}`; if (kept.length) record.keptParts = kept; sayKept(); await save(); await bootLandingDone(false, `the landing failed: ${why}`); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); throw new Error(record.error); }; // NOTHING LANDED: the store keeps what it holds, and every part — the one // that would have landed, every part meant for removal, a joined file and // its parts — stays, listed, needing a person. Nothing is removed. const notLanded = async (why: string): Promise => { await keep(best.group, `not landed: ${why}`, { seconds: best.seconds, ...(best.part ? { part: best.part } : {}), extra: [best.file] }); for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: nothing was landed`, r.o); record.status = stopped?.status ?? "failed"; if (stopped) record.stoppedBy = stopped.by; record.endedAt = now().toISOString(); record.error = `not landed: ${why}`; if (kept.length) record.keptParts = kept; delete record.joins; sayKept(); await save(); await bootLandingDone(false, `not landed: ${why}`); // The operator's keep marks hold whatever landed (as main did). if (req.doNotClean) { await setDoNotClean(videoDir, true, { by: "live-recording", via: "record-live", ...(opts.jobId ? { jobId: opts.jobId } : {}), ...(req.note ? { note: req.note } : {}), }).catch((e: Error) => say(`"Do not clean" could not be set (${e.message}).`)); } await applyPendingKeep(paths, req.slug, id, onLog, opts.jobId).catch((e: Error) => say(`The pending keep could not be applied (${e.message}).`)); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); if (!cancelled) throw new Error(record.error); return summary; }; // A CONTAINER ALREADY IN THE STORE (an earlier run's landing, a shutdown's // included) is replaced only by a file that holds the whole stream from its // start (the coverage rule), or by a proven join that includes it: "longer" // is not containment. The store read fails closed (main's storeState). const store = await storeState(); if (store.kind === "unknown") { return notLanded(`${store.why}: a container may be stored, and nothing lands over it unproven`); } if (store.kind === "stored" && !cov.covers && !storedInJoin) { const storedSeconds = (await probe(store.path, landSignal).catch(() => null))?.seconds ?? null; return notLanded( `the store already holds a recording of this stream (${storedSeconds !== null ? spanWords(storedSeconds) : "length unknown"}), ` + "and this one is not proven to hold it (not the whole stream from its start, nor a join that includes it): the stored one stays", ); } // REVIEW-6 10: a RAW source (a stream file landed as it is, a muxed .ts the // landing remuxes) is copied, not moved: it stays until the stored file is // verified against it. A merged file is moved (its streams are the source). const rawSource = best.group.streams.includes(path.basename(best.file)) || /\.ts$/i.test(best.file); // REVIEW-7 8: a copy needs its size plus the floor free where a rename // needed nothing — checked first, said plainly; everything is kept. if (rawSource) { const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0); // (REVIEW-8 5: the room the landing itself asks — the size plus its 2 GB // margin — not the recorders' 20 GB floor.) const need = bestBytes + LAND_MEDIA_DISK_MARGIN_BYTES; if (free < need) { return notLanded( `${path.basename(best.file)} is landed by a copy (it is kept until the stored file is checked against it), which needs ${formatBytes(need)} free on the store's disk; it has ${formatBytes(free)} — everything is kept, free some space and Record again or land it by hand`, ); } } let landed: Awaited>; try { landed = await landMediaFile({ paths, slug: req.slug, channelConfig: opts.channelConfig, videoId: id, sourcePath: best.file, via: "record-live", move: !rawSource, url: plan.url, note: req.note ?? `a live recording (${best.part?.method ?? "an earlier run's part"})`, onLog, signal: landSignal, ...(deps.land ? { deps: deps.land } : {}), }); } catch (err) { return landingFailed((err as Error).message); } { const st = landed.container ? await stat(landed.container).catch(() => null) : null; const sizeOk = st?.isFile() && st.size > 0 && (landed.kept !== "new" || landed.finalized !== "copied" || st.size === bestBytes); if (!sizeOk) { await landingFailed( st ? `the stored file is ${st.size} bytes, the part ${bestBytes}` : `the stored file ${landed.container ?? "(none)"} is not there`, ); } } // The landing kept the store's own container: nothing of this run was // stored, so nothing is removed. if (landed.kept !== "new") { return notLanded(`the store holds a recording as long or longer (${spanWords(landed.existingSeconds ?? 0)}); this one may hold time it does not`); } // DESIGN-4 4 — LANDED AS "NOT YET VERIFIED": the landed file is in the // store; the stream files it was merged from, and every part meant for // removal, stay until it is verified (after the hand-off, below) — never // the other order. The landed file in staging itself was moved or copied. if (!rawSource) await rm(best.file, { force: true }); const mergedFrom = best.group.streams.filter((f) => at(f) !== best.file); const verifyAgainst: string[] = []; for (const f of mergedFrom) if ((await sizeOf(at(f))) > 0) verifyAgainst.push(at(f)); if (rawSource && !verifyAgainst.length) verifyAgainst.push(best.file); record.verification = { state: "pending", at: now().toISOString(), ...(verifyAgainst.length ? { against: verifyAgainst.map((f) => path.basename(f)) } : {}) }; if (stillLive) { const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; const elapsed = Number.isFinite(startMs) ? (now().getTime() - startMs) / 1000 : null; const unrecorded = elapsed !== null && best.seconds !== null ? Math.max(0, Math.round(elapsed - best.seconds)) : null; const why = stopped ? stopped.by === "shutdown" ? "an editor shutdown stopped it" : "it was cancelled" : record.restarts?.refused ? `not restarted: ${record.restarts.refused}` : lsEnd === "is_live" || lsEnd === "is_upcoming" ? "the last read says the stream is live" : "the stream's state could not be read"; record.landedWhileLive = { at: now().toISOString(), unrecordedSeconds: unrecorded, why }; say( `LANDED WHILE THE STREAM IS STILL LIVE (${why}): what is stored is the stream SO FAR, not the whole` + (unrecorded !== null ? ` — about ${spanWords(unrecorded)} of it, by the clock, is in no landed file now` : "") + "; the row needs a person, and nothing reusable is removed until the stream is confirmed done.", ); } const skippedHere = best.part?.skippedFragments ?? (await readStemMarks(slugStore, best.group.stem)).skipped; if (skippedHere && skippedHere.count > 0) { record.skippedFragments = { ...skippedHere }; say(`The landed file holds a HOLE: ${skippedHere.count} fragment(s) yt-dlp could not fetch${skippedHere.positions.length ? ` (positions ${skippedHere.positions.slice(0, 10).join(", ")})` : ""}; the row stays loud.`); } sayKept(); record.landedPart = best.part ? record.parts.indexOf(best.part) : undefined; record.kept = landed.kept; record.status = stopped?.status ?? "landed"; if (stopped) record.stoppedBy = stopped.by; if (kept.length) record.keptParts = kept; record.endedAt = now().toISOString(); if (removed.length) record.removedParts = removed; if (joinsRecord) { await liveJoinsSidecar .write(videoDir, { landedAt: now().toISOString(), container: landed.container, ...joinsRecord }) .catch((e: Error) => say(`live-joins.json could not be written (${e.message}); the joins are on the row.`)); } if (record.missingStream) say(`Landed without its ${record.missingStream} stream: it needs a person.`); if (!record.coverage.covers && record.coverage.streamSeconds !== null && record.coverage.capturedSeconds !== null) { say( `The landed part holds ${spanWords(record.coverage.capturedSeconds)} of a ${spanWords(record.coverage.streamSeconds)} stream ` + `(${record.coverage.basis === "duration" ? "its record's duration" : "by the clock"}): it does not supersede an earlier failure.`, ); } await save(); summary.landed = { kept: landed.kept, seconds: landed.newSeconds, container: landed.container }; summary.status = record.status; await bootLandingDone(true); // 4. Keep it, and hand it on. if (req.doNotClean) { await setDoNotClean(videoDir, true, { by: "live-recording", via: "record-live", ...(opts.jobId ? { jobId: opts.jobId } : {}), ...(req.note ? { note: req.note } : {}), }); say(`Marked "Do not clean"${req.note ? `: ${req.note}` : ""}.`); } await applyPendingKeep(paths, req.slug, id, onLog, opts.jobId); const facts = await (deps.handoff ?? readHandoffFacts)({ slug: req.slug, channelConfig: opts.channelConfig, videoDir, transcribeJob: req.transcribe === true, }); // A SHORTER STORED CONTAINER WAS REPLACED (REVIEW-LF-4 2): a transcript // that ends inside it is that file's, and is asked for again. const redo = landed.existingSeconds !== undefined ? await transcriptOfReplaced(videoDir, landed.existingSeconds, landed.newSeconds ?? null) : null; if (redo) { record.transcriptRedo = { ...redo, at: now().toISOString() }; if (redo.verdict === "shorter") { say(`The transcript is the replaced shorter file's (${redo.why}): the transcription is asked again.`); // `replace`: the job would otherwise find transcript.json and do nothing. const r = opts.requestTranscription ? await opts.requestTranscription(req.slug, id, { replace: true }) : { ok: false, error: "no transcription can be asked from here" }; if (r.ok && r.jobId) record.transcriptRedo.jobId = r.jobId; else record.transcriptRedo.error = r.error ?? "no job"; say(r.ok ? `transcribe-one job ${r.jobId}` : `The transcription was not asked again: ${r.error ?? "no job"} — it needs a person.`); } else { say(`The transcript may be the replaced shorter file's; that cannot be told (${redo.why}): nothing is asked, it needs a person.`); } await save(); } else if (req.transcribe === true && !facts.hasTranscript && opts.requestTranscription) { const r = await opts.requestTranscription(req.slug, id); say(r.ok ? `transcribe-one job ${r.jobId}` : `The transcribe-one job was not queued: ${r.error ?? "no job"}`); } for (const l of transcriptionHandoffLines(facts)) say(l); // 5. DESIGN-4 4 — THE CHECK, then the removals: the landed file against the // stream files it was merged from (packets per track, spans, a hole scan), // or scanned alone. Verified: the streams, their fragments and every part // meant for removal go. Not: nothing goes — kept and listed, the row loud. { const ffprobe = paths.ffprobeBin || "ffprobe"; let verdict: { ok: true } | { ok: false; why: string }; try { // REVIEW-7 4: the tracks' tolerance is max(2 s, 2 fragments) — the // fragment's length from the stream file's kept fragments. const fragmentSeconds = await fragmentSecondsOf(slugStore, mergedFrom, best.seconds); verdict = !landed.container ? { ok: false, why: "there is no stored file to check" } : verifyAgainst.length ? await (deps.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg, { fragmentSeconds })))(landed.container, verifyAgainst, landSignal) : await (deps.verifyScan ?? ((f, sg) => verifyScan(ffprobe, f, sg, { fragmentSeconds })))(landed.container, landSignal); } catch (err) { verdict = { ok: false, why: (err as Error).message }; } // REVIEW-6 3: before any fragment goes, each stream file is exactly its // kept fragments 1..N, byte for byte (they may be the only whole copy). // (REVIEW-7 4: a part whose fragments were dropped for want of disk has // none to compare with — the byte check is skipped, said.) const droppedHere = best.part?.fragmentsDropped ?? (await readStemMarks(slugStore, best.group.stem)).dropped; if (verdict.ok && droppedHere && mergedFrom.length) { say(`The byte check against the kept fragments is skipped: they were dropped for want of disk (${droppedHere}).`); // REVIEW-8 3: the track spans alone are no proof — never "verified whole". verdict = { ok: false, why: `its fragments were dropped for want of disk (${droppedHere}): it cannot be proven whole by its track spans alone` }; } if (verdict.ok && !droppedHere) { for (const f of mergedFrom) { const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message })); if (eq && !eq.ok) { verdict = { ok: false, why: eq.why }; break; } } } const keptBefore = kept.length; if (verdict.ok) { record.verification = { ...record.verification!, state: "verified", at: now().toISOString() }; const gaps = record.joins?.filter((j) => j.kind === "gap").length ?? 0; say( gaps ? `The landed file reads clean, but it was joined with ${gaps} gap(s) by the clock: it is NOT whole.` : stillLive ? `The landed file matches its stream files (${verifyAgainst.length ? verifyAgainst.map((f) => path.basename(f)).join(", ") : "its scan"}) — the stream SO FAR, not the whole: it is still live.` : `The landed file is verified whole (${verifyAgainst.length ? `against ${verifyAgainst.map((f) => path.basename(f)).join(", ")}` : "its scan"}).`, ); // (Nothing on disk is removed for a stream that went private.) if (record.endedBy?.class === "private") for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the stream went private or was removed`, r.o); else for (const r of toRemove) await removeGroup(r.group, r.why, r.extra); // DESIGN-5 7 — ONLY WHEN CONFIRMED DONE (the platform says over, and // verified): the landed part's stream files, state and fragments go. // Still live: they stay, for a restart's reuse. // (A stream that went private or was removed keeps everything on disk: // DESIGN-5 (c) — it may come back, and what is there is all there is.) const wentPrivate = record.endedBy?.class === "private"; if (!stillLive && !wentPrivate) { for (const f of [...best.group.finished, ...best.group.streams, ...best.group.scratch]) await rm(at(f), { force: true }); } else { await keep( best.group, wentPrivate ? "the landed part's stream files, state and fragments, kept: the stream went private or was removed while it was recorded" : "the landed part's stream files, state and fragments, kept for a restart's reuse until the stream is confirmed done", { ...(best.part ? { part: best.part } : {}) }, ); } if (removed.length) record.removedParts = removed; for (const r of removed) say(`Removed: ${r.stem} (${formatBytes(r.bytes)}) — ${r.why}.`); } else if (landSignal.aborted) { record.verification = { ...record.verification!, why: "stopped before the check" }; say("Stopped before the landed file was verified: nothing is removed; the stream files and the other parts stay."); for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the landed file is not yet verified`, r.o); } else { record.verification = { ...record.verification!, state: "failed", at: now().toISOString(), why: verdict.why }; say(`The landed file is NOT verified whole (${verdict.why}): nothing is removed — its stream files and every other part stay, and the row needs a person.`); await keep(best.group, `the files the landed file was made from: it is NOT verified whole (${verdict.why})`, { ...(best.part ? { part: best.part } : {}) }); for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the landed file is not verified whole`, r.o); } if (kept.length > keptBefore) { record.keptParts = kept; for (const k of kept.slice(keptBefore)) say(`Kept, not removed: ${k.stem} (${formatBytes(k.bytes)}) — ${k.why}.`); } await save(); } say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); return summary; } // WAS THE VIDEO'S TRANSCRIPT MADE FROM THE FILE A LANDING JUST REPLACED // (REVIEW-LF-4 2)? Told by the transcript itself, against the two lengths: its // last cue ends inside the replaced container (no later than its length plus // 60 s) while the new container runs on more than 60 s past that — so it // holds nothing of the rest, whichever file it was made from, and is the // short one's. A transcript whose speech runs past the replaced file's end // was not made from it; a new file not longer than the old leaves nothing to // redo; no transcript.json, nothing to redo (the ordinary hand-off asks). // Not tellable — the transcript does not read or holds no cues, or the // replaced length is not known — "unknown": a person decides. export const TRANSCRIPT_REDO_TOLERANCE_SECONDS = 60; export async function transcriptOfReplaced( videoDir: string, replacedSeconds: number | null, newSeconds: number | null, ): Promise | null> { const tol = TRANSCRIPT_REDO_TOLERANCE_SECONDS; let src: string; try { // (Its plain form, else its stored, compressed one.) src = await readStoredText(videoDir, WHISPER_FILENAME, "utf8"); } catch (err) { if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; return { verdict: "unknown", why: `${WHISPER_FILENAME} does not read (${(err as Error).message})`, replacedSeconds, lastCueEnd: null }; } if (replacedSeconds === null || newSeconds === null) { return { verdict: "unknown", why: `the ${replacedSeconds === null ? "replaced" : "new"} file's length is not known`, replacedSeconds, lastCueEnd: null }; } if (newSeconds <= replacedSeconds + tol) return null; let lastCueEnd = 0; try { const cues = parseTranscriptJson(src); if (!cues.length) return { verdict: "unknown", why: `${WHISPER_FILENAME} holds no cues`, replacedSeconds, lastCueEnd: null }; for (const c of cues) if (typeof c.end === "number" && c.end > lastCueEnd) lastCueEnd = c.end; } catch (err) { return { verdict: "unknown", why: `${WHISPER_FILENAME} does not parse (${(err as Error).message})`, replacedSeconds, lastCueEnd: null }; } if (lastCueEnd > replacedSeconds + tol) return null; return { verdict: "shorter", why: `its last cue ends at ${spanWords(lastCueEnd)}, inside the replaced ${spanWords(replacedSeconds)}; the new file is ${spanWords(newSeconds)}`, replacedSeconds, lastCueEnd, }; } // REVIEW-7 4 — THE CHECK, AGAIN: a landing whose verification is `failed` or // `pending` is checked once more against the stream files it was made from // (`pnpm ops live-recording-verify`, the row's Verify button). Verified, and // the stream confirmed done (not landed while live, not gone private), the // stream files, their state and fragments go and the row says so; otherwise // the row says why, and nothing is removed. export async function reverifyLiveLanding(o: { paths: Paths; slug: string; id: string; startedAt?: string; channelConfig: ChannelConfig | null; deps?: { verifyMerged?: RecordLiveDeps["verifyMerged"]; say?: (s: string) => void }; }): Promise<{ ok: true; verified: boolean; why?: string; removed: string[] } | { ok: false; error: string }> { const say = o.deps?.say ?? (() => {}); const rows = (await loadLiveRecordingRows(o.paths, o.slug).catch(() => [])).filter((r) => r.id === o.id); const row = o.startedAt ? rows.find((r) => r.startedAt === o.startedAt) : rows.filter((r) => r.verification && r.verification.state !== "verified").sort((a, b) => b.startedAt.localeCompare(a.startedAt))[0]; if (!row) return { ok: false, error: `${o.slug}/${o.id}: no landing waiting for its check` }; const against = row.verification?.against ?? []; if (!row.verification || row.verification.state === "verified") return { ok: false, error: `${o.slug}/${o.id} (${row.startedAt}): already verified` }; if (!against.length) return { ok: false, error: `${o.slug}/${o.id} (${row.startedAt}): no stream files are named to check against` }; const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id); const pointer = await loadSavedVideo(videoDir).catch(() => null); if (!pointer) return { ok: false, error: `${o.slug}/${o.id}: the store holds no container to check` }; const stored = savedVideoPath(pointer); const slugStore = path.join(savedVideoRoot(o.paths, o.channelConfig), o.slug); const files = against.map((n) => path.join(slugStore, n)); for (const f of files) if (!(await stat(f).catch(() => null))) return { ok: false, error: `${path.basename(f)} is no longer in staging` }; const ffprobe = o.paths.ffprobeBin || "ffprobe"; const fragmentSeconds = await fragmentSecondsOf(slugStore, against, row.coverage?.capturedSeconds ?? null); let verdict: { ok: true } | { ok: false; why: string } = await (o.deps?.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg, { fragmentSeconds })))( stored, files, new AbortController().signal, ).catch((e: Error) => ({ ok: false as const, why: e.message })); const stems = [...new Set(livePartFiles(o.id, against).map((g) => g.stem))]; // REVIEW-8 6: never under a recorder that still writes these files. const locks: StemLock[] = []; for (const st of stems) { const lk = await takeStemLock(slugStore, st); if (!lk.ok) { for (const l of locks) await l.release(); return { ok: false, error: `${o.slug}/${o.id}: ${lk.why} — not checked again while it records` }; } locks.push(lk); } try { const dropped = (await Promise.all(stems.map((st) => readStemMarks(slugStore, st)))).some((m) => m.dropped); if (verdict.ok && dropped) verdict = { ok: false, why: "its fragments were dropped for want of disk: it cannot be proven whole by its track spans alone" }; if (verdict.ok && !dropped) { for (const n of against) { const eq = await streamEqualsFragments(slugStore, n).catch((e: Error) => ({ ok: false as const, why: e.message })); if (eq && !eq.ok) { verdict = { ok: false, why: eq.why }; break; } } } const at = new Date().toISOString(); const confirmedDone = !row.landedWhileLive && row.endedBy?.class !== "private"; const removed: string[] = []; if (verdict.ok && confirmedDone) { const names = await readdir(slugStore).catch(() => [] as string[]); for (const g of livePartFiles(o.id, names).filter((x) => stems.includes(x.stem))) { for (const f of [...g.finished, ...g.streams, ...g.scratch]) { if (f.endsWith(".rec.lock")) continue; // (ours: released below) await rm(path.join(slugStore, f), { force: true }); removed.push(f); } } } const apply = (r: T): T => { r.verification = verdict.ok ? { ...r.verification!, state: "verified", at } : { ...r.verification!, state: "failed", at, why: (verdict as { why: string }).why }; if (removed.length && r.keptParts) r.keptParts = r.keptParts.filter((k) => !stems.includes(k.stem)); if (r.keptParts && !r.keptParts.length) delete r.keptParts; return r; }; await patchLiveRecordingRow(o.paths, o.slug, o.id, row.startedAt, (r) => { apply(r); }); // The record beside the video says the same, when it is this run's. const rec = await liveRecordingSidecar.load(videoDir).catch(() => null); if (rec && rec.startedAt === row.startedAt) await liveRecordingSidecar.write(videoDir, apply(rec)).catch(() => {}); say( verdict.ok ? `${o.slug}/${o.id}: the landed file is verified${confirmedDone ? `; ${removed.length} file(s) of its stream files removed` : " (the stream is not confirmed done: its stream files are kept)"}.` : `${o.slug}/${o.id}: NOT verified (${(verdict as { why: string }).why}); nothing is removed.`, ); return { ok: true, verified: verdict.ok, ...(verdict.ok ? {} : { why: (verdict as { why: string }).why }), removed }; } finally { for (const l of locks) await l.release(); } } // Every refusal before any job; then the job. export async function runRecordLiveJob( opts: Omit, ): Promise { const { paths, request: req } = opts; try { await assertChannelTextReadable(paths, req.slug, opts.channelConfig); } catch (err) { return { ok: false, error: (err as Error).message }; } const plan = await resolveRecordLivePlan(paths, req, opts.channelConfig); if ("error" in plan) return { ok: false, error: plan.error }; const queueKey = recordLiveQueueKey(req.slug, plan.id, plan.kickChannel); const busy = getRegistry() .list() .find((j) => j.queueKey === queueKey && (j.status === "running" || j.status === "queued")); if (busy && !req.dryRun) { return { ok: false, info: true, error: `This stream is already being recorded (job ${busy.id})` }; } return runManagedFunction({ kind: RECORD_LIVE_JOB_KIND, queueKey: req.dryRun ? `${queueKey}:dry-run` : queueKey, paths, channelSlug: req.slug, ...(plan.id ? { videoId: plan.id } : {}), fn: async (onLog, signal, _progress, ctx) => { await recordLiveRun({ ...opts, plan, onLog, signal, jobId: ctx.jobId }); await opts.afterRun?.(); }, }); }