// RECORD A LIVE STREAM FROM ITS START — the pure half (plans/live-capture.md). // // What a live playlist holds, measured 2026-10-22: // // Rumble a DVR stream's master (`rumble.com/live-hls-dvr//playlist.m3u8`) // names `chunklist__i0_DVR.m3u8` variants: 2-second segments from // media sequence 1, as a sliding window of up to ~7200 segments (4 h). // No EXT-X-PLAYLIST-TYPE. A stream under 4 h old is held whole; past // that, the window holds the last 4 h. The non-DVR chunklist holds ~2 // minutes. yt-dlp (the fork's `--live-from-start`, which hands ffmpeg // `-live_start_index 0`) records from the window's first segment. // Kick the channel's live playlist (IVS) holds the last ~30 s. The ongoing // stream's VOD (`kick.com//videos/`, the uuid is the // livestream's id) is an EXT-X-PLAYLIST-TYPE:EVENT playlist of 10 s // segments from sequence 0 — and every fetch of it ENDS with // EXT-X-ENDLIST, a snapshot of the stream so far. ffmpeg reads one // snapshot and stops, which is why a by-hand recording of the VOD // stops at "now" and a second one of the channel was needed for the // rest. Polling the VOD playlist and appending each new segment // records the whole stream into one file. // // Everything here is pure: playlist text in, facts out; options in, argv out. // --- playlists ---------------------------------------------------------------- export type MediaSegment = { // The segment's media sequence number. seq: number; uri: string; duration: number; // EXT-X-PROGRAM-DATE-TIME as epoch ms, when the playlist states one for (or // before) this segment. programDateTimeMs?: number; }; export type MediaPlaylist = { kind: "media"; mediaSequence: number; targetDuration: number | null; // EXT-X-PLAYLIST-TYPE (EVENT, VOD), or null when absent. playlistType: string | null; endList: boolean; segments: MediaSegment[]; totalSeconds: number; }; export type MasterVariant = { url: string; bandwidth: number | null; width: number | null; height: number | null; }; export type MasterPlaylist = { kind: "master"; variants: MasterVariant[] }; function resolveUri(uri: string, baseUrl: string | undefined): string { if (!baseUrl) return uri; try { return new URL(uri, baseUrl).toString(); } catch { return uri; } } function attr(line: string, name: string): string | null { const m = new RegExp(`(?:^|[,:])${name}=("[^"]*"|[^,]*)`).exec(line); if (!m) return null; const v = m[1]!; return v.startsWith('"') ? v.slice(1, -1) : v; } // A playlist's text, read as a master (variants) or a media playlist // (segments). Null when it is not an M3U8 at all. Segment URIs are resolved // against `baseUrl` when given. export function parsePlaylist(text: string, baseUrl?: string): MediaPlaylist | MasterPlaylist | null { const lines = text.split(/\r?\n/).map((l) => l.trim()); if (lines[0] !== "#EXTM3U") return null; if (lines.some((l) => l.startsWith("#EXT-X-STREAM-INF"))) { const variants: MasterVariant[] = []; for (let i = 0; i < lines.length; i++) { const l = lines[i]!; if (!l.startsWith("#EXT-X-STREAM-INF")) continue; const uri = lines.slice(i + 1).find((x) => x !== "" && !x.startsWith("#")); if (!uri) continue; const res = attr(l, "RESOLUTION"); const [w, h] = res ? res.split("x").map((n) => Number(n)) : [NaN, NaN]; const bw = Number(attr(l, "BANDWIDTH")); variants.push({ url: resolveUri(uri, baseUrl), bandwidth: Number.isFinite(bw) && bw > 0 ? bw : null, width: Number.isFinite(w) && w! > 0 ? w! : null, height: Number.isFinite(h) && h! > 0 ? h! : null, }); } return { kind: "master", variants }; } let mediaSequence = 0; let targetDuration: number | null = null; let playlistType: string | null = null; let endList = false; const segments: MediaSegment[] = []; let pendingDuration: number | null = null; let pdt: number | undefined; for (const l of lines) { if (l.startsWith("#EXT-X-MEDIA-SEQUENCE:")) { const n = Number(l.slice("#EXT-X-MEDIA-SEQUENCE:".length)); if (Number.isInteger(n) && n >= 0) mediaSequence = n; } else if (l.startsWith("#EXT-X-TARGETDURATION:")) { const n = Number(l.slice("#EXT-X-TARGETDURATION:".length)); if (Number.isFinite(n) && n > 0) targetDuration = n; } else if (l.startsWith("#EXT-X-PLAYLIST-TYPE:")) { playlistType = l.slice("#EXT-X-PLAYLIST-TYPE:".length).trim().toUpperCase() || null; } else if (l === "#EXT-X-ENDLIST") { endList = true; } else if (l.startsWith("#EXT-X-PROGRAM-DATE-TIME:")) { const t = Date.parse(l.slice("#EXT-X-PROGRAM-DATE-TIME:".length)); if (Number.isFinite(t)) pdt = t; } else if (l.startsWith("#EXTINF:")) { const n = Number.parseFloat(l.slice("#EXTINF:".length)); pendingDuration = Number.isFinite(n) && n >= 0 ? n : 0; } else if (l !== "" && !l.startsWith("#") && pendingDuration !== null) { segments.push({ seq: mediaSequence + segments.length, uri: resolveUri(l, baseUrl), duration: pendingDuration, ...(pdt !== undefined ? { programDateTimeMs: pdt } : {}), }); if (pdt !== undefined) pdt += pendingDuration * 1000; pendingDuration = null; } } const totalSeconds = Math.round(segments.reduce((s, x) => s + x.duration, 0) * 1000) / 1000; return { kind: "media", mediaSequence, targetDuration, playlistType, endList, segments, totalSeconds }; } // The variant to record: the tallest at or under `maxHeight` (null = the // tallest), else the shortest there is. Variants with no height sort last. export function pickVariant(variants: readonly MasterVariant[], maxHeight: number | null): MasterVariant | null { if (variants.length === 0) return null; const tall = (v: MasterVariant) => v.height ?? -1; const sorted = [...variants].sort((a, b) => tall(b) - tall(a) || (b.bandwidth ?? 0) - (a.bandwidth ?? 0)); if (maxHeight === null) return sorted[0]!; return sorted.find((v) => v.height !== null && v.height <= maxHeight) ?? sorted[sorted.length - 1]!; } // The first media sequence number a platform's playlists start a broadcast at. export function firstSequenceOf(platform: string | null | undefined): number { return platform === "rumble" ? 1 : 0; } export type PlaylistReach = { // The playlist still lists the broadcast's first segment. fromStart: boolean; firstSeq: number | null; // Seconds of the broadcast the playlist lists. heldSeconds: number; // Seconds before the playlist's first segment that it no longer lists, when // the program date-time says (the broadcast's start is not known otherwise). missingSeconds: number | null; }; // Does this live playlist reach the broadcast's start? `startedAtMs` (the // stream's start, e.g. the record's `release_timestamp`/`timestamp`) is used // to say how much is missing when it does not. export function playlistReach( p: MediaPlaylist, platform: string | null | undefined, startedAtMs?: number | null, ): PlaylistReach { const first = p.segments[0]; const fromStart = first !== undefined && first.seq <= firstSequenceOf(platform); let missingSeconds: number | null = fromStart ? 0 : null; if (!fromStart && first?.programDateTimeMs !== undefined && startedAtMs) { missingSeconds = Math.max(0, Math.round((first.programDateTimeMs - startedAtMs) / 1000)); } return { fromStart, firstSeq: first?.seq ?? null, heldSeconds: p.totalSeconds, missingSeconds }; } // The segments of `next` not yet taken, given the last sequence number taken // (null: none yet). In order. export function newSegments(next: MediaPlaylist, lastSeq: number | null): MediaSegment[] { return next.segments.filter((s) => lastSeq === null || s.seq > lastSeq); } // --- argv ----------------------------------------------------------------------- // The default quality of a live recording: 720p, the persist presets' usual. export const LIVE_DEFAULT_MAX_HEIGHT = 720; // What yt-dlp says when `--live-from-start` finds no format that can start at // the beginning (a stream without DVR, or an extractor that does not support it). export function liveFromStartUnsupported(stderr: string): boolean { return /--live-from-start is passed, but there are no formats that can be downloaded from the start/i.test(stderr); } // A yt-dlp failure that a page opened in a browser may get past: the platform // refused the extractor's own requests (Cloudflare's 403, the embed JSON), or // the extractor could not read the page. export function extractionRefused(stderr: string): boolean { return /HTTP Error 403|403: Forbidden|Unable to extract|Unsupported URL|cloudflare|Unable to download (?:JSON metadata|webpage)/i.test( stderr, ); } // SEPARATE STREAMS OR ONE. A Rumble or Kick live playlist is muxed (video and // audio in one HLS variant), so one `best` filter picks one. A YouTube live // stream with `--live-from-start` offers ONLY separate DASH video and audio // (measured 2026-10-26 on 5-XlMxKT494: eight formats, the metadata pass picked // `270+234`), and `-f best` failed at once with "Requested format is not // available". A separate-streams recording takes the video at the height asked // for plus the best audio, and yt-dlp merges them when it ends. export const MUXED_LIVE_PLATFORMS: ReadonlySet = new Set(["rumble", "kick"]); // The platforms recorded as separate video + audio unless the request says // otherwise (`separate`). export const SEPARATE_LIVE_PLATFORMS: ReadonlySet = new Set(["youtube"]); export function separateStreamsDefault(platform: string | null | undefined): boolean { return platform != null && SEPARATE_LIVE_PLATFORMS.has(platform); } // The quality selector for a live recording. Muxed: one `best` (at or under // the height). Separate: the video at or under the height plus the best // audio, then a muxed one at that height, then any video plus audio. export function liveFormatSelector(maxHeight: number | null, separate = false): string { if (separate) return maxHeight === null ? "bv*+ba/b" : `bv*[height<=${maxHeight}]+ba/b[height<=${maxHeight}]/bv*+ba/b`; return maxHeight === null ? "best" : `best[height<=${maxHeight}]/best`; } // The containers yt-dlp may merge separate streams into: mp4 when the codecs // fit it (h264/av1 + aac), else mkv. The landing copies either as it is. export const LIVE_MERGE_OUTPUT_FORMAT = "mp4/mkv"; // THE yt-dlp RECORDING (path A). `channelArgs` are the channel's own // (channelExtraArgs: cookies, the platform's args — Rumble's `--impersonate` — // and `ytdlpExtraArgs`). // // Muxed: MPEG-TS written straight to `output` (`--hls-use-mpegts --no-part // --fixup never`): a recording cut short by a cancel or a crash is the same // readable file a finished one is, and the landing (controller/landMedia.ts) // remuxes it to mp4 either way. // // Separate (`separate`): `output` is a STEM, and yt-dlp writes each stream to // `.f.` while it records (`--no-part`: whole fragments // appended, readable at any moment), then merges them into `.` // (LIVE_MERGE_OUTPUT_FORMAT) and removes them. A recording stopped before the // merge leaves the streams, and record-live merges them itself // (livePartFiles, mergeStreamsArgs). export function ytdlpLiveArgs(opts: { url: string; output: string; fromStart: boolean; maxHeight: number | null; channelArgs: readonly string[]; separate?: boolean; // An upcoming stream: wait for it to start, re-asking every 60 s. Never for // a stream that is (or was) live — yt-dlp would wait for the NEXT one. waitForVideo?: boolean; // A resume (DESIGN-3): the format ids already on disk, pinned. format?: string; // DESIGN-4 3: the last resort for a fragment that cannot be fetched — this // one run may SKIP it (the part is then marked, never proven). allowSkip?: boolean; }): string[] { return [ "--ignore-config", "--no-playlist", ...opts.channelArgs, // After the channel's args, so a channel's free text cannot undo them. opts.fromStart ? "--live-from-start" : "--no-live-from-start", ...(opts.waitForVideo ? ["--wait-for-video", "60"] : []), "-f", opts.format ?? liveFormatSelector(opts.maxHeight, opts.separate === true), ...(opts.separate ? ["--merge-output-format", LIVE_MERGE_OUTPUT_FORMAT] : []), // DESIGN-4 4: the stream files outlive yt-dlp's merge, until the editor // has checked the merged file against them. ...(opts.separate ? ["-k"] : []), // DESIGN-4 1, 3: a from-start download keeps every fragment (the byte // accounting a resume rests on), and a fragment that cannot be fetched // ends its stream instead of leaving a hole, retried with a back-off. // (Separate streams only: a muxed recording is ffmpeg's, with no fragments // of yt-dlp's, and its argv stays exactly what it was.) ...(opts.fromStart && opts.separate ? ["--keep-fragments", ...(opts.allowSkip ? ["--skip-unavailable-fragments"] : ["--abort-on-unavailable-fragments"]), "--retry-sleep", "fragment:exp=1:20"] : []), "--hls-use-mpegts", "--no-part", "--fixup", "never", "--no-write-info-json", "--no-write-subs", "--no-write-auto-subs", "--no-write-thumbnail", "--no-write-description", "--no-download-archive", "--no-mtime", "--newline", "-o", opts.separate ? `${opts.output}.%(ext)s` : opts.output, "--", opts.url, ]; } // --- a part's files on disk ----------------------------------------------------- // A recording part is a STEM in the store's slug dir, // `..live-.`, and the files named for it: // finished `.ts` (muxed), `.` (yt-dlp's merge), or // `.merged.` (record-live's own merge) // streams `.f.`: one separate stream, unmerged // scratch yt-dlp's fragments and state (`-Frag`, `.ytdl`, `.part`) // and its merge in progress (`.temp.`) export type LivePartFiles = { stem: string; finished: string[]; streams: string[]; scratch: string[] }; const LIVE_STEM_RE = /^([^.]+)\.([\w-]+)\.(.+)$/; // The parts of record `id` the names (a directory listing) hold, by stem, in // name order. Names that are not a part of `id` are left out. export function livePartFiles(id: string, names: readonly string[]): LivePartFiles[] { const prefix = `.${id}.live-`; const by = new Map(); for (const name of [...names].sort()) { if (!name.startsWith(prefix)) continue; const m = LIVE_STEM_RE.exec(name.slice(prefix.length)); if (!m) continue; const stem = `${prefix}${m[1]}.${m[2]}`; const rest = m[3]!; let g = by.get(stem); if (!g) by.set(stem, (g = { stem, finished: [], streams: [], scratch: [] })); if (/-Frag\d+|\.ytdl$|\.part$|^temp\./i.test(rest)) g.scratch.push(name); else if (/^f[^.]+\.[a-z0-9]+$/i.test(rest)) g.streams.push(name); else if (/^(?:merged\.)?[a-z0-9]+$/i.test(rest)) g.finished.push(name); else g.scratch.push(name); } return [...by.values()]; } // ffmpeg's merge of a video stream and an audio stream, stream-copied: // mp4 (+faststart) when `mp4` (the codecs fit it), else mkv. export function mergeStreamsArgs(opts: { video: string; audio: string; output: string; mp4: boolean }): string[] { return [ "-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", opts.video, "-i", opts.audio, "-map", "0:v:0", "-map", "1:a:0", "-c", "copy", ...(opts.mp4 ? ["-movflags", "+faststart", "-f", "mp4"] : ["-f", "matroska"]), opts.output, ]; } // yt-dlp found no format the selector names. export function formatUnavailable(stderr: string): boolean { return /Requested format is not available/i.test(stderr); } // The HLS demuxer refuses a segment whose URL does not end in a listed media // extension. Rumble's CDN (seen 2026-10-23) serves a stream's segments as byte // ranges of one `.tar` (`…/81j9A.gaa.tar?r_file=media-0.ts&r_range=…`), so the // default list plus `tar` -- not `-extension_picky 0`, which would let a playlist // name any file at all. export const HLS_SEGMENT_EXTENSIONS = "3gp,aac,avi,ac3,eac3,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,vtt,wav,webvtt,cmfv,cmfa,ec3,fmp4,html,tar"; // THE ffmpeg RECORDING (path B): a playlist URL found by the browser, // recorded from its first listed segment (`-live_start_index 0` when // `fromStart`), stream-copied into MPEG-TS. Segment and playlist retries keep // a flaky CDN from ending a four-hour recording. export function ffmpegLiveArgs(opts: { url: string; output: string; fromStart: boolean; userAgent?: string; referer?: string; // A `Cookie:` header value. cookieHeader?: string; }): string[] { const headers: string[] = []; if (opts.referer) headers.push(`Referer: ${opts.referer}`); if (opts.cookieHeader) headers.push(`Cookie: ${opts.cookieHeader}`); return [ "-nostdin", "-hide_banner", "-loglevel", "warning", "-y", ...(opts.userAgent ? ["-user_agent", opts.userAgent] : []), ...(headers.length ? ["-headers", headers.map((h) => `${h}\r\n`).join("")] : []), "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_on_network_error", "1", "-reconnect_delay_max", "30", "-seg_max_retry", "10", "-m3u8_hold_counters", "60", "-allowed_segment_extensions", HLS_SEGMENT_EXTENSIONS, ...(opts.fromStart ? ["-live_start_index", "0"] : []), "-i", opts.url, "-map", "0", "-c", "copy", "-f", "mpegts", opts.output, ]; } // --- the recording's own record (live-recording.json) --------------------------- export const LIVE_RECORDING_FILENAME = "live-recording.json"; // How a part was recorded. // ytdlp yt-dlp (the fork), --live-from-start when asked // browser the playlist found by a browser page, recorded by ffmpeg // vod-poll Kick: the ongoing VOD's EVENT playlist polled, segments appended export type LivePartMethod = "ytdlp" | "browser" | "vod-poll"; export type LivePart = { method: LivePartMethod; // The part's stem in the store's slug dir (livePartFiles): which files on // disk are this part's — what live pre-clip follows while it records. stem?: string; url: string; fromStart: boolean; startedAt: string; endedAt?: string; // Seconds the part holds (ffprobe), once ended. seconds?: number | null; bytes?: number; // Why it ended, or failed. note?: string; // Its separate streams were left unmerged (a cancel, a crash) and merged // by record-live. merged?: boolean; // Which attempt of the run this part was (1-based; liveAttemptSchedule). attempt?: number; // What the recorder said when the part recorded nothing: its last `ERROR:` // line (lastErrorLine), so the reason is in the record, not only the log. error?: string; // What kind of failure that was (liveFailureClass). failureClass?: LiveFailureClass; // The listing's own (controller/liveRecordings.ts), while it records: when // the part's files last grew. Never written to the record. lastGrowthAt?: string; // A separate-streams attempt where one stream wrote bytes and the other // nothing: the stream that is missing ("unknown": the one that wrote could // not be read). missingStream?: MissingStream; // A from-start try beside a live-edge recording (StartRecovery). recovery?: boolean; // The stall watchdog stopped its recorder: its files had not grown for // stallMinutes (LiveRestarts). stalled?: boolean; // A restart of the recording after a stall or a recorder that died while // the stream was live (1-based). restart?: number; // The insurance recorder's part: the live edge, beside a from-start // recording that is catching up (LiveInsurance). insurance?: boolean; // Recorded `--no-live-from-start` with ffmpeg at the playlist's first listed // segment: from the start only if the playlist reaches it. index0?: boolean; // DESIGN-3: how many times its recorder was RESUMED in place (the same // files, yt-dlp's own `.ytdl` state). resumes?: number; // Why the last resume wrote nothing (the fallback followed). resumeError?: string; // DESIGN-4 3: fragments yt-dlp skipped (the last resort, or a gap in the // kept fragment numbers): how many, and which (generator positions, as far // as known). A part with any is never proven, never covers, never resumed // in place, and its row stays loud after the landing. skippedFragments?: { count: number; positions: number[] }; // Fragments that could not be fetched (the abort's error lines). fragmentErrors?: number; // Fragment requests answered "HTTP Error 403: Forbidden" (with a private // or removed state read after them: went-private). fragment403?: number; // DESIGN-4 1: its kept fragments were dropped for want of disk (why): the // recording went on, resumability went. fragmentsDropped?: string; // A fresh from-start part after a stop (DESIGN-4 2), its number. fresh?: number; // REVIEW-7 2: after a resume, a stream file that is not its kept fragments // (why) — the resume may have appended what is not the stream. resumeDamaged?: string; // REVIEW-7 7: why the behind check could not tell how far behind it is. behindUnknown?: string; // DESIGN-5 7: resumed after yt-dlp had finished it (a self-exit): its // state rebuilt at the fragment count the byte equation proves — the // fragments it reused (not fetched again). reused?: { fragments: number; at: string }; // Proven to begin at the stream's start, by what was recorded: a YouTube // `--live-from-start` part (not one fallen to index 0) on a stream under // 120 h old; another platform's // `--live-from-start` only when that run's first playlist read listed the // start; a platform VOD whose poll began at its first segment. A part // without it (index-0, the browser path, a later attempt, rows written // before the mark, a recovery try, a live-edge part) is never taken as // holding the start for a removal or a replacement. A part RESUMED in place // keeps the mark its original run earned (the same file continues). provenStart?: boolean; }; export type MissingStream = "video" | "audio" | "unknown"; // A PART THE LANDING DID NOT LAND AND DID NOT REMOVE. It holds captured media // the landed file is not known to contain (an earlier run's part, a part // recorded from another point of the stream, a part that cannot be landed as // it is): its files stay in the store's staging dir, listed here with their // sizes, until a person decides. Nothing removes them automatically. export type KeptPart = { stem: string; files: { name: string; bytes: number }[]; bytes: number; seconds: number | null; // Null: an earlier run's part (its record is that run's). fromStart: boolean | null; run: "this" | "earlier"; why: string; }; // A part the landing removed, and why (a part inside the landed file: a // shorter part of the same run from its start, or any part when the landed // file holds the whole stream — StreamCoverage). export type RemovedPart = { stem: string; bytes: number; why: string }; // Whether the landed recording holds the whole stream: what supersedes an // earlier failure (lib/liveRecordings-server.ts). `basis` is where the // stream's length came from: the ended stream's own `duration`, else the // clock (the last part's end minus the stream's start, which can only // overstate it). export type StreamCoverage = { capturedSeconds: number | null; streamSeconds: number | null; basis: "duration" | "clock" | null; toleranceSeconds: number; covers: boolean; }; // The span of the stream a recording does NOT hold, in stream seconds: a // fallback to the live edge starts `toSeconds` into the stream (null: the // stream's start is not known). export type LostSpan = { fromSeconds: number; toSeconds: number | null }; // `interrupted`: stopped by an editor shutdown, not by a person (a Cancel is // `cancelled`). export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled" | "interrupted"; export type LiveRecordingRecord = { status: LiveRecordingStatus; url: string; platform: string; fromStart: boolean; // Recorded as separate video + audio streams (the request's `separate`, else // the platform's default). separate?: boolean; startedAt: string; endedAt?: string; parts: LivePart[]; // The part that was landed (its index in `parts`), and what the landing kept. landedPart?: number; kept?: "new" | "existing"; // The playlist's reach when the recording started, when it was read. reach?: PlaylistReach; error?: string; // How many recorder attempts the run made (liveAttemptSchedule). attempts?: number; // From its start kept failing and the run recorded from the live edge: // what it does not hold is `lost`. fallback?: "live-edge"; lost?: LostSpan; // A "must not lose" recording: asked with doNotClean or a note. mustKeep?: boolean; // The job that ran it. jobId?: string; // When the stream started (its record's release_timestamp/timestamp), ISO. streamStartedAt?: string; // The last failed attempt's class (liveFailureClass). failureClass?: LiveFailureClass; // The attempts ended with one of the two streams recording nothing. missingStream?: MissingStream; // Who stopped it, when it was stopped: a person's Cancel, or the editor // shutting down (then the status is `interrupted`). // `crash`: the editor died with it recording (found so at the next boot). stoppedBy?: "operator" | "shutdown" | "crash"; // Parts left on disk, not landed (KeptPart). keptParts?: KeptPart[]; // Parts the landing removed as inside the landed file (RemovedPart). removedParts?: RemovedPart[]; // Once landed: does it hold the whole stream (StreamCoverage). coverage?: StreamCoverage; // After a fallback to the live edge: the from-start tries beside it // (StartRecovery). startRecovery?: StartRecovery; // The recorder restarted after a stall or a death mid-stream (LiveRestarts). restarts?: LiveRestarts; // This run was started by the boot pass after an editor restart, for the // interrupted run that started at this time (its row's startedAt). resumeOf?: string; // The insurance recorder beside the from-start recording (LiveInsurance). insurance?: LiveInsurance; // The platform refused a state read as private/removed (or over), twice a // minute apart, while it was being recorded (REVIEW-4 5.1). endedBy?: { class: LiveFailureClass; message: string; at: string }; // DESIGN-3: parts an editor shutdown stopped with their state kept, waiting // in staging (not landed) for the boot's restart to resume them. awaitingResume?: string[]; // The transcript was the replaced shorter file's (LiveTranscriptRedo). transcriptRedo?: LiveTranscriptRedo; // DESIGN-4 4: the landed file checked against the stream files it was // merged from (or scanned alone) before they, and every part meant for // removal, were removed. pending: landed, not yet verified. verification?: LiveVerification; // The landed file holds skipped fragments (its part's skippedFragments). skippedFragments?: { count: number; positions: number[] }; // DESIGN-5 4: landed while the last state read said the stream is live (or // could not be read): never "the whole stream"; how much of it, by the // clock at that moment, is in no landed file. landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string }; // REVIEW-7 1: the state cannot be read for the network: nothing is started, // the read is made again on a paced wait (since, how many reads). offline?: { since: string; reads: number }; // Spawns that did not start because the store's disk was under the floor // (RECORD_LIVE_MIN_FREE_BYTES): what, when, and how much was free. spaceHeld?: LiveSpaceHeld[]; // The landed file is parts joined into one (controller/liveJoin.ts): where // each join is, and what it is. Also in data//live-joins.json. joins?: LiveJoin[]; }; // --- parts joined into one file (controller/liveJoin.ts) --------------------------- // One join in the joined file: `at` seconds into it. overlap: the two parts // share `seconds` of the stream, found by their sound (basis "content"); // `duplicatedSeconds` are heard twice at the join (the cut starts at a // keyframe). gap: `seconds` of the stream are in NEITHER part, by the clock // (basis "clock", about) — the joined file's timeline after it is not the // stream's (live-joins.json maps it). export type LiveJoin = { at: number; kind: "overlap" | "gap"; seconds: number; duplicatedSeconds?: number; // An overlap: where the next part was asked to start, and where its stream // copy really starts (seconds into that part); duplicatedSeconds is the // difference. cutAt?: number; cutFrom?: number; basis: "content" | "clock"; score?: number; parts: string[]; }; // Where one part is in the joined file and in the stream: the joined file's // [joinedFrom, joinedTo) is the part file's [fileFrom, fileTo), which begins // `streamFrom` seconds into the stream (basis: "start" a from-start part, // "content" found by sound, "clock" by the clock). export type LiveJoinSegment = { stem: string; streamFrom: number; streamFromBasis: "start" | "content" | "clock"; fileFrom: number; fileTo: number; joinedFrom: number; joinedTo: number; }; export const LIVE_JOINS_FILENAME = "live-joins.json"; export type LiveSpaceHeld = { what: string; at: string; freeBytes: number }; export type LiveVerification = { state: "pending" | "verified" | "failed"; at: string; why?: string; against?: string[] }; // A landing that REPLACED a shorter stored container while the video's // transcript does not reach past that container's end (REVIEW-LF-4 2): the // transcript is the short file's, and the transcription is asked again. // "shorter": its last cue ends inside the replaced file's length (within // 60 s) and the new file runs on past it; "unknown": which file it came from // cannot be told (it does not read, holds no cues, or the replaced file's // length is not known) — nothing is asked, a person decides. jobId: the // transcription asked; error: why it was not. export type LiveTranscriptRedo = { verdict: "shorter" | "unknown"; why: string; replacedSeconds: number | null; lastCueEnd: number | null; at: string; jobId?: string; error?: string; }; // data//live-joins.json: the landed container was joined from parts. export type LiveJoinsRecord = { landedAt: string; container: string | null; seconds: number; segments: LiveJoinSegment[]; joins: LiveJoin[]; }; export function coerceLiveJoins(raw: unknown): LiveJoinsRecord | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const r = raw as LiveJoinsRecord; if (!Array.isArray(r.segments) || !Array.isArray(r.joins) || typeof r.seconds !== "number") return null; return r; } // --- the insurance recorder: the live edge while the start catches up ---------- // // A from-start recording of a stream that has run for a while is BEHIND the // live edge for a long time (20 Nov 2026: fragment 4453 of 30299 after ten // minutes). A stream removed in that window loses everything between the // catch-up point and its end. The insurance recorder records the live edge // beside it — its own part, its own recorder — and stops LIVE_INSURANCE_MARGIN_MS // after the from-start recorder has caught up (every stream it reports within // LIVE_CAUGHT_UP_FRAGS fragments of its total), or runs the whole stream // ("whole"). It starts LIVE_INSURANCE_DELAY_MS after the from-start part's // first bytes, so the two extractions are never back to back. Its part lands // only under the landing's rules: removed when the landed file holds the // whole stream, else kept and listed. // // ON by default when the stream is marked keep before or when the recording // starts (doNotClean asked, the record's Do-not-clean marker, a pending // keep); OFF otherwise; the request's `insurance` overrides either way. export const LIVE_CAUGHT_UP_FRAGS = 30; export const LIVE_INSURANCE_DELAY_MS = 60_000; export const LIVE_INSURANCE_MARGIN_MS = 5 * 60_000; // After the main recording ends with the stream read as ended. export const LIVE_INSURANCE_END_GRACE_MS = 2 * 60_000; // Starts of the insurance recorder: the first, after it died early, after a // from-start part showed itself far behind again. Bounded PER HOUR (DESIGN-5 // point 5: ingest pauses must not spend them), and per run. export const LIVE_INSURANCE_MAX_STARTS_PER_HOUR = 3; export const LIVE_INSURANCE_MAX_STARTS = 24; // How far behind the live edge a from-start part must show itself (its first // `frag N/M`: the stream's age × (1 − N/M)) for the insurance to start. export const LIVE_INSURANCE_BEHIND_SECONDS = 10 * 60; // waiting for the from-start part's first bytes (and the pause) // recording it records // caught-up stopped: the from-start recording caught up (+ the margin) // ended its recorder ended (the stream ended, or the grace after it) // stalled the stall watchdog stopped it (older rows) // died it exited (or stalled) before the from-start recording // caught up or the stream ended: started again within // LIVE_INSURANCE_MAX_STARTS // stopped a Cancel or a shutdown, or the run fell back to the live edge // failed it recorded nothing // not-started not needed or not possible: the from-start part never // recorded, the run fell back to the live edge, or it caught // up before the insurance began export type LiveInsuranceState = "waiting" | "recording" | "caught-up" | "ended" | "stalled" | "died" | "stopped" | "failed" | "not-started"; export type LiveInsurance = { mode: "catch-up" | "whole"; // On by the keep-mark default, asked by the request, or started because a // from-start part showed itself far behind (insuranceWhenBehind). by: "default" | "asked" | "behind"; // When each start was made (the hourly bound). startTimes?: string[]; state: LiveInsuranceState; reason?: string; // How many times it was started. starts?: number; }; // Whether the insurance runs, and how: the request's `insurance` (true, false, // "whole") wins; absent, on ("catch-up") exactly when the stream is marked keep. export function insuranceDecision(o: { asked: boolean | "whole" | undefined; keepMarked: boolean }): Pick | null { if (o.asked === false) return null; if (o.asked === "whole") return { mode: "whole", by: "asked" }; if (o.asked === true) return { mode: "catch-up", by: "asked" }; return o.keepMarked ? { mode: "catch-up", by: "default" } : null; } // yt-dlp's fragment progress, `[download] … (frag N/M)`, with the separate // stream's number (`1: …`, `2: …`; "0" for a muxed one). export function parseFragProgress(line: string): { stream: string; frag: number; total: number } | null { const m = /^(?:(\d+):\s*)?\[download\].*\(frag (\d+)\/(\d+)\)/.exec(line.trim()); if (!m) return null; return { stream: m[1] ?? "0", frag: Number(m[2]), total: Number(m[3]) }; } // Caught up: every stream that has reported is within LIVE_CAUGHT_UP_FRAGS of // its total. `feed` answers whether it is now. export function catchUpTracker(): { feed: (line: string) => boolean; reset: () => void; seen: () => boolean } { const by = new Map(); return { feed(line) { const p = parseFragProgress(line); if (!p) return false; by.set(p.stream, { frag: p.frag, total: p.total }); return [...by.values()].every((v) => v.total > 0 && v.frag >= v.total - LIVE_CAUGHT_UP_FRAGS); }, reset() { by.clear(); }, seen: () => by.size > 0, }; } // WHAT THE BOOT PASS DID WITH AN INTERRUPTED RUN (controller/liveRecordingBoot.ts), // on that run's row. Written BEFORE the new run is asked for (`starting`), so // a row is restarted at most once, even if the boot itself dies after. // starting the new run is being asked for // asked a record-live job was queued (jobId) // restarted that job found the stream live and records it // landing the stream had ended; what the earlier run left lands // ended the stream had ended and nothing was left to land // unknown the stream's state could not be read: nothing was started // (never a recording on a guess) — Record again // refused not restarted (reason: a restart loop, a recorder of the last // process still writing, the setting off) // failed the job could not be queued (reason) // landing: the boot's run is landing what the interrupted run left (the // stream ended, gone, or its state not readable); landed / failed: what that // landing did (REVIEW-5 B3: the row says what was done, not what was meant). export type LiveBootRestartState = "starting" | "asked" | "restarted" | "landing" | "landed" | "ended" | "unknown" | "refused" | "failed"; export type LiveBootRestart = { at: string; by: "boot"; state: LiveBootRestartState; jobId?: string; reason?: string }; // --- the stall watchdog and the restarts ------------------------------------------ // // While a recorder runs, its part's files (every one: a merge's temp file is // growth too) are compared every LIVE_WATCH_MS. No growth for stallMinutes // (settings.liveRecording.stallMinutes, default 10) stops THAT recorder // (SIGINT, so its file is finalized); its part stays. A recorder that stalled // with bytes, or exited with bytes while the stream still reads live (two // reads LIVE_RESTART_CONFIRM_MS apart — a stream that has just ended may read // live for a moment), is restarted: one metadata read (the read the job makes // at its end anyway), LIVE_RESTART_WAIT_MS, a new part with its own stem // from the LIVE EDGE (the earlier part holds the past; REVIEW-2 of // live-guard-2). Bounded: LIVE_RESTART_MAX_PER_HOUR in any 60 minutes and // LIVE_RESTART_MAX_PER_RUN in all; past either the run lands what it has and // `refused` needs a person. export const LIVE_WATCH_MS = 60_000; export const LIVE_RESTART_WAIT_MS = 30_000; export const LIVE_RESTART_CONFIRM_MS = 60_000; // Restarts are live-edge recorders (REVIEW-2 of live-guard-2): cheap, so a // flaky connection gets more of them than the whole-stream passes once did. export const LIVE_RESTART_MAX_PER_HOUR = 6; export const LIVE_RESTART_MAX_PER_RUN = 24; export type LiveRestarts = { count: number; // When each restart was made, ISO. at: string[]; // Why no further restart was made though the stream was live. refused?: string; // REVIEW-5 note 3: a bound reached on a stream still live is waited out, // not an end: how many times, and the wait in progress (nothing records // meanwhile — the row says so). waited?: number; waiting?: { until: string; why: string }; }; // How long to wait before one more restart at `nowMs` (REVIEW-5 note 3): the // hour's bound frees when its oldest restart is an hour old; past the run's // bound, at most one an hour. null: no wait. export function restartWaitMs(r: Pick, nowMs: number): { ms: number; why: string } | null { const recent = r.at.map((a) => Date.parse(a)).filter((t) => nowMs - t < 3_600_000).sort((a, b) => a - b); if (recent.length >= LIVE_RESTART_MAX_PER_HOUR) { return { ms: Math.max(1_000, recent[0]! + 3_600_000 - nowMs), why: `${recent.length} restarts in the last hour (at most ${LIVE_RESTART_MAX_PER_HOUR})` }; } if (r.count >= LIVE_RESTART_MAX_PER_RUN && recent.length) { return { ms: Math.max(1_000, recent[recent.length - 1]! + 3_600_000 - nowMs), why: `${r.count} restarts in this run (past ${LIVE_RESTART_MAX_PER_RUN}: at most one an hour)` }; } return null; } // Whether one more restart is allowed at `nowMs`; else the reason. export function restartRefusal(r: Pick, nowMs: number): string | null { if (r.count >= LIVE_RESTART_MAX_PER_RUN) return `${r.count} restarts in this run (at most ${LIVE_RESTART_MAX_PER_RUN})`; const recent = r.at.filter((a) => nowMs - Date.parse(a) < 3_600_000).length; if (recent >= LIVE_RESTART_MAX_PER_HOUR) return `${recent} restarts in the last hour (at most ${LIVE_RESTART_MAX_PER_HOUR})`; return null; } // --- recovering the start beside a live-edge recording ---------------------------- // // A run that fell back to the live edge (its from-start attempts recorded // nothing) tries from its start again BESIDE the live-edge recorder, which is // never touched: every LIVE_RECOVERY_EVERY_MS (stretched by pacing.jitter), one // try at a time, at most LIVE_RECOVERY_MAX_TRIES. YouTube keeps a live stream's // start for days, so a refusal that passes (20 Nov 2026: the same argv worked // hours later) still gets the whole stream. Each failed try costs what the // failed from-start attempt did: one extraction and its probes, at the pace. export const LIVE_RECOVERY_EVERY_MS = 15 * 60_000; export const LIVE_RECOVERY_MAX_TRIES = 8; // waiting the next try is due (or the first) // trying a try records now // recorded a try recorded from its start and the stream ended: the // landing decides whether it holds the whole stream // recovered the landed file is a from-start try and holds the whole stream // gave-up a failure no try can help (ended, private, members, the disk, // the argv, from-its-start unsupported, a second rate limit) // exhausted every try was made // stopped the live-edge recording ended (or a Cancel) before a try // recorded export type StartRecoveryState = "waiting" | "trying" | "recorded" | "recovered" | "gave-up" | "exhausted" | "stopped"; export type StartRecovery = { tries: number; max: number; everyMs: number; state: StartRecoveryState; // The last failed try's reason and class. lastError?: string; failureClass?: LiveFailureClass; }; const LIVE_STATUSES: ReadonlySet = new Set(["recording", "landed", "failed", "cancelled", "interrupted"]); const PART_METHODS: ReadonlySet = new Set(["ytdlp", "browser", "vod-poll"]); export function coerceLiveRecording(raw: unknown): LiveRecordingRecord | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const r = raw as Record; if (typeof r.status !== "string" || !LIVE_STATUSES.has(r.status)) return null; if (typeof r.url !== "string" || typeof r.startedAt !== "string") return null; const parts = Array.isArray(r.parts) ? (r.parts as unknown[]).filter( (p): p is LivePart => !!p && typeof p === "object" && PART_METHODS.has(String((p as LivePart).method)) && typeof (p as LivePart).url === "string" && typeof (p as LivePart).startedAt === "string", ) : []; return { ...(r as LiveRecordingRecord), platform: typeof r.platform === "string" ? r.platform : "unknown", fromStart: r.fromStart === true, parts, }; } // The platforms a recording knows how to follow. Anything else is tried with // yt-dlp's own `--live-from-start` (YouTube, Twitch) and no fallback. export const BROWSER_FALLBACK_PLATFORMS: ReadonlySet = new Set(["rumble"]); // --- attempts: what one recorder run came to, and what is tried next ------------ // // A from-start attempt that records nothing is not the end of a recording // (20 Nov 2026: YouTube answered `--live-from-start`'s HEADs without a // sequence number for ~45 s, yt-dlp said "The downloaded file is empty", and // the same argv seven hours later worked). The run tries again, paced, and // then from the live edge, so that something is captured; each wait is // stretched by pacing.jitter and no attempt is a new kind of request: the // live edge is the `--no-live-from-start` Kick's channel recorder already // makes. // The waits before the 1st, 2nd and 3rd attempt of one mode. export const LIVE_RETRY_WAITS_MS: readonly number[] = [0, 60_000, 180_000]; export type LiveAttemptMode = "from-start" | "live-edge"; // Every attempt a run may make, in order: from its start three times (0, +60, // +180 s), then from the live edge three times (0, +60, +180 s). A run asked // not to start at the start makes only the live-edge three. export function liveAttemptSchedule(fromStart: boolean): { mode: LiveAttemptMode; waitMs: number }[] { const edge = LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "live-edge" as const, waitMs })); if (!fromStart) return edge; return [...LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "from-start" as const, waitMs })), ...edge]; } // WHY AN ATTEMPT RECORDED NOTHING, from what the recorder said (its stderr // tail). The class decides what is tried next and is kept on the part and the // row: // ended the stream is over, not live, or its recording is not // available — not retried // private private, removed, unavailable, the account terminated — // not retried // members members-only, paid, or a login is required — not retried // disk no space left, the store read-only or not writable — not // retried // rate-limited HTTP 429 / "Too Many Requests" / the bot check — ONE more // try after LIVE_RATE_LIMIT_WAIT_MS, then not again // empty "The downloaded file is empty" (20 Nov 2026) — the schedule // network a connection or HTTP 5xx error — the schedule // unknown anything else — the schedule // (A part with bytes, a Cancel, an argv no try can fix and a stream that // cannot start at its start are told apart by classifyAttempt first.) export type LiveFailureClass = | "ended" | "private" | "members" | "disk" | "rate-limited" | "empty" | "network" | "unknown" | "argv" | "unsupported" | "partial" | "stalled" // DESIGN-5: yt-dlp could not refresh the stream's URL ("Cannot find // refreshed url for format …", "Giving up after N retries") — the platform // stopped serving that format (its DVR switched off mid-stream); yt-dlp then // merges and exits 0 while the stream may still be live. | "url-refresh" // DESIGN-5 (c): fragment requests answered 403 Forbidden, then the state // read says the video is private or removed — the platform pulled it while // it was recorded: what is on disk lands, loud, never retried in a loop, // and nothing on disk is removed. | "went-private"; // What yt-dlp says when the stream is over or gone: no attempt can help. export function liveStreamGone(stderr: string): boolean { const c = liveFailureClass(stderr); return c === "ended" || c === "private"; } export function liveFailureClass(stderr: string): LiveFailureClass { const t = stderr; // First: no space is no space, whatever else the tail says. if (/No space left on device|Errno 28\b|Disk quota exceeded|Read-only file system|\[Errno 13\] Permission denied/i.test(t)) return "disk"; if (/Cannot find refreshed url for format/i.test(t)) return "url-refresh"; // Before `members`: the bot check's message also says "use --cookies". // (YouTube's soft block, "This content isn't available, try again later", // is a rate limit too: REVIEW-4 1.3 of live-guard-2.) if (/HTTP Error 429|Too Many Requests|Sign in to confirm you(?:'|’)re not a bot|confirm you(?:'|’)re not a bot|content isn(?:'|’)t available, try again later/i.test(t)) return "rate-limited"; if (/This live event has ended|is no longer live|is not currently live|This live stream recording is not available|live stream has ended/i.test(t)) return "ended"; if (/Private video|This video is private|Video unavailable|This video has been removed|has been terminated|This video is no longer available/i.test(t)) return "private"; if (/Join this channel|available to this channel's members|members-only|members only|requires payment|Sign in to confirm your age|login required|account is required|use --cookies|--cookies-from-browser/i.test(t)) return "members"; if (/The downloaded file is empty/i.test(t)) return "empty"; if (/timed out|Connection reset|Connection refused|Network is unreachable|Temporary failure in name resolution|getaddrinfo|Name or service not known|IncompleteRead|Remote end closed|HTTP Error 5\d\d|Unable to download/i.test(t)) return "network"; return "unknown"; } // The wait before the one more try a rate limit or a bot check gets. export const LIVE_RATE_LIMIT_WAIT_MS = 15 * 60_000; // What one attempt came to. // recorded it wrote media (whatever its exit): never retried here // stopped a Cancel's SIGINT // partial separate streams, and one wrote bytes while the other wrote // nothing: a failed attempt, retried on the schedule // unsupported yt-dlp cannot start this stream at its start (→ index 0) // argv the same argv would fail the same way (no format the // selector names, a URL no extractor takes): not retried // final ended, private, members-only or the disk (liveFailureClass): // not retried // rate-limited 429 or the bot check: one more try after a long wait // nothing it recorded nothing for another reason (empty, network, // unknown — an exit 0 with no bytes too: nothing was recorded, // and the stream may still be live): retried on the schedule export type LiveAttemptClass = "recorded" | "stopped" | "partial" | "unsupported" | "argv" | "final" | "rate-limited" | "nothing"; export function classifyAttempt(o: { exitCode: number | null; signalled: boolean; stderrTail: string; bytes: number; // Separate streams: one of the two wrote nothing (the caller probes). partial?: boolean; }): LiveAttemptClass { if (o.signalled) return "stopped"; if (o.bytes > 0) return o.partial ? "partial" : "recorded"; if (liveFromStartUnsupported(o.stderrTail)) return "unsupported"; if (formatUnavailable(o.stderrTail) || /Unsupported URL/i.test(o.stderrTail)) return "argv"; const c = liveFailureClass(o.stderrTail); if (c === "ended" || c === "private" || c === "members" || c === "disk") return "final"; if (c === "rate-limited") return "rate-limited"; return "nothing"; } // The recorder's last `ERROR:` line (yt-dlp prefixes a separate stream's lines // with its number, `1: ERROR: …`), else its last line; at most 300 characters. export function lastErrorLine(stderr: string): string | null { const lines = stderr .split(/[\r\n]+/) .map((l) => l.trim()) .filter(Boolean); const err = [...lines].reverse().find((l) => /^(?:\d+:\s*)?ERROR:/.test(l)); const line = err ?? lines.at(-1) ?? null; return line ? line.replace(/^\d+:\s*/, "").slice(0, 300) : null; } // "2 h 14 min", "14 min", "40 s". export function spanWords(seconds: number): string { const s = Math.max(0, Math.round(seconds)); if (s < 60) return `${s} s`; const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); return h ? `${h} h ${m} min` : `${m} min`; }