Archilyzer · Source

archilyzer

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

commit 15e239ba42d935eefc70f3f0b8b6ce38ec52c2df
parent bff9f3aa907550a56909fd092a23fa6d27f18a6d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 16:22:04 -0400

Merge lane/live-capture: record-live (a live stream from its start; Kick by its VOD; a Playwright fallback) and import-media (an external file made a transcribed item), one landing, a guard against shorter downloads, pending keep markers

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 4+++-
MENVIRONMENT.md | 1+
MOPERATING.md | 33+++++++++++++++++++++++++++++++++
Acommon/controller/importMedia.ts | 336+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/keepVideosMatching.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/landMedia.test.ts | 320+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/landMedia.ts | 524+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/preparePlayable.ts | 2+-
Acommon/controller/recordLive.test.ts | 380+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/recordLive.ts | 951+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/transcode.ts | 6+++++-
Mcommon/jobs/jobKinds.ts | 36++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 1+
Acommon/lib/liveCapture.test.ts | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/liveCapture.ts | 373+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/mediaImport-server.ts | 20++++++++++++++++++++
Acommon/lib/mediaImport.test.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/mediaImport.ts | 379+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/mediaTier.ts | 4++++
Mcommon/lib/metadataHistory.ts | 3+++
Acommon/lib/pendingKeep-server.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 19+++++++++++++++++++
Mcommon/ytdlp/finalizeAppExtraction.ts | 15+++++++++++++++
Acommon/ytdlp/landedGuard.ts | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/liveSniff.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/_door.test.ts | 3+++
Aeditor/app/api/ops/import-media/route.ts | 28++++++++++++++++++++++++++++
Meditor/app/api/ops/keep-videos/route.ts | 27++++++++++++++++++++++++---
Aeditor/app/api/ops/record-live/route.ts | 23+++++++++++++++++++++++
Meditor/app/channels/[slug]/components/ChannelMediaTools.tsx | 3+++
Meditor/app/channels/[slug]/components/KeepMatchingControl.tsx | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aeditor/app/channels/[slug]/components/LiveMediaTools.tsx | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/CleanupStage.tsx | 3++-
Aeditor/app/channels/[slug]/liveMediaActions.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx | 3+++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 41+++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/fixtures/bin/fake-ffmpeg.mjs | 11+++++++++++
Meditor/e2e/fixtures/bin/fake-ffprobe.mjs | 21+++++++++++++++++++++
Aeditor/e2e/live-capture.spec.ts | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/live-capture.md | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 46+++++++++++++++++++++++++++++++++++++++++++++-
41 files changed, 4848 insertions(+), 10 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -118,6 +118,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `import-archive-org` | import-archive-org imports archive.org media into a channel, as one job on archive.org's queue: {"slug", "item", "files": \[...\] \| "match": "&lt;regex&gt;"} for one item; {"slug", "items": \["&lt;id&gt;" \| {"item", "files"? \| "match"?}, ...\]} for many (a bare id takes "match", else every media original); or {"slug", "query": "&lt;archive.org search&gt;", "limit"?: 100} for the first items a search finds (at most 500). One file at a time, a jittered pause between files and between items; a record already held (on disk, or in the saved-video store) is skipped. "dryRun": true lists each file as held, RESTRICTED (archive.org marks it not for download: a fetch would answer 401/403) or would get, and fetches nothing. A 401/403 skips the rest of its item; three such items in a row, a 429 or three failures in a row stop the job. The log ends with a summary: line; a re-run resumes. | `pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait`<br>`pnpm ops import-archive-org --json '{"slug":"demo-archive","query":"collection:example-collection","dryRun":true}' --wait` | | `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | | | `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(&lt;id&gt;)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | | +| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.&lt;fmt&gt;, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` | +| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/&lt;channel&gt;" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has; the longest part wins. Refused for a stream that is not live. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'` | | `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | | | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | @@ -141,7 +143,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` | | `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | -| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. | | +| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` | | `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. | `pnpm ops persist-videos --file list.json --wait` | | `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -167,6 +167,7 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know |---|---|---|---| | `SITE_ID` | — | Which site a compose or an export build is for. The build stage (`archilyzer publish build <id>`) sets it for its children; `compose site`, `build site` and `deploy site` fall back to it when no id is given. | common/bin/compose-site.ts, export/app/lib/site.ts | | `INSTANCE_MODE` | a site | `hub` makes the export build the hub. Set by `archilyzer build hub`. | export/app/lib/mode.ts, common/lib/archive/contract.ts | +| `DISPLAY` | set by `xvfb-run` | record-live's browser fallback (path B) opens the page HEADED when a display is set — the caller runs it under `xvfb-run -a`, because Rumble's Cloudflare refuses a headless Chromium — and headless otherwise. | common/ytdlp/liveSniff.mjs | | `BUILD_ARCHIVES` | on | `0` skips archive-zip generation for one build (`--skip-archives`). | common/bin/compose-site.ts, common/bin/build-archives.ts | | `REPORTS_ALLOW_MISSING_MEDIA` | off | `1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list. | common/bin/compose-site.ts | | `ARCHIVES_READONLY` | off | `1` inside a docker-mode build container: materialize archives, never write the shared cache. | common/bin/compose-site.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -322,6 +322,39 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150 the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. The video page's Transcribe row says **Transcribe now (workers paused)**. +## Record a live stream; import a file + +```sh +pnpm ops record-live --json '{"slug":"example-rumble","url":"https://rumble.com/v1abcde-a-live-show.html"}' +pnpm ops record-live --json '{"slug":"example-kick","url":"https://kick.com/somechannel","doNotClean":true,"note":"keep"}' +pnpm ops import-media --json '{"slug":"example-rumble","path":"/home/me/Podcasts/v1embed.from-start.mp4.part","url":"https://rumble.com/v1abcde-a-live-show.html","move":true,"dryRun":true}' --wait +pnpm ops import-media --json '{"slug":"example-archive","path":"/mnt/old/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"}}' --wait +pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":"keep"}' +``` + +- `record-live` (the channel page's Media → **Record live**, or a video's Media tools) records until the stream + ends — hours, one job per stream on its own queue — then lands the recording as the video's source. From the + start by default: Rumble's DVR playlist holds a stream's first 4 hours (past that, the last 4), which yt-dlp's + `--live-from-start` reads (the private fork's Rumble support). When Rumble refuses yt-dlp, the page is opened in a + browser under `xvfb-run` for its own playlist and ffmpeg records that. Kick's live playlist holds ~30 s, so on + Kick the stream's VOD is polled from its first segment while the channel's live stream records beside it; the + longer part lands. `job cancel` stops the recorders with SIGINT and lands what they have. A stream that is not + live is refused: download it, or import a recording of it. +- `import-media` (Media → **Import a file**) makes one file from outside the archive a normal transcribed item: + `"url"` makes or refreshes the record from its page (metadata only, under the id the archive keys it by — a + Rumble URL's id, not the embed id in the file name), `"id"` names a record already here, `"meta"` describes one + by hand. A `.part`/`.ts` recording is remuxed `-c copy` to mp4; nothing is re-encoded. It lands only when longer + than a container already saved (`"replace": true` lands it anyway); `"move": true` removes the original once the + copy verifies. Always preview (`"dryRun": true`) first. A directory, a .zip or a .7z goes to attach-media. +- Both land the same way: the saved-video store, `audio.<fmt>`, the channel's `archive` line, `media-import.json` + beside the record (where it came from, what was kept) — and a later sync, refetch or "Persist source video" that + brings a SHORTER copy keeps the landed one (its `challenges`). The transcription lane takes the audio by its + rules, behind any pause; `"transcribe": true` queues a transcribe-one job, also behind the pause. Nothing here + lifts a pause. +- `keep-videos` with `"ids"` marks a held video now and records one not held yet (a live stream) as pending in + `channels/<slug>/pending-keep.json`; it is marked when its record is first written — a download, an import, a + recording. The channel's Cleanup stage → **Keep videos by id** lists the pending ids. + ## Find clips in a recording ```sh diff --git a/common/controller/importMedia.ts b/common/controller/importMedia.ts @@ -0,0 +1,336 @@ +// IMPORT A FILE AS A NORMAL TRANSCRIBED ITEM — `pnpm ops import-media`, the +// channel page's and the video page's "Import a file" (plans/live-capture.md). +// +// A file from outside the archive — a stream recorded by hand, a copy from an +// external archive — becomes a video like any other: a record, its source +// container in the saved-video store, audio.<fmt>, and the channel's pipeline +// from there. Which record: +// +// url the source page. The record is created (or refreshed) by ONE +// metadata-only yt-dlp pass — refreshVideoMetadata, the channel's +// cookies and the platform's pace — under the id the archive names +// it by (`dataDirIdForUrl`: Rumble's URL id, not the embed id the +// metadata carries). A held platform, or one cooling down, refuses +// a new record before any job; an existing one is landed without the +// refresh. +// id a record already here. +// meta a record by hand ({title, date?, duration?, description?}) for a +// file with no source page; its id is `id` when given, else the +// file's name (importIdFromFilename). Never over an existing record. +// +// The landing is landMediaFile's (controller/landMedia.ts), shared with the +// live recording: probe, keep the longer, finalize without re-encoding, +// persist, move only after the verify, audio, archive line, provenance. +// A directory, a .zip or a .7z is not a file: the editor action hands it to +// attach-media's walk (controller/attachMedia.ts) instead. +// +// The job is `import-media` on its own queue (`import-media:<slug>`): a +// multi-GB copy never holds a platform's download queue. `needsMedia`: it +// writes the container and the audio. + +import path from "node:path"; +import { mkdir, readdir, rm, stat } from "node:fs/promises"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import type { ResolvedCookiePolicy } from "../lib/cookiePolicy"; +import { writeJsonAtomic } from "../lib/jsonFile-server"; +import { + importIdFromFilename, + manualRecordInfo, + type ImportMediaRequest, +} from "../lib/mediaImport"; +import { withMetadataHistory } from "../lib/metadataHistory-server"; +import { setDoNotClean } from "../lib/doNotClean-server"; +import { applyPendingKeep } from "../lib/pendingKeep-server"; +import type { Paths } from "../lib/paths"; +import { detectPlatform } from "../lib/platform"; +import { + heldPlatformRefusal, + platformCooldownRemainingMs, + recordDownloadBackoff, + recordPlatformClean, +} from "../jobs/downloadBackoff"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { configForVideoUrl } from "../ytdlp/channelArgs"; +import { dataDirIdForUrl } from "../ytdlp/runYtdlp"; +import { + landMediaFile, + probeMedia, + readHandoffFacts, + transcriptionHandoffLines, + type LandMediaDeps, + type LandMediaResult, +} from "./landMedia"; +import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; + +export const IMPORT_MEDIA_JOB_KIND = "import-media"; +export const IMPORT_MEDIA_RESULT_MARKER = "@@import-media "; + +export function importMediaQueueKey(slug: string): string { + return `import-media:${slug}`; +} + +// A path the action hands to attach-media's walk rather than landing itself. +export function isArchivePath(p: string, isDirectory: boolean): boolean { + return isDirectory || /\.(zip|7z)$/i.test(p); +} + +export type ImportTarget = + | { kind: "url"; id: string; url: string; platform: string; exists: boolean } + | { kind: "id"; id: string } + | { kind: "meta"; id: string }; + +async function isDir(p: string): Promise<boolean> { + return stat(p).then((s) => s.isDirectory(), () => false); +} + +async function hasInfo(videoDir: string): Promise<boolean> { + return stat(path.join(videoDir, "metadata.info.json")).then((s) => s.isFile(), () => false); +} + +// WHICH RECORD, OR WHY NOT — before any job, in the sentences the caller shows. +export async function resolveImportTarget( + paths: Paths, + req: ImportMediaRequest, +): Promise<ImportTarget | { error: string; info?: boolean }> { + const dataDir = path.join(paths.channelsDir, req.slug, "data"); + if (req.url) { + const id = dataDirIdForUrl(req.url); + if (!id) return { error: `No record id can be read from ${req.url}` }; + if (req.id && req.id !== id) { + return { error: `"id" ${req.id} is not the id ${req.url} is archived by (${id}); give one of them` }; + } + const platform = detectPlatform(req.url) ?? "unknown"; + return { kind: "url", id, url: req.url, platform, exists: await hasInfo(path.join(dataDir, id)) }; + } + if (req.meta) { + const id = req.id ?? importIdFromFilename(path.basename(req.path)); + if (await isDir(path.join(dataDir, id))) { + return { + error: `${req.slug} already has a record ${id}: import into it with {"id": "${id}"} and no "meta", or name a new id`, + }; + } + return { kind: "meta", id }; + } + const id = req.id!; + if (!(await isDir(path.join(dataDir, id)))) { + return { error: `${req.slug} has no record ${id}: give the source page as "url", or describe it with "meta"` }; + } + return { kind: "id", id }; +} + +export type ImportMediaJobOpts = { + paths: Paths; + request: ImportMediaRequest; + channelConfig: ChannelConfig; + cookiePolicy: ResolvedCookiePolicy; + // After the landing, when the request asked `transcribe: true`: the editor + // queues the transcribe-one job (held by any pause, as every one is). + requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; + afterRun?: () => void | Promise<void>; + deps?: { + refresh?: RefreshRunner; + land?: LandMediaDeps; + // Test seam: the hand-off's facts (default: the running editor's). + handoff?: typeof readHandoffFacts; + }; +}; + +export type ImportMediaSummary = { + slug: string; + id: string; + dryRun: boolean; + record: "created" | "refreshed" | "existing" | "by-hand" | "would-create" | "would-refresh"; + kept: LandMediaResult["kept"]; + seconds: number | null; + existingSeconds?: number | null; + finalized: LandMediaResult["finalized"]; + audio: LandMediaResult["audio"]; + moved: boolean; + container: string | null; + transcribeJob?: string; +}; + +// THE RUN, without the job around it (the job's `fn`, and the tests'). +export async function importMediaRun( + opts: ImportMediaJobOpts & { target: ImportTarget; onLog: (s: string) => void; signal: AbortSignal }, +): Promise<ImportMediaSummary> { + const { paths, request: req, target, onLog, signal } = opts; + const say = (s: string) => onLog(s.endsWith("\n") ? s : `${s}\n`); + const channelDir = path.join(paths.channelsDir, req.slug); + const videoDir = path.join(channelDir, "data", target.id); + let record: ImportMediaSummary["record"] = "existing"; + say(`Import ${req.path} into ${req.slug}/${target.id}${req.dryRun ? " (dry run: nothing is written)" : ""}`); + + if (target.kind === "url") { + const cfg = configForVideoUrl(opts.channelConfig, target.url); + if (req.dryRun) { + record = target.exists ? "would-refresh" : "would-create"; + say(`Record: ${target.exists ? "refreshed" : "created"} from ${target.url} by one metadata-only pass (not run in a dry run).`); + } else { + const held = await heldPlatformRefusal(target.platform, "The metadata fetch", paths); + const cooling = held ? 0 : await platformCooldownRemainingMs(target.platform, paths); + if ((held || cooling > 0) && target.exists) { + say(`Record: not refreshed — ${held ?? `${target.platform} is cooling down`}. The record on disk stands.`); + } else if (held || cooling > 0) { + throw new Error(held ?? `${target.platform} is in a rate-limit cooldown; import once it lapses`); + } else { + const created = !(await isDir(videoDir)); + await mkdir(videoDir, { recursive: true }); + try { + await refreshVideoMetadata({ + paths, + slug: req.slug, + videoId: target.id, + videoUrl: target.url, + channelConfig: cfg, + cookiePolicy: opts.cookiePolicy, + onLog, + signal, + requestedBy: IMPORT_MEDIA_JOB_KIND, + onPlatformBackoff: () => recordDownloadBackoff(target.platform, paths), + onPlatformClean: () => recordPlatformClean(target.platform, paths), + ...(opts.deps?.refresh ? { run: opts.deps.refresh } : {}), + }); + record = target.exists ? "refreshed" : "created"; + } catch (err) { + // A record this run made and could not fill is not left half-made. + if (created) { + const left = await readdir(videoDir).catch(() => [] as string[]); + if (left.every((n) => n === "metadata.history.json" || n.endsWith(".part"))) { + await rm(videoDir, { recursive: true, force: true }); + } + } + throw err; + } + } + } + } else if (target.kind === "meta") { + record = req.dryRun ? "would-create" : "by-hand"; + const probed = await (opts.deps?.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s)))(req.path, signal); + const info = manualRecordInfo({ + id: target.id, + meta: req.meta!, + seconds: probed?.seconds ?? null, + fileName: path.basename(req.path), + }); + say(`Record: written by hand — "${String(info.title)}"${info.upload_date ? `, ${String(info.upload_date)}` : ""}.`); + if (!req.dryRun) { + await mkdir(videoDir, { recursive: true }); + await withMetadataHistory(videoDir, { by: "import-media", requestedBy: IMPORT_MEDIA_JOB_KIND, onLog }, () => + writeJsonAtomic(path.join(videoDir, "metadata.info.json"), info, { indent: 0, newline: false }), + ); + } + } + + let landed: LandMediaResult; + try { + landed = await landMediaFile({ + paths, + slug: req.slug, + channelConfig: opts.channelConfig, + videoId: target.id, + sourcePath: req.path, + via: "import-media", + ...(req.move ? { move: true } : {}), + ...(req.replace ? { replace: true } : {}), + ...(req.audio === false ? { audio: false } : {}), + ...(target.kind === "url" ? { url: target.url } : {}), + ...(req.note ? { note: req.note } : {}), + ...(req.dryRun ? { dryRun: true } : {}), + // A dry run of a record not made yet has no directory to read. + ...(req.dryRun && record === "would-create" ? { recordMayBeMissing: true } : {}), + onLog, + signal, + ...(opts.deps?.land ? { deps: opts.deps.land } : {}), + }); + } catch (err) { + // A record this run made for a file that did not land is not left behind: + // a data/<id>/ with metadata is what every enumerator reads as "fetched". + if (!req.dryRun && (record === "created" || record === "by-hand")) { + const left = await readdir(videoDir).catch(() => [] as string[]); + if (left.every((n) => n === "metadata.info.json" || n === "metadata.history.json")) { + await rm(videoDir, { recursive: true, force: true }); + say(`The record ${target.id} this import made is removed again (nothing landed).`); + } + } + throw err; + } + + if (req.doNotClean) { + if (!req.dryRun) await setDoNotClean(videoDir, true, req.note); + say(`${req.dryRun ? "Would mark" : "Marked"} "Do not clean"${req.note ? `: ${req.note}` : ""}.`); + } + if (!req.dryRun) await applyPendingKeep(paths, req.slug, target.id, onLog); + + let transcribeJob: string | undefined; + if (!req.dryRun && landed.audio !== "skipped") { + const facts = await (opts.deps?.handoff ?? readHandoffFacts)({ + slug: req.slug, + channelConfig: opts.channelConfig, + videoDir, + transcribeJob: req.transcribe === true, + }); + if (req.transcribe === true && !facts.hasTranscript && opts.requestTranscription) { + const r = await opts.requestTranscription(req.slug, target.id); + if (r.ok && r.jobId) transcribeJob = r.jobId; + else say(`The transcribe-one job was not queued: ${r.error ?? "no job"}`); + } + for (const l of transcriptionHandoffLines(facts)) say(l); + if (transcribeJob) say(`transcribe-one job ${transcribeJob}`); + } + const summary: ImportMediaSummary = { + slug: req.slug, + id: target.id, + dryRun: req.dryRun === true, + record, + kept: landed.kept, + seconds: landed.newSeconds, + ...(landed.existingSeconds !== undefined ? { existingSeconds: landed.existingSeconds } : {}), + finalized: landed.finalized, + audio: landed.audio, + moved: landed.moved, + container: landed.container, + ...(transcribeJob ? { transcribeJob } : {}), + }; + say(`${IMPORT_MEDIA_RESULT_MARKER}${JSON.stringify(summary)}`); + return summary; +} + +// Every refusal before any job; then the job. +export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise<StreamActionResult> { + const { paths, request: req } = opts; + const st = await stat(req.path).catch(() => null); + if (!st) return { ok: false, error: `${req.path} is not there` }; + if (!st.isFile()) return { ok: false, error: `${req.path} is not a file` }; + try { + await assertChannelTextReadable(paths, req.slug, opts.channelConfig); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + const target = await resolveImportTarget(paths, req); + if ("error" in target) return { ok: false, error: target.error, ...(target.info ? { info: true } : {}) }; + if (target.kind === "url" && !target.exists && !req.dryRun) { + const held = await heldPlatformRefusal(target.platform, "The metadata fetch", paths); + if (held) return { ok: false, info: true, error: held }; + const remainingMs = await platformCooldownRemainingMs(target.platform, paths); + if (remainingMs > 0) { + return { + ok: false, + info: true, + error: `${target.platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). Import once it lapses.`, + }; + } + } + return runManagedFunction({ + kind: IMPORT_MEDIA_JOB_KIND, + queueKey: importMediaQueueKey(req.slug), + paths, + channelSlug: req.slug, + videoId: target.id, + fn: async (onLog, signal) => { + await importMediaRun({ ...opts, target, onLog, signal }); + await opts.afterRun?.(); + }, + }); +} diff --git a/common/controller/keepVideosMatching.ts b/common/controller/keepVideosMatching.ts @@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { assertChannelMediaReachable } from "../lib/channelMedia"; import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; +import { addPendingKeep, loadPendingKeep, type PendingKeepEntry } from "../lib/pendingKeep-server"; import { classifyAgainstFilter, compileDownloadFilter, @@ -245,3 +246,63 @@ export async function keepVideosMatching( dryRun, }; } + +// --- by id, including videos not here yet -------------------------------------- + +export type KeepVideosByIdsResult = { + ids: string[]; + // Held, marked by this call (would be, on a dry run). + marked: string[]; + // Held and already marked. + alreadyKept: string[]; + // Not held: recorded as pending by this call (would be, on a dry run). The + // marker is set when the record is first written (lib/pendingKeep-server.ts). + pending: string[]; + // Every pending entry of the channel after this call (before it, on a dry run). + pendingAll: PendingKeepEntry[]; + dryRun: boolean; +}; + +// KEEP THESE IDS. A held one is marked now, as the toggle marks it; one the +// channel does not hold yet becomes a pending entry, applied when the record +// first lands (a download, an import, a live recording). No dir is created. +export async function keepVideosByIds(opts: { + paths: Paths; + channelSlug: string; + ids: readonly string[]; + note?: string; + dryRun?: boolean; +}): Promise<KeepVideosByIdsResult> { + const { paths, channelSlug } = opts; + const dryRun = opts.dryRun === true; + const ids = [...new Set(opts.ids.map((s) => s.trim()).filter(Boolean))]; + if (ids.length === 0) throw new KeepVideosError('"ids" must name at least one video id'); + for (const id of ids) { + if (!/^[\w.-]+$/.test(id) || id === "." || id === "..") throw new KeepVideosError(`"${id}" is not a video id`); + } + if (!(await channelExists(paths, channelSlug))) { + throw new KeepVideosError(`Channel "${channelSlug}" not found`); + } + const config = await readChannelConfig(paths, channelSlug); + await assertChannelMediaReachable(paths, channelSlug, config); + const held = new Set(await listChannelVideoIds(paths, channelSlug)); + const note = opts.note?.trim() || "keep-videos: by id"; + const result: KeepVideosByIdsResult = { ids, marked: [], alreadyKept: [], pending: [], pendingAll: [], dryRun }; + for (const id of ids) { + if (!held.has(id)) { + result.pending.push(id); + continue; + } + const videoDir = path.join(paths.channelsDir, channelSlug, "data", id); + if (await isDoNotClean(videoDir)) result.alreadyKept.push(id); + else { + if (!dryRun) await setDoNotClean(videoDir, true, note); + result.marked.push(id); + } + } + result.pendingAll = + !dryRun && result.pending.length + ? await addPendingKeep(paths, channelSlug, result.pending, note) + : await loadPendingKeep(paths, channelSlug); + return result; +} diff --git a/common/controller/landMedia.test.ts b/common/controller/landMedia.test.ts @@ -0,0 +1,320 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { MediaProbe } from "../lib/mediaImport"; +import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/landMedia.test.ts +// +// The landing import-media and record-live share (controller/landMedia.ts), the +// import job's run, the pending "Do not clean", and the guard that keeps a later +// download from clobbering a longer landed recording. A temp corpus; ffprobe, +// the remux and the audio extraction are stubs that read a fake "media" file +// (`format=<name>;seconds=<n>`), except one case that runs the real ffmpeg. + +const ROOT = await mkdtemp(path.join(tmpdir(), "land-media-")); +const CORPUS = path.join(ROOT, "transcripts"); +const OUTSIDE = path.join(ROOT, "outside"); +process.env.TRANSCRIPTS_DIR = CORPUS; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await mkdir(CORPUS, { recursive: true }); +await mkdir(OUTSIDE, { recursive: true }); +await writeFile(process.env.SETTINGS_FILE, "{}"); + +const { getPaths } = await import("../lib/paths"); +const { landMediaFile, transcriptionHandoffLines } = await import("./landMedia"); +const { importMediaRun, resolveImportTarget } = await import("./importMedia"); +const { mediaImportSidecar } = await import("../lib/mediaImport-server"); +const { loadSavedVideo } = await import("../lib/savedVideo-server"); +const { isDoNotClean } = await import("../lib/doNotClean-server"); +const { addPendingKeep, applyPendingKeep, loadPendingKeep } = await import("../lib/pendingKeep-server"); +const { keepVideosByIds } = await import("./keepVideosMatching"); +const { prepareLandedGuard, settleLandedGuard, landedContainerWins } = await import("../ytdlp/landedGuard"); + +const paths = getPaths(); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const SLUG = "synth-rumble"; +const CONFIG = { handling: "transcribe", url: "https://rumble.com/c/Synth", platform: "rumble", name: "Synth" } as ChannelConfig; +await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true }); +await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); +await mkdir(paths.savedVideosDir, { recursive: true }); + +// A fake media file: its "probe" is its text. +async function fake(name: string, format: string, seconds: number, dir = OUTSIDE): Promise<string> { + const f = path.join(dir, name); + await writeFile(f, `format=${format};seconds=${seconds};${"x".repeat(64)}`); + return f; +} +async function fakeProbe(file: string): Promise<MediaProbe | null> { + const text = await readFile(file, "utf8").catch(() => ""); + const m = /format=([^;]+);seconds=([\d.]+)/.exec(text); + if (!m) return null; + return { formatName: m[1]!, seconds: Number(m[2]), videoCodec: "h264", audioCodec: "aac" }; +} +const remuxed: string[] = []; +const deps = { + probe: fakeProbe, + // The stub "remux": the same bytes, now an mp4. + remux: async (src: string, dest: string) => { + remuxed.push(src); + await writeFile(dest, (await readFile(src, "utf8")).replace(/format=[^;]+/, "format=mov,mp4,m4a")); + }, + transcode: async (o: { videoDir: string; sourcePath: string; fmt: string }) => { + await copyFile(o.sourcePath, path.join(o.videoDir, `audio.${o.fmt}`)); + }, + freeBytes: async () => 1e15, +}; +const signal = new AbortController().signal; +const log: string[] = []; +const onLog = (s: string) => void log.push(s); + +async function record(id: string, meta: Record<string, unknown> = {}): Promise<string> { + const dir = path.join(CORPUS, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: `embed-${id}`, extractor: "RumbleEmbed", title: id, ...meta })); + return dir; +} + +test("a live recording's MPEG-TS lands as an mp4 in the store, with audio, the archive line and provenance", async () => { + const dir = await record("v1live"); + const src = await fake("v1.from-start.mp4.part", "mpegts", 3600); + const r = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v1live", sourcePath: src, via: "import-media", move: true, url: "https://rumble.com/v1live-x.html", onLog, signal, deps }); + assert.equal(r.kept, "new"); + assert.equal(r.finalized, "remuxed"); + assert.equal(r.audio, "extracted"); + assert.equal(r.moved, true); + assert.ok(remuxed.includes(src)); + await assert.rejects(stat(src), "the original is gone once the copy verified"); + const pointer = await loadSavedVideo(dir); + assert.equal(pointer?.file, "source-media.mp4"); + assert.equal(pointer?.keepReason, "pin"); + assert.equal(pointer?.origin?.requestedBy, "import-media"); + assert.ok((await readdir(dir)).includes("audio.mp3")); + const prov = await mediaImportSidecar.load(dir); + assert.equal(prov?.entries[0]?.source.name, "v1.from-start.mp4.part"); + assert.equal(prov?.entries[0]?.kept, "new"); + const archive = await readFile(path.join(CORPUS, "channels", SLUG, "archive"), "utf8"); + assert.match(archive, /^RumbleEmbed embed-v1live$/m); + // No staging left behind. + const slugStore = path.join(paths.savedVideosDir, SLUG); + assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".")), []); +}); + +test("keep the longer: a shorter file is not landed, the store and the original stay", async () => { + const dir = await record("v2"); + const long = await fake("long.mp4", "mov,mp4,m4a", 5000); + await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v2", sourcePath: long, via: "import-media", onLog, signal, deps }); + const short = await fake("short.mp4", "mov,mp4,m4a", 4000); + const r = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v2", sourcePath: short, via: "import-media", move: true, onLog, signal, deps }); + assert.equal(r.kept, "existing"); + assert.equal(r.existingSeconds, 5000); + assert.equal(r.audio, "kept-existing"); + await stat(short); // not moved: nothing was landed from it + const pointer = await loadSavedVideo(dir); + assert.match(await readFile(path.join(pointer!.dir, pointer!.file), "utf8"), /seconds=5000/); + // attach-media's provenance: the directory, the entry, the copied bytes' sha256. + assert.equal(pointer?.origin?.kind, "local-archive"); + assert.equal(pointer?.origin?.entry, "long.mp4"); + assert.match(pointer?.sha256 ?? "", /^[0-9a-f]{64}$/); + assert.equal(pointer?.origin?.sha256, pointer?.sha256); + // replace lands it anyway. + const r2 = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v2", sourcePath: short, via: "import-media", replace: true, onLog, signal, deps }); + assert.equal(r2.kept, "new"); +}); + +test("a dry run writes nothing; an unreadable file and one inside the archive are refused", async () => { + const dir = await record("v3"); + const src = await fake("v3.ts", "mpegts", 100); + const r = await landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v3", sourcePath: src, via: "import-media", move: true, dryRun: true, onLog, signal, deps }); + assert.equal(r.dryRun, true); + assert.equal(await loadSavedVideo(dir), null); + await stat(src); + await writeFile(path.join(OUTSIDE, "junk.mp4"), "not media"); + await assert.rejects( + landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v3", sourcePath: path.join(OUTSIDE, "junk.mp4"), via: "import-media", onLog, signal, deps }), + /ffprobe cannot read/, + ); + const inside = await fake("audio.mp3", "mp3", 10, dir); + await assert.rejects( + landMediaFile({ paths, slug: SLUG, channelConfig: CONFIG, videoId: "v3", sourcePath: inside, via: "import-media", onLog, signal, deps }), + /inside the archive/, + ); +}); + +test("import: a record by hand for a file with no source page, marked Do not clean; never over a record", async () => { + const src = await fake("Old Talk.mkv", "matroska,webm", 900); + const req = { slug: SLUG, path: src, meta: { title: "An old talk", date: "2019-05-01" }, doNotClean: true, note: "keep it" }; + const target = await resolveImportTarget(paths, req); + assert.ok(!("error" in target) && target.kind === "meta" && target.id === "old-talk"); + const s = await importMediaRun({ + paths, + request: req, + channelConfig: CONFIG, + cookiePolicy: { cookies: undefined, mode: "when-required" }, + target: target as never, + onLog, + signal, + deps: { + land: deps, + handoff: async () => ({ workersPaused: true, laneEnabled: true, laneHeld: false, ruleCoversChannel: true, channelPaused: false, hasTranscript: false, transcribeJob: false }), + }, + }); + assert.equal(s.record, "by-hand"); + assert.equal(s.kept, "new"); + const dir = path.join(CORPUS, "channels", SLUG, "data", "old-talk"); + const info = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")); + assert.equal(info.title, "An old talk"); + assert.equal(info.upload_date, "20190501"); + assert.ok(await isDoNotClean(dir)); + assert.ok(log.some((l) => /waits behind the pause/.test(l)), "the hand-off says the pause holds it"); + const again = await resolveImportTarget(paths, req); + assert.match((again as { error: string }).error, /already has a record old-talk/); +}); + +test("import: a record made for a file that does not land is removed again", async () => { + const bad = path.join(OUTSIDE, "Broken Thing.mp4"); + await writeFile(bad, "not media at all"); + const req = { slug: SLUG, path: bad, meta: { title: "Broken" } }; + const target = await resolveImportTarget(paths, req); + await assert.rejects( + importMediaRun({ paths, request: req, channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "when-required" }, target: target as never, onLog, signal, deps: { land: deps } }), + /ffprobe cannot read/, + ); + await assert.rejects(stat(path.join(CORPUS, "channels", SLUG, "data", "broken-thing"))); +}); + +test("import by url: one metadata pass makes the record under the URL id", async () => { + const req = { slug: SLUG, path: await fake("rec.mp4.part", "mpegts", 1200), url: "https://rumble.com/v9abcde-a-stream.html" }; + const target = await resolveImportTarget(paths, req); + assert.ok(!("error" in target) && target.kind === "url" && target.id === "v9abcde" && !target.exists); + const calls: string[][] = []; + const refresh = async (cwd: string, args: string[]): Promise<AttemptOutcome> => { + calls.push(args); + const dir = path.join(cwd, "data", "v9abcde"); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "v8embed", extractor: "RumbleEmbed", title: "A stream", live_status: "was_live" })); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }; + const s = await importMediaRun({ + paths, + request: req, + channelConfig: CONFIG, + cookiePolicy: { cookies: undefined, mode: "when-required" }, + target: target as never, + onLog, + signal, + deps: { refresh, land: deps, handoff: async () => ({ workersPaused: false, laneEnabled: false, laneHeld: false, ruleCoversChannel: false, channelPaused: false, hasTranscript: false, transcribeJob: false }) }, + }); + assert.equal(s.record, "created"); + assert.equal(calls.length, 1); + assert.ok(calls[0]!.includes("--skip-download"), "metadata only"); + assert.ok(calls[0]!.includes("--impersonate"), "Rumble's own args"); + const archive = await readFile(path.join(CORPUS, "channels", SLUG, "archive"), "utf8"); + assert.match(archive, /^RumbleEmbed v8embed$/m); +}); + +test("the store's root: the corpus default is made when missing; an override or a dangling link is refused", async () => { + const { ensureStoreRoot } = await import("./landMedia"); + const { symlink } = await import("node:fs/promises"); + const base = path.join(ROOT, "roots"); + await mkdir(base, { recursive: true }); + const def = path.join(base, "saved-videos"); + await ensureStoreRoot({ savedVideosDir: def }, def, "x"); + assert.ok((await stat(def)).isDirectory()); + await assert.rejects(ensureStoreRoot({ savedVideosDir: def }, path.join(base, "elsewhere"), "nothing landed"), /is not there \(is its drive mounted\?\) — nothing landed/); + const dangling = path.join(base, "moved-store"); + await symlink(path.join(base, "unmounted", "saved-videos"), dangling); + await assert.rejects(ensureStoreRoot({ savedVideosDir: dangling }, dangling, "x"), /is not there/); +}); + +test("the hand-off never lifts a pause, and says what takes the video", () => { + const base = { workersPaused: false, laneEnabled: true, laneHeld: false, ruleCoversChannel: true, channelPaused: false, hasTranscript: false, transcribeJob: false }; + assert.match(transcriptionHandoffLines(base)[0]!, /lane's rules take this channel/); + assert.match(transcriptionHandoffLines({ ...base, laneHeld: true })[0]!, /waits behind the pause \(the transcription lane is held\); nothing here lifts it/); + assert.match(transcriptionHandoffLines({ ...base, ruleCoversChannel: false })[0]!, /does not take this channel/); + assert.match(transcriptionHandoffLines({ ...base, transcribeJob: true, workersPaused: true })[0]!, /transcribe-one job .* workers are paused/); + assert.match(transcriptionHandoffLines({ ...base, hasTranscript: true })[0]!, /already on disk/); +}); + +test("pending keep: an id not held is pending, and marked when its record lands", async () => { + const r = await keepVideosByIds({ paths, channelSlug: SLUG, ids: ["v1live", "vnotyet"], note: "Huck — keep" }); + assert.deepEqual(r.marked, ["v1live"]); + assert.deepEqual(r.pending, ["vnotyet"]); + assert.deepEqual((await loadPendingKeep(paths, SLUG)).map((e) => e.id), ["vnotyet"]); + assert.equal(await applyPendingKeep(paths, SLUG, "vnotyet"), false, "no dir yet: still pending"); + const dir = await record("vnotyet"); + assert.equal(await applyPendingKeep(paths, SLUG, "vnotyet", onLog), true); + assert.ok(await isDoNotClean(dir)); + assert.deepEqual(await loadPendingKeep(paths, SLUG), []); + const dry = await keepVideosByIds({ paths, channelSlug: SLUG, ids: ["vlater"], dryRun: true }); + assert.deepEqual(dry.pending, ["vlater"]); + assert.deepEqual(await loadPendingKeep(paths, SLUG), [], "a dry run records nothing"); + await addPendingKeep(paths, SLUG, ["vlater"], "n"); + assert.equal((await loadPendingKeep(paths, SLUG))[0]?.note, "n"); +}); + +test("a later download shorter than the landed recording does not clobber it; a longer one wins", async () => { + const dir = await record("v1live"); // landed in the first test: audio.mp3 of 3600 s + const measure = async (f: string) => (await fakeProbe(f))?.seconds ?? null; + // Shorter download. + const plan = await prepareLandedGuard(dir, onLog); + assert.deepEqual(plan?.asides, ["audio.mp3"]); + assert.ok((await readdir(dir)).includes("audio.mp3.landed-kept")); + await fake("audio.mp3", "mp3", 3000, dir); + await settleLandedGuard(plan!, { measure }, onLog); + assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=3600/, "the landed audio stays"); + assert.ok(!(await readdir(dir)).includes("audio.mp3.landed-kept")); + // Longer download. + const plan2 = await prepareLandedGuard(dir, onLog); + await fake("audio.mp3", "mp3", 4000, dir); + await settleLandedGuard(plan2!, { measure }, onLog); + assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=4000/); + // No new audio: the landed one comes back. + const plan3 = await prepareLandedGuard(dir, onLog); + await settleLandedGuard(plan3!, { measure }, onLog); + assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=4000/); + const prov = await mediaImportSidecar.load(dir); + assert.deepEqual(prov?.challenges?.map((c) => c.kept), ["landed", "download"]); + // The container: a shorter downloaded one loses. + const newer = await fake("source-media.mp4", "mov,mp4", 100, dir); + assert.equal(await landedContainerWins(dir, newer, { measure }, onLog), true); + // A video that was never landed is an ordinary download. + assert.equal(await prepareLandedGuard(await record("plain"), onLog), null); +}); + +test("the real ffmpeg: an MPEG-TS remuxed with -c copy into an mp4 of the same length", async (t) => { + const ts = path.join(OUTSIDE, "real.ts"); + try { + execFileSync(paths.ffmpegBin, [ + "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=3:size=160x120:rate=10", "-f", "lavfi", "-i", "sine=duration=3", + "-c:v", "libx264", "-c:a", "aac", "-f", "mpegts", ts, + ]); + } catch { + t.skip("no ffmpeg with libx264 here"); + return; + } + await record("vreal"); + const r = await landMediaFile({ + paths: { ...paths, monorepoRoot: ROOT }, + slug: SLUG, + channelConfig: CONFIG, + videoId: "vreal", + sourcePath: ts, + via: "record-live", + move: true, + audio: false, + onLog, + signal, + deps: { freeBytes: async () => 1e15 }, + }); + assert.equal(r.finalized, "remuxed"); + assert.ok(r.container?.endsWith("source-media.mp4")); + assert.ok(Math.abs((r.newSeconds ?? 0) - 3) < 0.5); + const fmt = execFileSync(paths.ffprobeBin, ["-v", "error", "-show_entries", "format=format_name", "-of", "csv=p=0", r.container!]).toString(); + assert.match(fmt, /mp4/); +}); diff --git a/common/controller/landMedia.ts b/common/controller/landMedia.ts @@ -0,0 +1,524 @@ +// LAND ONE FILE AS A VIDEO'S SOURCE — the one landing `import-media` and +// `record-live` share (plans/live-capture.md), so a live recording and an +// imported file end identically. The rules are lib/mediaImport.ts's header; +// this is their I/O: +// +// 1. ffprobe the file — refused when it cannot be read or holds no audio. +// 2. KEEP THE LONGER: over a container already in the store, the new one is +// landed only when it is longer (or `replace`); a shorter one is left +// where it was found, untouched. +// 3. FINALIZE into a staging file beside the store dir, on the store's disk: +// attach-media's hashed copy (copyFileHashed; a rename when `move` and the same disk) or a +// `-c copy` remux through the heavy slot (preparePlayable.ts +// ffmpegRemux). Verified: the bytes for a copy, ffprobe and the length for +// a remux. +// 4. persistSourceVideo — `source-media.<ext>` in the store, the pointer in +// data/<id>/, `keepReason: "pin"` (never pruned), `origin.requestedBy` the +// landing's caller. A replaced container of another name is removed. +// 5. `move`: the original is removed only now, after the verify. +// 6. audio.<fmt> (the channel's format, mp3 by default) extracted from the +// kept container by transcodeAudio — which runs the media tier's hook — +// when there is none, or the one there is shorter than the container. +// 7. The channel's `archive` gains the record's line (a record yt-dlp wrote), +// so a sync does not download it again; `media-import.json` gains the +// entry. +// +// THE PIPELINE TAKES IT FROM THERE: a video with audio and no transcript is +// what the transcription lane draws (held by any pause, never lifted here). +// The caller says so in the log (transcriptionHandoffLines). +// +// GUARDED like attach-media: the store root must exist (an unmounted drive is +// never materialised by a mkdir), the store must not be mid-move +// (assertSavedVideosStoreWritable), and its disk must have the file's size +// plus a margin free. + +import path from "node:path"; +import { appendFile, lstat, mkdir, readFile, readdir, rename, rm, stat } from "node:fs/promises"; +import { copyFileHashed } from "../lib/zipReader"; +import { execa } from "execa"; +import type { AudioFormat, ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import { getFreeBytes } from "../lib/diskSpace"; +import { formatBytes } from "../lib/format"; +import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; +import { removeMediaFile } from "../lib/mediaTier-server"; +import { WHISPER_FILENAME } from "../lib/videoStatus"; +import { + KEEP_LONGER_TOLERANCE_SECONDS, + archiveLineFor, + chooseKept, + finalizeFor, + readProbe, + type MediaImportEntry, + type MediaImportVia, + type MediaProbe, +} from "../lib/mediaImport"; +import { recordMediaImport } from "../lib/mediaImport-server"; +import { savedVideoDir, savedVideoPath, savedVideoRoot, type SavedVideoOrigin } from "../lib/savedVideo"; +import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server"; +import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; +import { ffmpegRemux } from "./preparePlayable"; +import { transcodeAudio } from "./transcode"; + +// Free space the store's disk keeps beyond the file (attach-media's margin). +export const LAND_MEDIA_DISK_MARGIN_BYTES = 2 * 1024 ** 3; + +export type LandMediaDeps = { + probe?: (file: string, signal?: AbortSignal) => Promise<MediaProbe | null>; + remux?: (src: string, dest: string, args: string[], signal?: AbortSignal) => Promise<void>; + transcode?: (opts: { + videoDir: string; + sourcePath: string; + sourceFilename: string; + fmt: AudioFormat; + onLog: (s: string) => void; + signal: AbortSignal; + }) => Promise<void>; + freeBytes?: (dir: string) => Promise<number>; + now?: () => Date; +}; + +export type LandMediaOpts = { + paths: Paths; + slug: string; + channelConfig: ChannelConfig; + videoId: string; + // The file to land (absolute). + sourcePath: string; + via: MediaImportVia; + // Remove the original once the landing verifies. A live recording's staging + // file is always moved. + move?: boolean; + replace?: boolean; + // false: the container only, no audio.<fmt>. + audio?: boolean; + // The page the file came from, for the provenance. + url?: string; + // A line for the provenance and the pointer's origin. + note?: string; + dryRun?: boolean; + // A dry run for a record not made yet: no data/<id>/ to read. + recordMayBeMissing?: boolean; + onLog: (s: string) => void; + signal: AbortSignal; + deps?: LandMediaDeps; +}; + +export type LandMediaResult = { + dryRun: boolean; + kept: "new" | "existing"; + newSeconds: number | null; + existingSeconds?: number | null; + finalized: "copied" | "remuxed"; + // The stored container now (absolute), or null on a dry run. + container: string | null; + audio: MediaImportEntry["audio"]; + moved: boolean; + lines: string[]; +}; + +export async function probeMedia(paths: Pick<Paths, "ffprobeBin">, file: string, signal?: AbortSignal): Promise<MediaProbe | null> { + try { + const r = await execa(paths.ffprobeBin, ["-v", "error", "-show_format", "-show_streams", "-of", "json", file], { + reject: false, + ...(signal ? { cancelSignal: signal } : {}), + }); + if (r.exitCode !== 0) return null; + return readProbe(JSON.parse(String(r.stdout))); + } catch { + return null; + } +} + +async function isDir(p: string): Promise<boolean> { + return stat(p).then((s) => s.isDirectory(), () => false); +} + +// THE STORE'S ROOT, OR WHY NOT. A root that is there is used. The corpus's own +// default (`transcripts/saved-videos`) that was never made is made — one +// directory, beside the corpus — as the first persist would make it. Anything +// else missing is refused: a channel's override root on another drive, or a +// relocated store whose link dangles, is an unmounted drive, and a mkdir there +// would fill the root filesystem. +export async function ensureStoreRoot( + paths: Pick<Paths, "savedVideosDir">, + storeRoot: string, + what: string, +): Promise<void> { + if (await isDir(storeRoot)) return; + const present = await lstat(storeRoot).then(() => true, () => false); + if (!present && path.resolve(storeRoot) === path.resolve(paths.savedVideosDir) && (await isDir(path.dirname(storeRoot)))) { + await mkdir(storeRoot).catch((err: NodeJS.ErrnoException) => { + if (err.code !== "EEXIST") throw err; + }); + return; + } + throw new Error(`the saved-video store ${storeRoot} is not there (is its drive mounted?) — ${what}`); +} + +function within(child: string, parent: string): boolean { + const rel = path.relative(parent, child); + return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel); +} + +async function sameDevice(a: string, b: string): Promise<boolean> { + const [x, y] = await Promise.all([stat(a).catch(() => null), stat(b).catch(() => null)]); + return x !== null && y !== null && x.dev === y.dev; +} + +async function appendArchiveLine(channelDir: string, line: string, onLog: (s: string) => void): Promise<void> { + const file = path.join(channelDir, "archive"); + const have = await readFile(file, "utf8").catch(() => ""); + const lower = line.toLowerCase(); + if (have.split("\n").some((l) => l.trim().toLowerCase() === lower)) return; + await appendFile(file, `${line}\n`); + onLog(`archive: + ${line}`); +} + +async function readInfo(videoDir: string): Promise<Record<string, unknown> | null> { + try { + const v = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")); + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null; + } catch { + return null; + } +} + +// Seconds of the audio file the video holds now, by name: null when none, or +// when it cannot be measured. +async function heldAudio( + videoDir: string, + probe: NonNullable<LandMediaDeps["probe"]>, + signal: AbortSignal, +): Promise<{ name: string; seconds: number | null } | null> { + const entries = await readdir(videoDir).catch(() => [] as string[]); + const name = pickPreferredAudio(entries.filter(isRealAudioFile)); + if (!name) return null; + const p = await probe(path.join(videoDir, name), signal); + return { name, seconds: p?.seconds ?? null }; +} + +export async function landMediaFile(opts: LandMediaOpts): Promise<LandMediaResult> { + const lines: string[] = []; + const say = (s: string) => { + lines.push(s); + opts.onLog(s.endsWith("\n") ? s : `${s}\n`); + }; + const probe = opts.deps?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(opts.paths, f, s)); + const now = opts.deps?.now ?? (() => new Date()); + const channelDir = path.join(opts.paths.channelsDir, opts.slug); + const videoDir = path.join(channelDir, "data", opts.videoId); + const name = path.basename(opts.sourcePath); + + const st = await stat(opts.sourcePath).catch(() => null); + if (!st?.isFile()) throw new Error(`${opts.sourcePath} is not a file`); + if (opts.via === "import-media") { + // A file already in the archive is not imported into it. + for (const root of [opts.paths.channelsDir, savedVideoRoot(opts.paths, opts.channelConfig)]) { + if (within(path.resolve(opts.sourcePath), path.resolve(root))) { + throw new Error(`${opts.sourcePath} is inside the archive (${root}); import a file from outside it`); + } + } + } + const probed = await probe(opts.sourcePath, opts.signal); + if (!probed) throw new Error(`ffprobe cannot read ${opts.sourcePath}: not a media file this can land`); + const fin = finalizeFor(name, probed); + if ("refused" in fin) throw new Error(fin.refused); + if (!(opts.dryRun && opts.recordMayBeMissing) && !(await isDir(videoDir))) { + throw new Error(`${opts.slug}/${opts.videoId} has no record (data/${opts.videoId}/)`); + } + say( + `${name}: ${formatBytes(st.size)}, ${probed.formatName}, ${probed.videoCodec ?? "no video"}/${probed.audioCodec}, ` + + `${probed.seconds !== null ? `${Math.round(probed.seconds)} s` : "length unknown"} — ${fin.action === "copy" ? "stored" : "remuxed"}: ${fin.reason}`, + ); + + // What the store holds now. + const pointer = await loadSavedVideo(videoDir); + let existingSeconds: number | null | undefined; + if (pointer) { + const existingPath = savedVideoPath(pointer); + if (await stat(existingPath).then((s) => s.isFile(), () => false)) { + existingSeconds = (await probe(existingPath, opts.signal))?.seconds ?? null; + } + } + const kept = chooseKept({ newSeconds: probed.seconds, existingSeconds, ...(opts.replace ? { replace: true } : {}) }); + if (existingSeconds !== undefined) { + say( + `The store holds ${pointer!.file} (${existingSeconds !== null ? `${Math.round(existingSeconds)} s` : "length unknown"}): ` + + (kept === "new" + ? opts.replace + ? "replaced (replace)." + : `this one is longer by more than ${KEEP_LONGER_TOLERANCE_SECONDS} s and replaces it.` + : "it is as long or longer and stays; this file is not landed."), + ); + } + + const fmt: AudioFormat = opts.channelConfig.audioFormat ?? "mp3"; + const wantAudio = opts.audio !== false; + const audioNow = wantAudio ? await heldAudio(videoDir, probe, opts.signal) : null; + const keptSeconds = kept === "new" ? probed.seconds : (existingSeconds ?? null); + const extract = + wantAudio && + (audioNow === null || + (kept === "new" && + keptSeconds !== null && + (audioNow.seconds === null || keptSeconds > audioNow.seconds + KEEP_LONGER_TOLERANCE_SECONDS))); + const audio: MediaImportEntry["audio"] = !wantAudio ? "skipped" : extract ? "extracted" : "kept-existing"; + say( + !wantAudio + ? "Audio: not extracted (audio: false)." + : extract + ? `Audio: audio.${fmt} ${audioNow ? `replaces ${audioNow.name} (${audioNow.seconds !== null ? `${Math.round(audioNow.seconds)} s` : "length unknown"})` : "extracted"} from the stored container.` + : `Audio: ${audioNow!.name} stays (${audioNow!.seconds !== null ? `${Math.round(audioNow!.seconds)} s` : "length unknown"}).`, + ); + + const storeRoot = savedVideoRoot(opts.paths, opts.channelConfig); + const storeDir = savedVideoDir(opts.paths, opts.channelConfig, opts.slug, opts.videoId); + if (opts.move && kept === "existing") say(`Not moved: ${opts.sourcePath} stays where it is (nothing was landed from it).`); + + if (opts.dryRun) { + return { + dryRun: true, + kept, + newSeconds: probed.seconds, + ...(existingSeconds !== undefined ? { existingSeconds } : {}), + finalized: fin.action === "copy" ? "copied" : "remuxed", + container: null, + audio, + moved: false, + lines, + }; + } + + let containerPath: string | null = pointer ? savedVideoPath(pointer) : null; + let moved = false; + if (kept === "new") { + await ensureStoreRoot(opts.paths, storeRoot, "nothing landed"); + await assertSavedVideosStoreWritable(opts.paths, storeDir); + const free = await (opts.deps?.freeBytes ?? getFreeBytes)(storeRoot); + if (free < st.size + LAND_MEDIA_DISK_MARGIN_BYTES) { + throw new Error( + `the store's disk has ${formatBytes(free)} free; ${name} needs ${formatBytes(st.size)} plus ${formatBytes(LAND_MEDIA_DISK_MARGIN_BYTES)}`, + ); + } + const slugDir = path.dirname(storeDir); + await mkdir(slugDir, { recursive: true }); + const staging = path.join(slugDir, `.${opts.videoId}.land-${process.pid}.part`); + await rm(staging, { force: true }); + let sha256: string | undefined; + try { + if (fin.action === "copy") { + if (opts.move && (await sameDevice(opts.sourcePath, slugDir))) { + await rename(opts.sourcePath, staging); + moved = true; + say(`Moved ${opts.sourcePath} into the store's staging (same disk).`); + } else { + // attach-media's copy of a directory entry: bytes counted, sha256'd. + const copied = await copyFileHashed(opts.sourcePath, staging, { signal: opts.signal }); + if (copied.bytes !== st.size) { + throw new Error(`the copy of ${name} is ${copied.bytes} bytes, the file ${st.size}`); + } + sha256 = copied.sha256; + } + } else { + const remux = opts.deps?.remux ?? ((s: string, d: string, a: string[], sig?: AbortSignal) => ffmpegRemux(opts.paths, s, d, a, sig)); + say(`Remuxing (stream copy, the heavy slot) …`); + await remux(opts.sourcePath, staging, fin.remuxArgs ?? [], opts.signal); + } + if (opts.signal.aborted) throw new Error("Cancelled"); + const check = await probe(staging, opts.signal); + if (!check) throw new Error(`the landed copy of ${name} cannot be read by ffprobe`); + if ( + probed.seconds !== null && + check.seconds !== null && + Math.abs(check.seconds - probed.seconds) > Math.max(KEEP_LONGER_TOLERANCE_SECONDS, probed.seconds * 0.005) + ) { + throw new Error(`the landed copy is ${Math.round(check.seconds)} s, the file ${Math.round(probed.seconds)} s`); + } + const at = now().toISOString(); + // An imported file carries attach-media's provenance (the directory, the + // entry, the bytes' sha256 when copied — `kind: "local-archive"`), so the + // video page says where it came from the same way; a live recording + // names only who made it. + const origin: SavedVideoOrigin = { + requestedBy: opts.via, + requestedAt: at, + reason: opts.note ?? (opts.via === "record-live" ? "a live recording" : `imported from ${opts.sourcePath}`), + ...(opts.via === "import-media" + ? { + kind: "local-archive" as const, + archive: path.dirname(opts.sourcePath), + entry: name, + attachedAt: at, + ...(sha256 ? { sha256 } : {}), + } + : {}), + }; + const landed = await persistSourceVideo({ + videoDir, + sourceFilename: `source-media.${fin.ext}`, + sourcePath: staging, + storeDir, + keepReason: "pin", + origin, + ...(sha256 ? { sha256 } : {}), + paths: opts.paths, + }); + containerPath = savedVideoPath(landed); + if (pointer && savedVideoPath(pointer) !== containerPath) { + await rm(savedVideoPath(pointer), { force: true }); + say(`The replaced container ${pointer.file} removed.`); + } + say(`Stored ${containerPath} (${formatBytes(landed.bytes)}).`); + } catch (err) { + // A move by rename put the original in staging: put it back. + if (moved) await rename(staging, opts.sourcePath).catch(() => {}); + await rm(staging, { force: true }).catch(() => {}); + throw err; + } + if (opts.move && !moved) { + await rm(opts.sourcePath, { force: true }); + moved = true; + say(`Removed the original ${opts.sourcePath} (the landed copy verified).`); + } + } + + if (extract && containerPath) { + const transcode = + opts.deps?.transcode ?? + ((o: Parameters<NonNullable<LandMediaDeps["transcode"]>>[0]) => + transcodeAudio({ + paths: opts.paths, + videoDir: o.videoDir, + sourceFilename: o.sourceFilename, + sourcePath: o.sourcePath, + targetFormat: o.fmt, + onLog: o.onLog, + signal: o.signal, + })); + await transcode({ + videoDir, + sourcePath: containerPath, + sourceFilename: path.basename(containerPath), + fmt, + onLog: opts.onLog, + signal: opts.signal, + }); + // The shorter audio it replaces, when that had another name. + if (audioNow && audioNow.name !== `audio.${fmt}`) { + await removeMediaFile(videoDir, audioNow.name); + say(`Removed the shorter ${audioNow.name}.`); + } + } + + const info = await readInfo(videoDir); + const line = info ? archiveLineFor(info) : null; + if (line) await appendArchiveLine(channelDir, line, (s) => say(s)); + + const entry: MediaImportEntry = { + at: now().toISOString(), + via: opts.via, + source: { + path: opts.sourcePath, + name, + bytes: st.size, + ...(moved ? { moved: true } : {}), + ...(opts.url ? { url: opts.url } : {}), + }, + finalized: fin.action === "copy" ? "copied" : "remuxed", + container: { + file: containerPath ? path.basename(containerPath) : "", + seconds: kept === "new" ? probed.seconds : (existingSeconds ?? null), + bytes: containerPath ? ((await stat(containerPath).catch(() => null))?.size ?? 0) : 0, + }, + kept, + ...(existingSeconds !== undefined ? { existingSeconds } : {}), + audio, + ...(opts.note ? { note: opts.note } : {}), + }; + await recordMediaImport(videoDir, entry); + return { + dryRun: false, + kept, + newSeconds: probed.seconds, + ...(existingSeconds !== undefined ? { existingSeconds } : {}), + finalized: entry.finalized, + container: containerPath, + audio, + moved, + lines, + }; +} + +// --- the hand-off to the pipeline --------------------------------------------- + +export type HandoffFacts = { + // The worker pool's live pause (never the stored flag: lib/pauseGates.ts). + workersPaused: boolean; + // `autoQueue.transcription`: on, held, and whether a rule names the channel. + laneEnabled: boolean; + laneHeld: boolean; + ruleCoversChannel: boolean; + // The channel's tier for the transcription lane is "paused". + channelPaused: boolean; + // This app's transcript (transcript.json) is on disk already. + hasTranscript: boolean; + // The request asked for a transcribe-one job. + transcribeJob: boolean; +}; + +// WHAT HAPPENS TO THE LANDED AUDIO NEXT, in the log's words. Never lifts a +// pause or a hold: a job asked for waits behind them, and the lane draws the +// video by its own rules when it runs. +export function transcriptionHandoffLines(f: HandoffFacts): string[] { + if (f.hasTranscript) { + return ["Transcription: a transcript is already on disk; nothing is queued for this video."]; + } + const holds: string[] = []; + if (f.workersPaused) holds.push("the transcription workers are paused"); + if (f.laneHeld) holds.push("the transcription lane is held"); + if (f.channelPaused) holds.push("this channel is paused for transcription"); + const behind = holds.length ? ` It waits behind the pause (${holds.join("; ")}); nothing here lifts it.` : ""; + if (f.transcribeJob) return [`Transcription: a transcribe-one job is asked for this video.${behind}`]; + if (f.laneEnabled && f.ruleCoversChannel) { + return [`Transcription: the transcription lane's rules take this channel; it draws this video in its order.${behind}`]; + } + return [ + "Transcription: the transcription lane does not take this channel" + + (f.laneEnabled ? " (no rule names it)" : " (the lane is off)") + + ` — transcribe it from the video page, or land it with transcribe: true.${behind}`, + ]; +} + +// The facts above, read from the running editor's settings and worker pool. +export async function readHandoffFacts(opts: { + slug: string; + channelConfig: ChannelConfig; + videoDir: string; + transcribeJob: boolean; +}): Promise<HandoffFacts> { + const { getSettings } = await import("../lib/settings"); + const { getWorkerPool } = await import("../jobs/workerPool"); + const { flattenLeaves, matchesChannel } = await import("../jobs/autoQueuePolicy"); + const { isChannelPaused } = await import("../lib/channelPriority"); + const settings = getSettings(); + const policy = settings.autoQueue?.transcription; + const platform = opts.channelConfig.platform ?? null; + let ruleCoversChannel = false; + try { + ruleCoversChannel = policy?.root + ? flattenLeaves(policy.root).some((l) => matchesChannel(l.match, { slug: opts.slug, platform } as never)) + : false; + } catch { + ruleCoversChannel = false; + } + return { + workersPaused: getWorkerPool().isPaused(), + laneEnabled: policy?.enabled === true, + laneHeld: policy?.held === true, + ruleCoversChannel, + channelPaused: settings.channelPriority ? isChannelPaused(settings.channelPriority, opts.slug, "transcription") : false, + hasTranscript: await stat(path.join(opts.videoDir, WHISPER_FILENAME)).then((s) => s.isFile(), () => false), + transcribeJob: opts.transcribeJob, + }; +} diff --git a/common/controller/preparePlayable.ts b/common/controller/preparePlayable.ts @@ -179,7 +179,7 @@ async function ffprobe(paths: Paths, file: string, signal?: AbortSignal): Promis // so a 36 GB channel interleaves with builds and e2e instead of holding the // slot for hours. The gate forwards a cancel to ffmpeg. A checkout without // the gate (a test's temp root) runs ffmpeg directly; HEAVY=0 bypasses it. -async function ffmpegRemux(paths: Paths, src: string, dest: string, args: string[], signal?: AbortSignal): Promise<void> { +export async function ffmpegRemux(paths: Paths, src: string, dest: string, args: string[], signal?: AbortSignal): Promise<void> { const ffmpegArgs = ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, ...args, dest]; const gate = paths.monorepoRoot ? path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs") : null; const gated = gate !== null && (await stat(gate).then((s) => s.isFile()).catch(() => false)); diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -0,0 +1,380 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { MediaProbe } from "../lib/mediaImport"; +import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/recordLive.test.ts +// +// Record live (controller/recordLive.ts) over a temp corpus: the recorders, the +// browser and the network are stubs that write fake "media" files +// (`format=<name>;seconds=<n>`); the landing is the real one with a stub probe. +// One case spawns a real child to prove a Cancel reaches it as SIGINT. + +const ROOT = await mkdtemp(path.join(tmpdir(), "record-live-")); +const CORPUS = path.join(ROOT, "transcripts"); +process.env.TRANSCRIPTS_DIR = CORPUS; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await mkdir(CORPUS, { recursive: true }); +await writeFile(process.env.SETTINGS_FILE, "{}"); + +const { getPaths } = await import("../lib/paths"); +const { + parseRecordLiveRequest, + planForUrl, + pollEventPlaylist, + recordLiveRun, + spawnRecorder, + choosePlaylist, + hlsFormatOf, +} = await import("./recordLive"); +const { liveRecordingSidecar } = await import("../lib/mediaImport-server"); +const { loadSavedVideo } = await import("../lib/savedVideo-server"); +const { isDoNotClean } = await import("../lib/doNotClean-server"); + +const paths = getPaths(); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const SLUG = "synth-rumble"; +const CONFIG = { handling: "transcribe", url: "https://rumble.com/c/Synth", platform: "rumble", name: "Synth" } as ChannelConfig; +await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true }); +await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); +await mkdir(paths.savedVideosDir, { recursive: true }); + +async function fakeProbe(file: string): Promise<MediaProbe | null> { + const text = await readFile(file, "utf8").catch(() => ""); + const all = [...text.matchAll(/seconds=([\d.]+)/g)].reduce((s, m) => s + Number(m[1]), 0); + if (!/format=/.test(text)) return null; + return { formatName: /format=([^;]+)/.exec(text)![1]!, seconds: all, videoCodec: "h264", audioCodec: "aac" }; +} +const land = { + probe: fakeProbe, + remux: async (src: string, dest: string) => { + await writeFile(dest, `format=mov,mp4;seconds=${(await fakeProbe(src))!.seconds};`); + }, + transcode: async (o: { videoDir: string; fmt: string }) => { + await writeFile(path.join(o.videoDir, `audio.${o.fmt}`), "format=mp3;seconds=1;"); + }, + freeBytes: async () => 1e15, +}; +const handoff = async () => ({ + workersPaused: true, + laneEnabled: true, + laneHeld: false, + ruleCoversChannel: true, + channelPaused: false, + hasTranscript: false, + transcribeJob: false, +}); +const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const; + +// A refresh that writes the stream's metadata (live, with one HLS format). +function refreshWith(meta: Record<string, unknown>, opts: { failFirst?: string } = {}) { + let n = 0; + return async (cwd: string, args: string[]): Promise<AttemptOutcome> => { + n++; + if (opts.failFirst && n === 1) return { exitCode: 1, stderrTail: opts.failFirst, archiveLine: null, formatLine: null }; + const o = args[args.indexOf("-o") + 1]!; + const dir = path.join(cwd, path.dirname(o)); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta)); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }; +} + +const RUMBLE_META = { + id: "v7embed", + extractor: "RumbleEmbed", + title: "A live show", + live_status: "is_live", + timestamp: 1792691875, + formats: [ + { format_id: "hls-0", protocol: "m3u8_native", height: 360, url: "https://cdn.example/live/chunklist_360p_i0_DVR.m3u8" }, + { format_id: "hls-1", protocol: "m3u8_native", height: 720, url: "https://cdn.example/live/chunklist_720p_i0_DVR.m3u8" }, + ], +}; +const DVR = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:1\n#EXTINF:2,\nm_1.ts\n#EXTINF:2,\nm_2.ts\n"; + +test("which stream: Rumble by URL id, Kick by channel or VOD uuid", () => { + assert.deepEqual(planForUrl("https://rumble.com/v7h8pxg-9-thugs.html"), { url: "https://rumble.com/v7h8pxg-9-thugs.html", platform: "rumble", id: "v7h8pxg" }); + const ch = planForUrl("https://kick.com/asmongold"); + assert.ok(!("error" in ch) && ch.id === null && ch.kickChannel === "asmongold"); + const vod = planForUrl("https://kick.com/asmongold/videos/01a164b1-0c18-723a-a785-f9637c989507"); + assert.ok(!("error" in vod) && vod.id === "01a164b1-0c18-723a-a785-f9637c989507" && vod.kickChannel === "asmongold"); + const canon = planForUrl("https://kick.com/video/01a164b1-0c18-723a-a785-f9637c989507"); + assert.ok(!("error" in canon) && canon.id === "01a164b1-0c18-723a-a785-f9637c989507"); + assert.ok("error" in parseRecordLiveRequest({ slug: "s" })); + assert.ok("error" in parseRecordLiveRequest({ slug: "s", url: "x", maxHeight: 10 })); + assert.deepEqual(parseRecordLiveRequest({ slug: "s", url: "https://kick.com/a", maxHeight: null, doNotClean: true }), { + slug: "s", + url: "https://kick.com/a", + maxHeight: null, + doNotClean: true, + }); + assert.equal(hlsFormatOf(RUMBLE_META, 480)?.height, 360); +}); + +test("Rumble path A: yt-dlp --live-from-start into a staging part, then landed; Do not clean; the pause named", async () => { + const calls: { bin: string; args: string[] }[] = []; + const log: string[] = []; + const s = await recordLiveRun({ + paths, + request: { slug: SLUG, url: "https://rumble.com/v1aaaaa-show.html", doNotClean: true, note: "Huck — keep" }, + plan: { url: "https://rumble.com/v1aaaaa-show.html", platform: "rumble", id: "v1aaaaa" }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: (l) => void log.push(l), + signal: new AbortController().signal, + deps: { + refresh: refreshWith(RUMBLE_META), + fetchText: async () => DVR, + spawn: async ({ bin, args }) => { + calls.push({ bin, args }); + await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=7200;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + land, + freeBytes: async () => 1e15, + handoff, + }, + }); + assert.equal(calls.length, 1); + const args = calls[0]!.args; + assert.ok(args.includes("--live-from-start")); + assert.ok(args.includes("--impersonate"), "the channel's Rumble args"); + assert.match(args[args.indexOf("--downloader-args") + 1]!, /-live_start_index 0/); + assert.equal(s.status, "landed"); + assert.equal(s.reach?.fromStart, true); + assert.equal(s.landed?.seconds, 7200); + const dir = path.join(CORPUS, "channels", SLUG, "data", "v1aaaaa"); + assert.equal((await loadSavedVideo(dir))?.origin?.requestedBy, "record-live"); + assert.ok(await isDoNotClean(dir)); + const rec = await liveRecordingSidecar.load(dir); + assert.equal(rec?.status, "landed"); + assert.equal(rec?.parts[0]?.method, "ytdlp"); + assert.ok(log.some((l) => /broadcast from its start/.test(l))); + assert.ok(log.some((l) => /waits behind the pause/.test(l))); + const slugStore = path.join(paths.savedVideosDir, SLUG); + assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".")), [], "no staging left"); +}); + +test("yt-dlp cannot start at the start: --no-live-from-start with ffmpeg at index 0; the longest part lands", async () => { + const calls: string[][] = []; + const s = await recordLiveRun({ + paths, + request: { slug: SLUG, url: "https://rumble.com/v2bbbbb-show.html" }, + plan: { url: "https://rumble.com/v2bbbbb-show.html", platform: "rumble", id: "v2bbbbb" }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: new AbortController().signal, + deps: { + refresh: refreshWith(RUMBLE_META), + fetchText: async () => DVR, + spawn: async ({ args }) => { + calls.push(args); + if (calls.length === 1) { + return { exitCode: 1, stderrTail: "ERROR: --live-from-start is passed, but there are no formats that can be downloaded from the start.", signalled: false }; + } + await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=600;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + land, + freeBytes: async () => 1e15, + handoff, + }, + }); + assert.equal(calls.length, 2); + assert.ok(calls[1]!.includes("--no-live-from-start")); + assert.match(calls[1]![calls[1]!.indexOf("--downloader-args") + 1]!, /-live_start_index 0/); + assert.equal(s.landed?.seconds, 600); +}); + +test("Rumble refuses yt-dlp: path B — the page's playlist from a browser, recorded by ffmpeg", async () => { + const bins: string[] = []; + const s = await recordLiveRun({ + paths, + request: { slug: SLUG, url: "https://rumble.com/v3ccccc-show.html" }, + plan: { url: "https://rumble.com/v3ccccc-show.html", platform: "rumble", id: "v3ccccc" }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: new AbortController().signal, + deps: { + refresh: refreshWith(RUMBLE_META, { failFirst: "ERROR: [RumbleEmbed] v3: Unable to download JSON metadata: HTTP Error 403: Forbidden" }), + fetchText: async (url) => + /playlist\.m3u8/.test(url) + ? "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,RESOLUTION=1280x720\nchunklist_720p_i0_DVR.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=1,RESOLUTION=640x360\nchunklist_360p_i0_DVR.m3u8\n" + : DVR, + sniff: async () => ({ ok: true, playlists: ["https://rumble.com/live-hls-dvr/key/playlist.m3u8?level=1"] }), + spawn: async ({ bin, args }) => { + bins.push(bin); + assert.equal(args[args.indexOf("-i") + 1], "https://rumble.com/live-hls-dvr/key/chunklist_720p_i0_DVR.m3u8"); + assert.equal(args[args.indexOf("-live_start_index") + 1], "0"); + await writeFile(args.at(-1)!, "format=mpegts;seconds=300;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + land, + freeBytes: async () => 1e15, + handoff, + }, + }); + assert.deepEqual(bins, [paths.ffmpegBin]); + assert.equal(s.parts[0]?.method, "browser"); + assert.equal(s.landed?.seconds, 300); +}); + +test("a stream that is not live is refused before anything is recorded", async () => { + await assert.rejects( + recordLiveRun({ + paths, + request: { slug: SLUG, url: "https://rumble.com/v4ddddd-show.html" }, + plan: { url: "https://rumble.com/v4ddddd-show.html", platform: "rumble", id: "v4ddddd" }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: new AbortController().signal, + deps: { refresh: refreshWith({ ...RUMBLE_META, live_status: "was_live" }), land, handoff }, + }), + /is not live \(live_status was_live\)/, + ); + await assert.rejects(stat(path.join(CORPUS, "channels", SLUG, "data", "v4ddddd")), "the record it made is not left behind"); +}); + +test("Kick: the ongoing VOD polled from segment 0 beside the channel's live stream; the longer lands", async () => { + const KICK = { handling: "transcribe", url: "https://kick.com/synth/videos", platform: "kick", name: "Synth Kick" } as ChannelConfig; + const slug = "synth-kick"; + await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true }); + await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK)); + const uuid = "01a164b1-0c18-723a-a785-f9637c989507"; + const spawned: string[][] = []; + const s = await recordLiveRun({ + paths, + request: { slug, url: "https://kick.com/synth" }, + plan: { url: "https://kick.com/synth", platform: "kick", id: null, kickChannel: "synth" }, + channelConfig: KICK, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: new AbortController().signal, + deps: { + kickVod: async () => ({ id: uuid, url: `https://kick.com/synth/videos/${uuid}` }), + refresh: refreshWith({ + id: uuid, + extractor: "kick:vod", + live_status: "is_live", + uploader_id: "synth", + formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/x/360p30/playlist.m3u8" }], + }), + spawn: async ({ args }) => { + spawned.push(args); + await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=1000;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + poll: async (o) => { + assert.equal(o.playlistUrl, "https://stream.kick.com/x/360p30/playlist.m3u8"); + await writeFile(o.output, "format=mpegts;seconds=5000;"); + return { segments: 500, seconds: 5000, gaps: 0, firstSeq: 0, ended: "the VOD has not grown" }; + }, + land, + freeBytes: async () => 1e15, + handoff, + }, + }); + assert.equal(spawned.length, 1); + assert.ok(spawned[0]!.includes("--no-live-from-start"), "the channel's live stream has no DVR"); + assert.equal(spawned[0]!.at(-1), "https://kick.com/synth"); + assert.equal(s.id, uuid); + assert.equal(s.landed?.seconds, 5000, "the VOD from its start is the longer"); + assert.deepEqual(s.parts.map((p) => p.method).sort(), ["vod-poll", "ytdlp"]); +}); + +test("the VOD poller appends new segments in order, counts a gap, and ends when the stream is over", async () => { + const out = path.join(ROOT, "poll.ts"); + const snapshots = [ + "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT\n#EXT-X-MEDIA-SEQUENCE:0\n#EXTINF:10,\n0.ts\n#EXTINF:10,\n1.ts\n#EXT-X-ENDLIST\n", + "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT\n#EXT-X-MEDIA-SEQUENCE:0\n#EXTINF:10,\n0.ts\n#EXTINF:10,\n1.ts\n#EXTINF:10,\n2.ts\n#EXTINF:10,\n3.ts\n#EXT-X-ENDLIST\n", + ]; + let reads = 0; + let clock = 0; + const r = await pollEventPlaylist({ + playlistUrl: "https://stream.kick.com/x/playlist.m3u8", + output: out, + onLog: () => {}, + signal: new AbortController().signal, + liveEnded: () => reads >= 2, + idleEndMs: 1e9, + idleAfterLiveEndMs: 30_000, + fetchText: async () => snapshots[Math.min(reads++, 1)]!, + fetchBytes: async (url) => { + if (url.endsWith("/2.ts")) throw new Error("HTTP 404"); + return new TextEncoder().encode(`[${url.split("/").pop()}]`); + }, + now: () => clock, + wait: async (ms) => { + clock += ms; + }, + }); + assert.equal(await readFile(out, "utf8"), "[0.ts][1.ts][3.ts]"); + assert.equal(r.segments, 3); + assert.equal(r.gaps, 1); + assert.equal(r.firstSeq, 0); + assert.match(r.ended, /live stream ended/); +}); + +test("Cancel reaches the recorder as SIGINT, and it gets to finish its file", async () => { + const out = path.join(ROOT, "sigint.txt"); + const script = `process.on("SIGINT", () => { require("fs").writeFileSync(${JSON.stringify(out)}, "finalized"); process.exit(0); }); console.log("frame= 1"); setInterval(() => {}, 1000);`; + const ac = new AbortController(); + const lines: string[] = []; + const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: (l) => void lines.push(l), signal: ac.signal, label: "t" }); + await new Promise((r) => setTimeout(r, 400)); + ac.abort(); + const o = await p; + assert.equal(o.signalled, true); + assert.equal(o.exitCode, 0); + assert.equal(await readFile(out, "utf8"), "finalized"); + assert.ok(lines.some((l) => /SIGINT/.test(l))); +}); + +test("a cancelled recording still lands what it has", async () => { + const ac = new AbortController(); + const s = await recordLiveRun({ + paths, + request: { slug: SLUG, url: "https://rumble.com/v5eeeee-show.html" }, + plan: { url: "https://rumble.com/v5eeeee-show.html", platform: "rumble", id: "v5eeeee" }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: () => {}, + signal: ac.signal, + deps: { + refresh: refreshWith(RUMBLE_META), + fetchText: async () => DVR, + spawn: async ({ args }) => { + await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=42;"); + ac.abort(); + return { exitCode: 255, stderrTail: "", signalled: true }; + }, + land, + freeBytes: async () => 1e15, + handoff, + }, + }); + assert.equal(s.status, "cancelled"); + assert.equal(s.landed?.seconds, 42); + const dir = path.join(CORPUS, "channels", SLUG, "data", "v5eeeee"); + await stat(path.join(dir, "saved-video.json")); +}); + +test("choosePlaylist: the master's variant by height, else the page's DVR chunklist", async () => { + const sig = new AbortController().signal; + const failing = async () => { + throw new Error("403"); + }; + assert.equal( + await choosePlaylist(["https://cdn/x/chunklist_i1.m3u8", "https://cdn/x/chunklist_i1_DVR.m3u8"], 720, failing, sig), + "https://cdn/x/chunklist_i1_DVR.m3u8", + ); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -0,0 +1,951 @@ +// 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:<slug>:<id>`), 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/<id>/ 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. +// 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.<fmt>, the archive +// line, media-import.json. The other parts are removed (staging scratch). +// 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 { mkdir, readFile, readdir, rm, stat } from "node:fs/promises"; +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, + extractionRefused, + ffmpegLiveArgs, + liveFormatSelector, + liveFromStartUnsupported, + newSegments, + parsePlaylist, + pickVariant, + playlistReach, + ytdlpLiveArgs, + type LivePart, + type LivePartMethod, + type LiveRecordingRecord, + type MediaPlaylist, + type MediaSegment, + type PlaylistReach, +} from "../lib/liveCapture"; +import { liveRecordingSidecar } from "../lib/mediaImport-server"; +import { setDoNotClean } from "../lib/doNotClean-server"; +import type { Paths } from "../lib/paths"; +import { detectPlatform } from "../lib/platform"; +import { savedVideoDir, savedVideoRoot } from "../lib/savedVideo"; +import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; +import { getFreeBytes } from "../lib/diskSpace"; +import { formatBytes } from "../lib/format"; +import { applyPendingKeep } from "../lib/pendingKeep-server"; +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { channelExtraArgs, configForVideoUrl } from "../ytdlp/channelArgs"; +import { dataDirIdForUrl } from "../ytdlp/runYtdlp"; +import { + ensureStoreRoot, + landMediaFile, + probeMedia, + readHandoffFacts, + transcriptionHandoffLines, + type LandMediaDeps, +} from "./landMedia"; +import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; +import { findVideoSourceUrl } from "./undownloadedVideos"; + +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", + "transcribe", + "doNotClean", + "note", + "dryRun", +] as const; + +// The user agent path B's ffmpeg and the playlist reads present (the pinned +// Firefox the Rumble channels' `ytdlpExtraArgs` carry). +export const LIVE_FETCH_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0"; + +// 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; +// 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; + +export type RecordLiveRequest = { + slug: string; + id?: string; + url?: string; + // Default true. + fromStart?: boolean; + // null = the tallest. Default LIVE_DEFAULT_MAX_HEIGHT. + maxHeight?: number | null; + transcribe?: boolean; + doNotClean?: boolean; + note?: string; + dryRun?: boolean; +}; + +export function parseRecordLiveRequest(body: Record<string, unknown>): 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", "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; + 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<RecordLivePlan | { error: string }> { + 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 }; +} + +export function recordLiveQueueKey(slug: string, id: string | null, kickChannel?: string): string { + return `record-live:${slug}:${id ?? `kick-${kickChannel ?? "?"}`}`; +} + +// --- the recorder process ---------------------------------------------------------- + +export type RecorderOutcome = { exitCode: number | null; stderrTail: string; signalled: boolean }; + +export type RecorderSpawn = (opts: { + bin: string; + args: string[]; + cwd: string; + onLog: (s: string) => void; + signal: AbortSignal; + label: string; +}) => Promise<RecorderOutcome>; + +// A progress line yt-dlp or ffmpeg repeats every second for hours. +const PROGRESS_RE = /^(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/; +const PROGRESS_EVERY_MS = 5 * 60_000; + +// ONE RECORDER: spawned as a plain child (so a SIGINT reaches yt-dlp, which +// asks its ffmpeg to quit with `q` and the file is finalized), its output in +// the job's log with the per-second progress thinned to one line every five +// minutes. A Cancel sends SIGINT, then SIGKILL after RECORDER_GRACE_MS. +export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, label }) => + 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"] }); + let tail = ""; + let lastProgress = 0; + let signalled = false; + let killTimer: NodeJS.Timeout | null = null; + const feed = (chunk: Buffer, isErr: boolean) => { + const text = chunk.toString("utf8"); + if (isErr) tail = (tail + text).slice(-32 * 1024); + for (const line of text.split(/[\r\n]+/)) { + const l = line.trim(); + if (!l) continue; + if (PROGRESS_RE.test(l)) { + const now = Date.now(); + if (now - lastProgress < PROGRESS_EVERY_MS) continue; + 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; + onLog(`[${label}] stopping: SIGINT, so the recording is finalized\n`); + child.kill("SIGINT"); + killTimer = setTimeout(() => child.kill("SIGKILL"), RECORDER_GRACE_MS); + }; + if (signal.aborted) onAbort(); + else signal.addEventListener("abort", onAbort, { once: true }); + child.on("error", (err) => { + tail += `\n${err.message}`; + }); + child.on("close", (code) => { + if (killTimer) clearTimeout(killTimer); + signal.removeEventListener("abort", onAbort); + resolve({ exitCode: code, stderrTail: tail, signalled }); + }); + }); + +// --- Kick: the ongoing VOD, polled ------------------------------------------------ + +export type FetchText = (url: string, signal: AbortSignal) => Promise<string>; +export type FetchBytes = (url: string, signal: AbortSignal) => Promise<Uint8Array>; + +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": LIVE_FETCH_USER_AGENT }, 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": LIVE_FETCH_USER_AGENT }, 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<void> { + 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<void>; +}): Promise<PollResult> { + 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<void>((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; + } + await wait(pollMs, opts.signal); + } + } finally { + await new Promise<void>((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<SniffResult>; + +// 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); + const [bin, ...args] = gated ? [process.execPath, gate, "--heavy", "--estimate", "1000", "--", ...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<string | null> { + 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/<channel>/videos, its first entry). + kickVod?: (channel: string, signal: AbortSignal) => Promise<{ id: string; url: string } | null>; + poll?: typeof pollEventPlaylist; + freeBytes?: (dir: string) => Promise<number>; + now?: () => Date; +}; + +export type RecordLiveJobOpts = { + paths: Paths; + request: RecordLiveRequest; + plan: RecordLivePlan; + channelConfig: ChannelConfig; + cookiePolicy: ResolvedCookiePolicy; + requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; + afterRun?: () => void | Promise<void>; + 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<string, unknown>; + +async function readMeta(videoDir: string): Promise<Meta | null> { + 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, + ["--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; + } +} + +export async function recordLiveRun( + opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal }, +): Promise<RecordLiveSummary> { + 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 runRecorder = deps.spawn ?? spawnRecorder; + const getText = deps.fetchText ?? fetchText; + 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!; + 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`}${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."); + 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/<id>/ with metadata is what every enumerator reads as "fetched". + const RECORD_ONLY = new Set(["metadata.info.json", "metadata.history.json", "live-recording.json"]); + const abandon = async () => { + if (!created) return; + const left = await readdir(videoDir).catch(() => [] as string[]); + if (left.every((n) => RECORD_ONLY.has(n))) await rm(videoDir, { recursive: true, force: true }); + }; + let extractionError: string | 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 } : {}), + }); + try { + await refresh(); + } catch (err) { + extractionError = (err as Error).message; + const canFallBack = BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(extractionError); + if (!canFallBack) { + await abandon(); + throw err; + } + 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; + if (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 < RECORD_LIVE_MIN_FREE_BYTES) { + throw new Error( + `the store's disk has ${formatBytes(free)} free; a live recording needs ${formatBytes(RECORD_LIVE_MIN_FREE_BYTES)} — nothing recorded`, + ); + } + } catch (err) { + await abandon(); + throw err; + } + await mkdir(slugStore, { recursive: true }); + const stamp = now().toISOString().replace(/[:.]/g, "-"); + const partPath = (tag: string) => path.join(slugStore, `.${id}.live-${stamp}.${tag}.ts`); + const leftovers = (await readdir(slugStore).catch(() => [] as string[])) + .filter((n) => n.startsWith(`.${id}.live-`) && n.endsWith(".ts")) + .map((n) => path.join(slugStore, n)); + if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed.`); + + const record: LiveRecordingRecord = { + status: "recording", + url: plan.url, + platform: plan.platform, + fromStart, + startedAt: now().toISOString(), + parts: [], + }; + const save = () => liveRecordingSidecar.write(videoDir, record); + + // How far back the playlist reaches (best effort, one read). + const fmt = meta ? hlsFormatOf(meta, maxHeight) : null; + if (fmt && plan.platform !== "kick") { + 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(); + + const parts: { part: LivePart; file: string }[] = []; + const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => { + const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString() }; + record.parts.push(part); + parts.push({ part, file }); + return part; + }; + const finish = (part: LivePart, note: string) => { + part.endedAt = now().toISOString(); + part.note = note; + }; + + // 2. The recording. + // "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. + const ytdlpPart = async ( + url: string, + tag: string, + mode: "from-start" | "index0" | "now", + extraNote = "", + ): Promise<RecorderOutcome> => { + const file = partPath(tag); + const part = begin("ytdlp", url, file, mode !== "now"); + await save(); + const args = ytdlpLiveArgs({ + url, + output: file, + fromStart: mode === "from-start", + maxHeight, + waitForVideo: liveStatus === "is_upcoming" && tag !== "channel", + channelArgs: [ + ...channelExtraArgs(cfg, cookies), + "--downloader-args", + `ffmpeg_i:${mode !== "now" ? "-live_start_index 0 " : ""}-m3u8_hold_counters 180 -seg_max_retry 10`, + ], + }); + const o = await runRecorder({ bin: paths.ytdlpBin, args, cwd: channelDir, onLog, signal, label: tag }); + finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? " (stopped)" : ""}`); + await save(); + return o; + }; + const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0); + + 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"); + liveDone = true; + return o; + })() + : Promise.resolve(); + let poll: Promise<unknown> = 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}`); + 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) { + let o = await ytdlpPart(plan.url, "ytdlp", fromStart ? "from-start" : "now"); + if (!signal.aborted && fromStart && liveFromStartUnsupported(o.stderrTail)) { + say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment."); + o = await ytdlpPart(plan.url, "ytdlp-index0", "index0", "--no-live-from-start + -live_start_index 0; "); + } + const last = parts[parts.length - 1]; + if ( + !signal.aborted && + o.exitCode !== 0 && + last && + (await sizeOf(last.file)) === 0 && + BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && + extractionRefused(o.stderrTail) + ) { + say("yt-dlp was refused; recording from the page's own playlist."); + pathB = true; + } + } 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: LIVE_FETCH_USER_AGENT, 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. + const cancelled = signal.aborted; + const landSignal = new AbortController().signal; + try { + await refresh(); + } catch (err) { + say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`); + } + const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s)); + const candidates: { file: string; seconds: number | null; part?: LivePart }[] = []; + for (const p of parts) { + if ((await sizeOf(p.file)) === 0) { + await rm(p.file, { force: true }); + continue; + } + const s = (await probe(p.file, landSignal))?.seconds ?? null; + p.part.seconds = s; + p.part.bytes = await sizeOf(p.file); + candidates.push({ file: p.file, seconds: s, part: p.part }); + } + for (const f of leftovers) { + if ((await sizeOf(f)) === 0) continue; + candidates.push({ file: f, seconds: (await probe(f, landSignal))?.seconds ?? null }); + } + summary.parts = record.parts.map((p) => ({ method: p.method, seconds: p.seconds ?? null, fromStart: p.fromStart })); + if (candidates.length === 0) { + record.status = cancelled ? "cancelled" : "failed"; + record.endedAt = now().toISOString(); + record.error = "nothing was recorded"; + await save(); + await abandon(); + summary.status = record.status; + say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); + if (!cancelled) throw new Error("nothing was recorded"); + return summary; + } + candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1)); + const best = candidates[0]!; + for (const c of candidates) { + say(`part ${path.basename(c.file)}: ${c.seconds !== null ? `${Math.round(c.seconds)} s` : "length unknown"}${c === best ? " — landed" : ""}`); + } + const landed = await landMediaFile({ + paths, + slug: req.slug, + channelConfig: opts.channelConfig, + videoId: id, + sourcePath: best.file, + via: "record-live", + move: true, + 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 } : {}), + }); + // The other parts were staging scratch; a shorter (or unlanded) one goes. + for (const c of candidates) if (c !== best || landed.kept === "existing") await rm(c.file, { force: true }); + record.landedPart = best.part ? record.parts.indexOf(best.part) : undefined; + record.kept = landed.kept; + record.status = cancelled ? "cancelled" : "landed"; + record.endedAt = now().toISOString(); + await save(); + summary.landed = { kept: landed.kept, seconds: landed.newSeconds, container: landed.container }; + summary.status = record.status; + + // 4. Keep it, and hand it on. + if (req.doNotClean) { + await setDoNotClean(videoDir, true, req.note); + say(`Marked "Do not clean"${req.note ? `: ${req.note}` : ""}.`); + } + await applyPendingKeep(paths, req.slug, id, onLog); + const facts = await (deps.handoff ?? readHandoffFacts)({ + slug: req.slug, + channelConfig: opts.channelConfig, + videoDir, + transcribeJob: req.transcribe === true, + }); + 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); + say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); + return summary; +} + +// Every refusal before any job; then the job. +export async function runRecordLiveJob( + opts: Omit<RecordLiveJobOpts, "plan">, +): Promise<StreamActionResult> { + 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) => { + await recordLiveRun({ ...opts, plan, onLog, signal }); + await opts.afterRun?.(); + }, + }); +} diff --git a/common/controller/transcode.ts b/common/controller/transcode.ts @@ -15,13 +15,17 @@ export type TranscodeAudioOptions = { paths: Paths; videoDir: string; sourceFilename: string; + // The source as an absolute path, when it is not in videoDir (a container + // in the saved-video store — controller/landMedia.ts). `sourceFilename` is + // then only its name, for the log. + sourcePath?: string; targetFormat: AudioFormat; onLog: (s: string) => void; signal: AbortSignal; }; export async function transcodeAudio(opts: TranscodeAudioOptions): Promise<void> { - const src = path.join(opts.videoDir, opts.sourceFilename); + const src = opts.sourcePath ?? path.join(opts.videoDir, opts.sourceFilename); const out = path.join(opts.videoDir, `audio.${opts.targetFormat}`); if (src === out) { throw new Error("Source and target are the same file"); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -762,6 +762,38 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "platform", needsMedia: true, }, + // A FILE MADE A NORMAL TRANSCRIBED ITEM (controller/importMedia.ts — `pnpm + // ops import-media`, "Import a file" on the channel and video pages): the + // record (one metadata-only pass for a source page, or by hand), then the + // landing shared with record-live (controller/landMedia.ts) — the container + // into the saved-video store, audio.<fmt> beside the record. Its own queue + // (`import-media:<slug>`), so a multi-GB copy never holds a platform's + // download queue. `needsMedia`: it writes the container and the audio. Not + // replayable: the ops call is the retry, and a landed file is "kept". + "import-media": { + kind: "import-media", + label: "Import a file", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + needsMedia: true, + }, + // A LIVE STREAM RECORDED (controller/recordLive.ts — `pnpm ops record-live`, + // "Record live" on the channel and video pages): yt-dlp `--live-from-start` + // (the fork's Rumble DVR support), else the page's playlist found by a + // browser and recorded by ffmpeg; Kick's ongoing VOD polled from its first + // segment beside the channel's live stream. Runs until the stream ends — + // hours — on its own queue (`record-live:<slug>:<id>`), never a platform's + // and never the heavy slot. Then the landing import-media uses. Cancel + // stops the recorder with SIGINT and lands what it has. `needsMedia`. + "record-live": { + kind: "record-live", + label: "Record live", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + needsMedia: true, + }, // FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's // Find clips, `pnpm ops find-clips`): the clip finder's chain for one video, // each step skipped when its output exists — persist the source, the corpus @@ -1349,6 +1381,10 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ // One video's live chat replay, normalized into the cues the index reads // (release 36 lane A). "fetch-chat", + // A file landed as a video's source, its audio beside it; a live recording + // landed the same way (plans/live-capture.md). + "import-media", + "record-live", ]); export function isIngestKind(kind: string | undefined): boolean { diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -174,6 +174,7 @@ const DECLARED: EnvVarDecl[] = [ // ── internal: the pipeline sets these for a process it spawns ────────── { name: "SITE_ID", audience: "internal", default: "—", readBy: "common/bin/compose-site.ts, export/app/lib/site.ts", doc: "Which site a compose or an export build is for. The build stage (`archilyzer publish build <id>`) sets it for its children; `compose site`, `build site` and `deploy site` fall back to it when no id is given." }, { name: "INSTANCE_MODE", audience: "internal", default: "a site", readBy: "export/app/lib/mode.ts, common/lib/archive/contract.ts", doc: "`hub` makes the export build the hub. Set by `archilyzer build hub`." }, + { name: "DISPLAY", audience: "internal", default: "set by `xvfb-run`", readBy: "common/ytdlp/liveSniff.mjs", doc: "record-live's browser fallback (path B) opens the page HEADED when a display is set — the caller runs it under `xvfb-run -a`, because Rumble's Cloudflare refuses a headless Chromium — and headless otherwise." }, { name: "BUILD_ARCHIVES", audience: "internal", default: "on", readBy: "common/bin/compose-site.ts, common/bin/build-archives.ts", doc: "`0` skips archive-zip generation for one build (`--skip-archives`)." }, { name: "REPORTS_ALLOW_MISSING_MEDIA", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list." }, { name: "ARCHIVES_READONLY", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` inside a docker-mode build container: materialize archives, never write the shared cache." }, diff --git a/common/lib/liveCapture.test.ts b/common/lib/liveCapture.test.ts @@ -0,0 +1,183 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + coerceLiveRecording, + extractionRefused, + ffmpegLiveArgs, + liveFormatSelector, + liveFromStartUnsupported, + newSegments, + parsePlaylist, + pickVariant, + playlistReach, + ytdlpLiveArgs, + type MediaPlaylist, +} from "./liveCapture"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/liveCapture.test.ts +// +// The playlists below are the shapes measured on 2026-10-22 (plans/live-capture.md), +// cut short. + +const RUMBLE_DVR = `#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-TARGETDURATION:2 +#EXT-X-MEDIA-SEQUENCE:1 +#EXT-X-DISCONTINUITY-SEQUENCE:0 +#EXT-X-PROGRAM-DATE-TIME:2026-10-22T17:58:02.584Z +#EXTINF:2, +media_3m1qvn_360p_1.ts +#EXTINF:2, +media_3m1qvn_360p_2.ts +#EXTINF:2, +media_3m1qvn_360p_3.ts +`; + +const RUMBLE_WINDOWED = `#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-TARGETDURATION:2 +#EXT-X-MEDIA-SEQUENCE:5313 +#EXT-X-PROGRAM-DATE-TIME:2026-10-22T14:17:06.315Z +#EXTINF:2, +media_nw0u1i_360p_5313.ts +#EXTINF:2, +media_nw0u1i_360p_5314.ts +`; + +const KICK_VOD = `#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-TARGETDURATION:10 +#EXT-X-PLAYLIST-TYPE:EVENT +#EXT-X-MEDIA-SEQUENCE:0 +#EXT-X-PROGRAM-DATE-TIME:2026-10-22T17:38:05.321Z +#EXTINF:10.000, +0.ts +#EXT-X-PROGRAM-DATE-TIME:2026-10-22T17:38:15.321Z +#EXTINF:10.000, +1.ts +#EXT-X-ENDLIST +`; + +const MASTER = `#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-STREAM-INF:BANDWIDTH=5212979,AVERAGE-BANDWIDTH=4739072,RESOLUTION=1920x1080 +https://cdn.example/live/chunklist_i0_DVR.m3u8 +#EXT-X-STREAM-INF:BANDWIDTH=3581600,RESOLUTION=1280x720 +https://cdn.example/live/chunklist_720p_i0_DVR.m3u8 +#EXT-X-STREAM-INF:BANDWIDTH=1460800,RESOLUTION=640x360 +chunklist_360p_i0_DVR.m3u8 +`; + +function media(text: string, base?: string): MediaPlaylist { + const p = parsePlaylist(text, base); + assert.equal(p?.kind, "media"); + return p as MediaPlaylist; +} + +test("a Rumble DVR playlist: sequence 1, resolved URIs, program date-times", () => { + const p = media(RUMBLE_DVR, "https://cdn.example/live/chunklist_360p_i0_DVR.m3u8"); + assert.equal(p.mediaSequence, 1); + assert.equal(p.targetDuration, 2); + assert.equal(p.playlistType, null); + assert.equal(p.endList, false); + assert.deepEqual( + p.segments.map((s) => [s.seq, s.uri]), + [ + [1, "https://cdn.example/live/media_3m1qvn_360p_1.ts"], + [2, "https://cdn.example/live/media_3m1qvn_360p_2.ts"], + [3, "https://cdn.example/live/media_3m1qvn_360p_3.ts"], + ], + ); + assert.equal(p.totalSeconds, 6); + assert.equal(p.segments[1]!.programDateTimeMs, Date.parse("2026-10-22T17:58:04.584Z")); +}); + +test("a Kick ongoing VOD: an EVENT playlist from 0 that ends every snapshot with ENDLIST", () => { + const p = media(KICK_VOD, "https://stream.kick.com/x/360p30/playlist.m3u8"); + assert.equal(p.playlistType, "EVENT"); + assert.equal(p.endList, true); + assert.equal(p.segments[0]!.seq, 0); + assert.equal(p.segments[1]!.uri, "https://stream.kick.com/x/360p30/1.ts"); +}); + +test("does the playlist reach the start: Rumble from 1, Kick from 0; a window past 4 h does not", () => { + assert.equal(playlistReach(media(RUMBLE_DVR), "rumble").fromStart, true); + assert.equal(playlistReach(media(KICK_VOD), "kick").fromStart, true); + const late = playlistReach(media(RUMBLE_WINDOWED), "rumble", Date.parse("2026-10-22T11:19:42Z")); + assert.equal(late.fromStart, false); + assert.equal(late.firstSeq, 5313); + assert.equal(late.missingSeconds, 10644); +}); + +test("newSegments takes what is past the last sequence taken", () => { + const p = media(RUMBLE_DVR); + assert.equal(newSegments(p, null).length, 3); + assert.deepEqual(newSegments(p, 2).map((s) => s.seq), [3]); + assert.equal(newSegments(p, 3).length, 0); +}); + +test("a master's variants, and the one ≤ maxHeight (else the shortest)", () => { + const m = parsePlaylist(MASTER, "https://cdn.example/live/playlist.m3u8"); + assert.equal(m?.kind, "master"); + const variants = m!.kind === "master" ? m!.variants : []; + assert.equal(variants.length, 3); + assert.equal(variants[2]!.url, "https://cdn.example/live/chunklist_360p_i0_DVR.m3u8"); + assert.equal(pickVariant(variants, 720)!.height, 720); + assert.equal(pickVariant(variants, null)!.height, 1080); + assert.equal(pickVariant(variants, 240)!.height, 360); + assert.equal(parsePlaylist("not a playlist"), null); +}); + +test("the yt-dlp argv: the channel's args first, the recording's after, MPEG-TS straight to the file", () => { + const args = ytdlpLiveArgs({ + url: "https://rumble.com/v1-x.html", + output: "/store/s/.v1.live.ytdlp.ts", + fromStart: true, + maxHeight: 720, + channelArgs: ["--impersonate", "firefox", "--no-live-from-start"], + }); + assert.ok(args.indexOf("--live-from-start") > args.indexOf("--no-live-from-start"), "after the channel's own"); + for (const flag of ["--hls-use-mpegts", "--no-part", "--ignore-config", "--no-download-archive"]) assert.ok(args.includes(flag), flag); + assert.deepEqual(args.slice(args.indexOf("--fixup"), args.indexOf("--fixup") + 2), ["--fixup", "never"]); + assert.equal(args[args.indexOf("-f") + 1], "best[height<=720]/best"); + assert.deepEqual(args.slice(-2), ["--", "https://rumble.com/v1-x.html"]); + assert.ok(!args.includes("--wait-for-video")); + const upcoming = ytdlpLiveArgs({ url: "u", output: "o", fromStart: false, maxHeight: null, channelArgs: [], waitForVideo: true }); + assert.ok(upcoming.includes("--no-live-from-start")); + assert.ok(upcoming.includes("--wait-for-video")); + assert.equal(liveFormatSelector(null), "best"); +}); + +test("the ffmpeg argv: from the first listed segment, stream copy, retries", () => { + const args = ffmpegLiveArgs({ url: "https://cdn/x.m3u8", output: "/o.ts", fromStart: true, userAgent: "UA", referer: "https://rumble.com/" }); + assert.equal(args[args.indexOf("-live_start_index") + 1], "0"); + assert.ok(args.indexOf("-live_start_index") < args.indexOf("-i")); + assert.deepEqual(args.slice(args.indexOf("-c"), args.indexOf("-c") + 2), ["-c", "copy"]); + assert.equal(args[args.indexOf("-headers") + 1], "Referer: https://rumble.com/\r\n"); + assert.equal(args.at(-1), "/o.ts"); + assert.ok(!ffmpegLiveArgs({ url: "u", output: "o", fromStart: false }).includes("-live_start_index")); +}); + +test("yt-dlp's two answers a recording acts on", () => { + assert.ok( + liveFromStartUnsupported( + "ERROR: [RumbleEmbed] v1: --live-from-start is passed, but there are no formats that can be downloaded from the start. If you want to download from the current time, use --no-live-from-start", + ), + ); + assert.ok(extractionRefused("ERROR: [RumbleEmbed] v1: Unable to download JSON metadata: HTTP Error 403: Forbidden")); + assert.ok(!extractionRefused("ERROR: This live event will begin in 3 hours")); +}); + +test("live-recording.json reads back, and refuses what is not one", () => { + const r = coerceLiveRecording({ + status: "landed", + url: "u", + platform: "rumble", + fromStart: true, + startedAt: "2026-10-22T18:00:00Z", + parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: "x" }, { method: "bogus" }], + }); + assert.equal(r?.parts.length, 1); + assert.equal(coerceLiveRecording({ status: "nope", url: "u", startedAt: "x" }), null); +}); diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -0,0 +1,373 @@ +// 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/<key>/playlist.m3u8`) +// names `chunklist_<q>_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/<channel>/videos/<uuid>`, 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, + ); +} + +// The quality selector for a live recording. Live HLS formats are muxed +// (video + audio in one), so one `best` filter picks one. +export function liveFormatSelector(maxHeight: number | null): string { + return maxHeight === null ? "best" : `best[height<=${maxHeight}]/best`; +} + +// THE yt-dlp RECORDING (path A). `channelArgs` are the channel's own +// (channelExtraArgs: cookies, the platform's args — Rumble's `--impersonate` — +// and `ytdlpExtraArgs`). The output is 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. +export function ytdlpLiveArgs(opts: { + url: string; + output: string; + fromStart: boolean; + maxHeight: number | null; + channelArgs: readonly string[]; + // 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; +}): 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", + liveFormatSelector(opts.maxHeight), + "--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.output, + "--", + opts.url, + ]; +} + +// 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", + ...(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; + 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; +}; + +export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled"; + +export type LiveRecordingRecord = { + status: LiveRecordingStatus; + url: string; + platform: string; + fromStart: 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; +}; + +const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled"]); +const PART_METHODS: ReadonlySet<string> = 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<string, unknown>; + 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<string> = new Set(["rumble"]); diff --git a/common/lib/mediaImport-server.ts b/common/lib/mediaImport-server.ts @@ -0,0 +1,20 @@ +// The two per-video sidecars of a landed file (lib/mediaImport.ts) and of a +// live recording (lib/liveCapture.ts), declared once. + +import { sidecar, sidecarField } from "./sidecar-server"; +import { + MEDIA_IMPORT_FILENAME, + appendMediaImportEntry, + coerceMediaImport, + type MediaImportEntry, +} from "./mediaImport"; +import { LIVE_RECORDING_FILENAME, coerceLiveRecording } from "./liveCapture"; + +export const mediaImportSidecar = sidecar(MEDIA_IMPORT_FILENAME, sidecarField(coerceMediaImport)); + +export const liveRecordingSidecar = sidecar(LIVE_RECORDING_FILENAME, sidecarField(coerceLiveRecording)); + +export async function recordMediaImport(videoDir: string, entry: MediaImportEntry): Promise<void> { + const prev = await mediaImportSidecar.load(videoDir); + await mediaImportSidecar.write(videoDir, appendMediaImportEntry(prev, entry)); +} diff --git a/common/lib/mediaImport.test.ts b/common/lib/mediaImport.test.ts @@ -0,0 +1,108 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + KEEP_LONGER_TOLERANCE_SECONDS, + appendMediaImportEntry, + archiveLineFor, + chooseKept, + coerceMediaImport, + finalizeFor, + importIdFromFilename, + manualRecordInfo, + parseImportRequest, + readProbe, + sourceExt, + type MediaImportEntry, + type MediaProbe, +} from "./mediaImport"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/mediaImport.test.ts + +test("keep the longer: a new file replaces a container only when longer by more than the slack", () => { + assert.equal(chooseKept({ newSeconds: 100 }), "new", "nothing stored"); + assert.equal(chooseKept({ newSeconds: 100, existingSeconds: 50 }), "new"); + assert.equal(chooseKept({ newSeconds: 100, existingSeconds: 100 - KEEP_LONGER_TOLERANCE_SECONDS }), "existing", "a tie stays"); + assert.equal(chooseKept({ newSeconds: 50, existingSeconds: 100 }), "existing"); + assert.equal(chooseKept({ newSeconds: 50, existingSeconds: 100, replace: true }), "new", "replace"); + assert.equal(chooseKept({ newSeconds: 100, existingSeconds: null }), "existing", "an unmeasured store stays"); + assert.equal(chooseKept({ newSeconds: null, existingSeconds: 10 }), "existing"); +}); + +const probe = (formatName: string, v: string | null, a: string | null, seconds = 60): MediaProbe => ({ + formatName, + seconds, + videoCodec: v, + audioCodec: a, +}); + +test("finalize: a stored container is copied, MPEG-TS and partials are remuxed, never re-encoded", () => { + assert.deepEqual(finalizeFor("x.mp4", probe("mov,mp4,m4a,3gp,3g2,mj2", "h264", "aac")), { + action: "copy", + ext: "mp4", + reason: "mov,mp4,m4a,3gp,3g2,mj2 as it is", + }); + const part = finalizeFor("v7f2czy.from-start.mp4.part", probe("mpegts", "h264", "aac")); + assert.ok(!("refused" in part) && part.action === "remux" && part.ext === "mp4"); + assert.ok(!("refused" in part) && part.remuxArgs!.includes("+faststart") && part.remuxArgs!.includes("copy")); + const ts = finalizeFor("rec.ts", probe("mpegts", "h264", "aac")); + assert.ok(!("refused" in ts) && ts.ext === "mp4"); + const odd = finalizeFor("rec.flv", probe("flv", "vp6f", "nellymoser")); + assert.ok(!("refused" in odd) && odd.ext === "mkv", "codecs mp4 cannot hold go to mkv"); + assert.ok(!("refused" in finalizeFor("x.webm", probe("matroska,webm", "vp9", "opus")))); + assert.deepEqual(finalizeFor("x.mp4", probe("mov,mp4", "h264", null)), { refused: "x.mp4 holds no audio stream: nothing to transcribe" }); + assert.equal(sourceExt("a.MP4.part"), "mp4"); +}); + +test("readProbe reads ffprobe's JSON", () => { + const p = readProbe({ + format: { format_name: "mpegts", duration: "1100.04" }, + streams: [{ codec_type: "video", codec_name: "h264" }, { codec_type: "audio", codec_name: "aac" }], + }); + assert.deepEqual(p, { formatName: "mpegts", seconds: 1100.04, videoCodec: "h264", audioCodec: "aac" }); + assert.equal(readProbe({}), null); +}); + +test("the request: one record named, absolute paths, booleans", () => { + const ok = parseImportRequest({ + slug: "the-quartering-rumble", + path: "/home/user/Podcasts/v7f2czy.from-start.mp4", + url: "https://rumble.com/v7h8pxg-x.html", + move: true, + doNotClean: true, + note: "keep", + }); + assert.ok(!("error" in ok)); + assert.equal((ok as { move: boolean }).move, true); + assert.equal((ok as { note: string }).note, "keep"); + const err = (b: Record<string, unknown>) => (parseImportRequest(b) as { error?: string }).error ?? ""; + assert.match(err({ slug: "s", path: "rel/x.mp4", id: "a" }), /absolute/); + assert.match(err({ slug: "s", path: "/x.mp4" }), /Say which record/); + assert.match(err({ slug: "s", path: "/x.mp4", url: "https://x/y", meta: { title: "t" } }), /not both/); + assert.match(err({ slug: "s", path: "/x.mp4", meta: { title: "t", date: "May 1" } }), /YYYY-MM-DD/); + assert.match(err({ slug: "s", path: "/x.mp4", id: "a", move: "yes" }), /true or false/); + assert.match(err({ slug: "s", path: "/x.mp4", id: "../a" }), /not a record id/); +}); + +test("a record by hand, an id from a file name, the archive line", () => { + assert.equal(importIdFromFilename("My Talk (2019) FINAL.mp4"), "my-talk-2019-final"); + assert.equal(importIdFromFilename("rec.mp4.part"), "rec"); + const info = manualRecordInfo({ id: "my-talk", meta: { title: "My talk", date: "2019-05-01" }, seconds: 123.456, fileName: "x.mkv" }); + assert.equal(info.upload_date, "20190501"); + assert.equal(info.duration, 123.46); + assert.equal(info.extractor, "import"); + assert.equal(archiveLineFor(info), null); + assert.equal(archiveLineFor({ extractor: "RumbleEmbed", id: "v7f2czy" }), "RumbleEmbed v7f2czy"); +}); + +test("media-import.json keeps its entries and challenges", () => { + const e = { at: "t", via: "import-media" } as MediaImportEntry; + const r = appendMediaImportEntry( + { entries: [], challenges: [{ at: "c", by: "download", what: "audio", newSeconds: 1, landedSeconds: 2, kept: "landed" }] }, + e, + ); + assert.equal(r.entries.length, 1); + assert.equal(r.challenges?.length, 1); + assert.equal(coerceMediaImport({ entries: [e, { bogus: 1 }] })?.entries.length, 1); + assert.equal(coerceMediaImport({}), null); +}); diff --git a/common/lib/mediaImport.ts b/common/lib/mediaImport.ts @@ -0,0 +1,379 @@ +// A FILE MADE INTO A NORMAL TRANSCRIBED ITEM — the pure half of the landing +// shared by `import-media` and `record-live` (controller/landMedia.ts, +// plans/live-capture.md). +// +// A file from outside — a recording made by hand, an external archive's copy, +// a live recording this app made — lands exactly like a persisted source +// video: `source-media.<ext>` in the saved-video store with a pointer in +// `data/<id>/saved-video.json`, `audio.<fmt>` beside the record (the tier hook +// after it), and the channel's pipeline takes it from there. What is its own: +// +// - FINALIZED, NEVER RE-ENCODED. A file ffprobe cannot read is refused. An +// MPEG-TS stream (a live recording, a yt-dlp `.part`), an FLV or anything +// else not a stored container is remuxed with `-c copy` (mp4 +faststart, +// else mkv when mp4 cannot hold its codecs); an mp4/mkv/webm/mov is +// copied as it is. +// - THE LONGER RECORDING STAYS. Over a container already in the store, the +// new one replaces it only when it is longer (KEEP_LONGER_TOLERANCE_SECONDS +// of slack, a tie keeps what is there) — unless `replace`. Which was kept, +// and both lengths, go in the provenance. +// - PROVENANCE: `media-import.json` beside the record, one entry per landing, +// newest last: where the file came from, its original name, when, how it +// was finalized, what was kept. + +import path from "node:path"; + +export const MEDIA_IMPORT_FILENAME = "media-import.json"; + +// Who landed a file. +export type MediaImportVia = "import-media" | "record-live"; + +// Two recordings of one stream within this many seconds are the same length: +// the one in the store stays. +export const KEEP_LONGER_TOLERANCE_SECONDS = 2; + +// How many entries media-import.json keeps (the oldest go first). +export const MEDIA_IMPORT_MAX_ENTRIES = 50; + +export type MediaImportEntry = { + at: string; + via: MediaImportVia; + source: { + // Absolute path of the file landed (a live recording: its staging file). + path: string; + // The file's own name, as it was. + name: string; + bytes: number; + // The original was removed once the copy verified (`move`). + moved?: boolean; + // The page it was recorded from or describes, when there is one. + url?: string; + }; + // How the container was made from it. + finalized: "copied" | "remuxed"; + container: { file: string; seconds: number | null; bytes: number }; + // What the store holds now: this landing's container ("new") or the one that + // was there ("existing", longer), with that one's length. + kept: "new" | "existing"; + existingSeconds?: number | null; + // What became of audio.<fmt>: extracted from the kept container, the one + // there kept (as long or longer), or none (`audio: false`). + audio: "extracted" | "kept-existing" | "skipped"; + note?: string; +}; + +// A later download of a landed video, and which recording stayed +// (ytdlp/landedGuard.ts). +export type MediaImportChallenge = { + at: string; + by: "download"; + what: "audio" | "container"; + newSeconds: number | null; + landedSeconds: number | null; + kept: "landed" | "download"; +}; + +export type MediaImportRecord = { entries: MediaImportEntry[]; challenges?: MediaImportChallenge[] }; + +export function coerceMediaImport(raw: unknown): MediaImportRecord | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const entries = (raw as { entries?: unknown }).entries; + if (!Array.isArray(entries)) return null; + const challenges = (raw as { challenges?: unknown }).challenges; + return { + ...(Array.isArray(challenges) + ? { + challenges: challenges.filter( + (c): c is MediaImportChallenge => !!c && typeof c === "object" && typeof (c as MediaImportChallenge).at === "string", + ), + } + : {}), + entries: entries.filter( + (e): e is MediaImportEntry => + !!e && + typeof e === "object" && + typeof (e as MediaImportEntry).at === "string" && + ((e as MediaImportEntry).via === "import-media" || (e as MediaImportEntry).via === "record-live"), + ), + }; +} + +export function appendMediaImportEntry(prev: MediaImportRecord | null, entry: MediaImportEntry): MediaImportRecord { + const entries = [...(prev?.entries ?? []), entry]; + return { ...(prev?.challenges ? { challenges: prev.challenges } : {}), entries: entries.slice(-MEDIA_IMPORT_MAX_ENTRIES) }; +} + +// KEEP THE LONGER. `existingSeconds` undefined = nothing in the store; +// null = something there that could not be measured (kept: an unreadable +// length is not evidence it is shorter). `replace` lands the new one always. +export function chooseKept(opts: { + newSeconds: number | null; + existingSeconds?: number | null; + replace?: boolean; +}): "new" | "existing" { + if (opts.replace) return "new"; + if (opts.existingSeconds === undefined) return "new"; + if (opts.existingSeconds === null) return "existing"; + if (opts.newSeconds === null) return "existing"; + return opts.newSeconds > opts.existingSeconds + KEEP_LONGER_TOLERANCE_SECONDS ? "new" : "existing"; +} + +// --- what ffprobe said ------------------------------------------------------------ + +export type MediaProbe = { + formatName: string; + seconds: number | null; + videoCodec: string | null; + audioCodec: string | null; +}; + +// ffprobe's `-show_format -show_streams -of json`, read. Null when it holds no +// format at all (not media). +export function readProbe(json: unknown): MediaProbe | null { + if (!json || typeof json !== "object") return null; + const j = json as { format?: { format_name?: unknown; duration?: unknown }; streams?: unknown }; + const formatName = typeof j.format?.format_name === "string" ? j.format.format_name : null; + if (!formatName) return null; + const d = Number.parseFloat(String(j.format?.duration ?? "")); + const streams = Array.isArray(j.streams) ? (j.streams as { codec_type?: unknown; codec_name?: unknown }[]) : []; + const codec = (type: string) => { + const s = streams.find((x) => x.codec_type === type && typeof x.codec_name === "string"); + return s ? String(s.codec_name) : null; + }; + return { + formatName, + seconds: Number.isFinite(d) && d > 0 ? Math.round(d * 1000) / 1000 : null, + videoCodec: codec("video"), + audioCodec: codec("audio"), + }; +} + +// Codecs an mp4 holds (a stream copy into mp4 of anything else fails). +const MP4_VIDEO = new Set(["h264", "hevc", "av1", "mpeg4", "vp9"]); +const MP4_AUDIO = new Set(["aac", "mp3", "ac3", "eac3", "opus", "alac", "flac"]); + +// A file's extension, without a trailing `.part` (a yt-dlp partial names the +// container it was to become). +export function sourceExt(name: string): string { + const base = name.replace(/\.part$/i, ""); + return path.extname(base).slice(1).toLowerCase(); +} + +export type LandingFinalize = { + action: "copy" | "remux"; + // The stored container's extension. + ext: string; + // Remux: the output format and its extra args. + remuxArgs?: string[]; + reason: string; +}; + +// HOW A PROBED FILE BECOMES A STORED CONTAINER. Never a re-encode. +export function finalizeFor(name: string, probe: MediaProbe): LandingFinalize | { refused: string } { + if (!probe.videoCodec && !probe.audioCodec) return { refused: `${name} holds no audio or video stream` }; + if (!probe.audioCodec) return { refused: `${name} holds no audio stream: nothing to transcribe` }; + const ext = sourceExt(name); + const partial = /\.part$/i.test(name); + const fmt = probe.formatName; + const isMp4 = /(^|,)(mov|mp4)(,|$)/.test(fmt); + const isMkv = /(^|,)(matroska|webm)(,|$)/.test(fmt); + if (!partial && isMp4 && ["mp4", "m4v", "mov"].includes(ext)) { + return { action: "copy", ext, reason: `${fmt} as it is` }; + } + if (!partial && isMkv && ["mkv", "webm"].includes(ext)) { + return { action: "copy", ext, reason: `${fmt} as it is` }; + } + const mp4Ok = + (probe.videoCodec === null || MP4_VIDEO.has(probe.videoCodec)) && + (probe.audioCodec === null || MP4_AUDIO.has(probe.audioCodec)); + if (mp4Ok) { + return { + action: "remux", + ext: "mp4", + remuxArgs: ["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-movflags", "+faststart", "-f", "mp4"], + reason: `${fmt}${partial ? " (a partial)" : ""} → mp4, stream copy`, + }; + } + return { + action: "remux", + ext: "mkv", + remuxArgs: ["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-f", "matroska"], + reason: `${fmt} (${probe.videoCodec ?? "no video"}/${probe.audioCodec}) → mkv, stream copy`, + }; +} + +// --- the request ------------------------------------------------------------------ + +export const IMPORT_MEDIA_BODY_KEYS = [ + "slug", + "path", + "url", + "id", + "meta", + "move", + "replace", + "audio", + "transcribe", + "doNotClean", + "note", + "dryRun", +] as const; + +// A record described by hand, for a file with no source page. +export type ManualMeta = { + title: string; + // YYYY-MM-DD (or YYYYMMDD). + date?: string; + duration?: number; + description?: string; + // A URL the file is a copy of, recorded as the record's `webpage_url` only + // when it is not a page yt-dlp would be asked about. + sourceNote?: string; +}; + +export type ImportMediaRequest = { + slug: string; + path: string; + url?: string; + id?: string; + meta?: ManualMeta; + move?: boolean; + replace?: boolean; + // false: land the container only, no audio.<fmt>. + audio?: boolean; + // true: hand the video to a transcribe-one job once landed (held by any + // pause like every transcription). Absent: the channel's lanes take it by + // their policy. + transcribe?: boolean; + // Set the video's "Do not clean" marker once landed, with `note`. + doNotClean?: boolean; + // Why: the marker's note, and the provenance entry's. + note?: string; + dryRun?: boolean; +}; + +// One path segment that a data dir may be named. +export function isRecordId(id: string): boolean { + return /^[\w.-]+$/.test(id) && id !== "." && id !== ".."; +} + +// An id for a file with no source page and no id given: its name, lowercased, +// [a-z0-9_-] only, at most 64 characters. +export function importIdFromFilename(name: string): string { + const stem = name.replace(/\.part$/i, "").replace(/\.[^.]+$/, ""); + const id = stem + .toLowerCase() + .replace(/[^a-z0-9_-]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 64) + .replace(/-+$/g, ""); + return id || "import"; +} + +function normalDate(raw: string | undefined): string | null { + if (!raw) return null; + const d = raw.trim().replace(/-/g, ""); + return /^\d{8}$/.test(d) ? d : null; +} + +// Validates a request body. The error is the sentence the caller answers. +export function parseImportRequest(body: Record<string, unknown>): ImportMediaRequest | { error: string } { + const str = (k: string) => (typeof body[k] === "string" ? (body[k] as string).trim() : undefined); + const slug = str("slug"); + const p = str("path"); + if (!slug) return { error: '"slug" is required' }; + if (!p) return { error: '"path" is required (an absolute path to a file, a directory, a .zip or a .7z)' }; + if (!path.isAbsolute(p)) return { error: `"path" must be absolute: ${p}` }; + const url = str("url"); + const id = str("id"); + let meta: ManualMeta | undefined; + if (body.meta !== undefined) { + const m = body.meta as Record<string, unknown> | null; + if (!m || typeof m !== "object" || Array.isArray(m)) return { error: '"meta" is {title, date?, duration?, description?}' }; + const title = typeof m.title === "string" ? m.title.trim() : ""; + if (!title) return { error: '"meta.title" is required' }; + if (m.date !== undefined && (typeof m.date !== "string" || normalDate(m.date) === null)) { + return { error: '"meta.date" is YYYY-MM-DD' }; + } + if (m.duration !== undefined && (typeof m.duration !== "number" || !(m.duration > 0))) { + return { error: '"meta.duration" is a number of seconds' }; + } + meta = { + title, + ...(typeof m.date === "string" ? { date: m.date } : {}), + ...(typeof m.duration === "number" ? { duration: m.duration } : {}), + ...(typeof m.description === "string" && m.description.trim() ? { description: m.description.trim() } : {}), + }; + } + if (url && meta) return { error: 'Give "url" (the source page) or "meta" (a record by hand), not both' }; + if (id !== undefined && !isRecordId(id)) return { error: `"${id}" is not a record id (one path segment)` }; + if (url && !/^https?:\/\//i.test(url)) return { error: `"url" must be an http(s) URL: ${url}` }; + if (!url && !id && !meta) { + return { error: 'Say which record the file is: "url" (its source page), "id" (a record already here) or "meta" ({title, date?})' }; + } + const flag = (k: string) => { + const v = body[k]; + if (v === undefined) return undefined; + if (typeof v !== "boolean") throw new Error(`"${k}" must be true or false`); + return v; + }; + try { + const move = flag("move"); + const replace = flag("replace"); + const audio = flag("audio"); + const transcribe = flag("transcribe"); + const doNotClean = flag("doNotClean"); + const dryRun = flag("dryRun"); + const note = str("note"); + return { + ...(doNotClean !== undefined ? { doNotClean } : {}), + ...(note ? { note } : {}), + slug, + path: p, + ...(url ? { url } : {}), + ...(id ? { id } : {}), + ...(meta ? { meta } : {}), + ...(move !== undefined ? { move } : {}), + ...(replace !== undefined ? { replace } : {}), + ...(audio !== undefined ? { audio } : {}), + ...(transcribe !== undefined ? { transcribe } : {}), + ...(dryRun !== undefined ? { dryRun } : {}), + }; + } catch (err) { + return { error: (err as Error).message }; + } +} + +// THE RECORD FOR A FILE WITH NO SOURCE PAGE: the fields every reader needs +// (id, title, upload_date, duration), and `extractor: "import"` so nothing +// mistakes it for a page yt-dlp could re-read. +export function manualRecordInfo(opts: { + id: string; + meta: ManualMeta; + seconds: number | null; + fileName: string; +}): Record<string, unknown> { + const date = normalDate(opts.meta.date); + const duration = opts.meta.duration ?? opts.seconds; + return { + id: opts.id, + title: opts.meta.title, + ...(opts.meta.description ? { description: opts.meta.description } : {}), + ...(date ? { upload_date: date } : {}), + ...(typeof duration === "number" && duration > 0 ? { duration: Math.round(duration * 100) / 100 } : {}), + extractor: "import", + extractor_key: "Import", + live_status: "not_live", + imported_from: opts.fileName, + }; +} + +// The `archive` file's line for a record yt-dlp wrote (`<extractor> <id>`, the +// shape downloadOneManaged prints with ARCHIVE_MARKER), or null for one it did +// not (a record by hand). +export function archiveLineFor(meta: Record<string, unknown>): string | null { + const ex = typeof meta.extractor === "string" ? meta.extractor : null; + const id = typeof meta.id === "string" ? meta.id : null; + if (!ex || !id || ex === "import") return null; + return `${ex} ${id}`; +} diff --git a/common/lib/mediaTier.ts b/common/lib/mediaTier.ts @@ -74,6 +74,10 @@ const SCRATCH_PATTERNS: ReadonlyArray<RegExp> = [ // is asked again (`audio.mp4.corrupt-kept`, ytdlp/corruptRefetch.ts): the // refetch moves it back or removes it when the download ends. /\.corrupt-kept$/, + // A landed recording's audio set aside while a later download of the same + // video runs (`audio.mp3.landed-kept`, ytdlp/landedGuard.ts): the longer of + // the two goes back under the name when the download ends. + /\.landed-kept$/, // The salvage transcription's decoded WAV (`audio.salvage.wav`, // lib/salvageAudio-server.ts): removed when the transcription ends. /^audio\.salvage\.wav$/, diff --git a/common/lib/metadataHistory.ts b/common/lib/metadataHistory.ts @@ -86,6 +86,9 @@ export const METADATA_HISTORY_WRITERS = [ // browser (release 32 R9, ytdlp/odyseeBrowserLookup.ts), when yt-dlp's lookup // is refused: only the keys the file lacks, and the one stored format. "browser-lookup", + // A record written by hand for a file with no source page (controller/ + // importMedia.ts, `meta`: a title, a date, the file's length). + "import-media", ] as const; export type MetadataHistoryWriter = (typeof METADATA_HISTORY_WRITERS)[number]; diff --git a/common/lib/pendingKeep-server.ts b/common/lib/pendingKeep-server.ts @@ -0,0 +1,91 @@ +// A "DO NOT CLEAN" ASKED FOR BEFORE THE VIDEO IS HERE (plans/live-capture.md). +// +// The marker (`data/<id>/do-not-clean.json`, lib/doNotClean-server.ts) lives in +// the video's dir, and nothing may make that dir but a fetch: every enumerator +// reads "has a dir" as "was fetched". A live stream has none — the download +// lane skips it while it is live — and the next sync may fetch its VOD before +// an import of a recording runs. So `keep-videos {ids}` records an id the +// channel does not hold yet as PENDING, in `channels/<slug>/pending-keep.json` +// ({entries: [{id, note, at}]}), and the marker is set the moment the record +// is first written: after a managed download (downloadOneManaged), an +// import-media landing, a record-live landing. Applied entries are removed. +// +// Written only through these functions (one atomic write per change). + +import path from "node:path"; +import { stat } from "node:fs/promises"; +import type { Paths } from "./paths"; +import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; +import { isDoNotClean, setDoNotClean } from "./doNotClean-server"; + +export const PENDING_KEEP_FILENAME = "pending-keep.json"; + +export type PendingKeepEntry = { id: string; note?: string; at: string }; + +function fileOf(paths: Pick<Paths, "channelsDir">, slug: string): string { + return path.join(paths.channelsDir, slug, PENDING_KEEP_FILENAME); +} + +export async function loadPendingKeep(paths: Pick<Paths, "channelsDir">, slug: string): Promise<PendingKeepEntry[]> { + const read = await readJsonFile(fileOf(paths, slug)); + if (!read.ok) return []; + const entries = (read.value as { entries?: unknown } | null)?.entries; + if (!Array.isArray(entries)) return []; + return entries.filter( + (e): e is PendingKeepEntry => + !!e && typeof e === "object" && typeof (e as PendingKeepEntry).id === "string" && typeof (e as PendingKeepEntry).at === "string", + ); +} + +async function save(paths: Pick<Paths, "channelsDir">, slug: string, entries: PendingKeepEntry[]): Promise<void> { + await writeJsonAtomic(fileOf(paths, slug), { entries }); +} + +// Adds (or re-notes) pending entries. Returns the list after. +export async function addPendingKeep( + paths: Pick<Paths, "channelsDir">, + slug: string, + ids: readonly string[], + note: string | undefined, + now: Date = new Date(), +): Promise<PendingKeepEntry[]> { + const entries = await loadPendingKeep(paths, slug); + for (const id of ids) { + const i = entries.findIndex((e) => e.id === id); + const entry: PendingKeepEntry = { id, ...(note ? { note } : {}), at: now.toISOString() }; + if (i >= 0) entries[i] = entry; + else entries.push(entry); + } + await save(paths, slug, entries); + return entries; +} + +// THE HOOK: when `id` is pending and its dir now exists, set the marker (with +// the pending note) and drop the entry. A no-op — one failed read — for the +// common case of a channel with nothing pending. Never throws: a marker that +// could not be set stays pending for the next landing. +export async function applyPendingKeep( + paths: Pick<Paths, "channelsDir">, + slug: string, + id: string, + onLog?: (s: string) => void, +): Promise<boolean> { + try { + const entries = await loadPendingKeep(paths, slug); + const entry = entries.find((e) => e.id === id); + if (!entry) return false; + const videoDir = path.join(paths.channelsDir, slug, "data", id); + if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) return false; + if (!(await isDoNotClean(videoDir))) await setDoNotClean(videoDir, true, entry.note ?? "keep-videos: asked before it was fetched"); + await save( + paths, + slug, + entries.filter((e) => e.id !== id), + ); + onLog?.(`Marked "Do not clean" (asked for before it was here${entry.note ? `: ${entry.note}` : ""}).\n`); + return true; + } catch (err) { + onLog?.(`The pending "Do not clean" for ${id} was not applied: ${(err as Error).message}\n`); + return false; + } +} diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -52,6 +52,8 @@ import { settleCorruptRefetch, type CorruptRefetchDeps, } from "./corruptRefetch"; +import { prepareLandedGuard, settleLandedGuard } from "./landedGuard"; +import { applyPendingKeep } from "../lib/pendingKeep-server"; import { formatBytes } from "../lib/format"; import { recordAvailability } from "../lib/availability-server"; import { withMetadataHistory } from "../lib/metadataHistory-server"; @@ -798,9 +800,26 @@ export async function downloadOneManaged( opts = { ...opts, storedUrl: "only" }; } } + // A LANDED RECORDING (an import, a live recording — ytdlp/landedGuard.ts) + // is never clobbered by a shorter download: its audio is set aside and the + // longer of the two stays. Null for every other video. + const landed = + canonicalId && !refetch + ? await prepareLandedGuard(path.join(channelDir, "data", canonicalId), opts.onLog) + : null; let outcome = await runManagedDownload(opts, channelDir, startedAt, canonicalId); if (refetch) outcome = await settleCorruptRefetch(refetch, outcome, refetchCtx); + if (landed) { + await settleLandedGuard( + landed, + { measure: (file) => probeMediaDurationSec({ ffprobeBin: opts.paths.ffprobeBin, file }) }, + opts.onLog, + ); + } await recordWaybackProvenance(opts, channelDir, canonicalId); + // A "Do not clean" asked for before the record existed (keep-videos ids, + // lib/pendingKeep-server.ts) is set now that it does. + if (canonicalId) await applyPendingKeep(opts.paths, opts.channelSlug, canonicalId, opts.onLog); return outcome; } finally { logStream?.end(); diff --git a/common/ytdlp/finalizeAppExtraction.ts b/common/ytdlp/finalizeAppExtraction.ts @@ -18,6 +18,8 @@ import { type SavedVideoOrigin, } from "../lib/savedVideo"; import { persistSourceVideo } from "../lib/savedVideo-server"; +import { probeMediaDurationSec } from "./ffprobeDuration"; +import { landedContainerWins } from "./landedGuard"; // After an app-mode transcribe download, produce audio.<fmt> from the downloaded // source-media.<ext> container via ffmpeg. When the video is persisted the @@ -64,6 +66,19 @@ export async function finalizeAppExtraction(opts: { ); return; } + // A LANDED RECORDING AS LONG OR LONGER STAYS (ytdlp/landedGuard.ts): the + // download's container is discarded, and nothing is extracted from it. + if ( + await landedContainerWins( + opts.videoDir, + path.join(opts.videoDir, source), + { measure: (file) => probeMediaDurationSec({ ffprobeBin: opts.paths.ffprobeBin, file }) }, + opts.onLog, + ) + ) { + await removeMediaFile(opts.videoDir, source); + return; + } if (opts.extractAudio === false) { opts.onLog( `Persist only: a transcript is on disk, so no audio.${opts.fmt} is extracted from ${source}.\n`, diff --git a/common/ytdlp/landedGuard.ts b/common/ytdlp/landedGuard.ts @@ -0,0 +1,158 @@ +// A LATER DOWNLOAD NEVER CLOBBERS A LONGER LANDED RECORDING (plans/live-capture.md). +// +// A video whose source was landed by import-media or record-live +// (controller/landMedia.ts — `media-import.json` beside the record, the +// pointer's `origin.requestedBy`) may be downloaded again by the ordinary +// paths: a sync that finds the VOD, a "Persist source video", a refetch. The +// VOD can be SHORTER than the recording (a streamer trims it, a platform cuts +// the first hours), so: +// +// audio before the download the held audio is set aside +// (`audio.mp3` → `audio.mp3.landed-kept`, through its tier link — +// lib/mediaTier-server.ts renameMediaFile; a scratch name the tier +// never moves). After it, the longer of the two stays +// (KEEP_LONGER_TOLERANCE_SECONDS of slack; a tie keeps the landed +// one) and the other is removed with removeMediaFile. No new file +// (a failed or skipped download): the aside one goes back. +// container finalizeAppExtraction asks `landedContainerWins` before it +// extracts or persists: when the store holds a landed container +// as long or longer than the new one, the new one is discarded, +// and so is its audio extraction. +// +// Every decision is appended to media-import.json's `challenges`. + +import path from "node:path"; +import { readdir } from "node:fs/promises"; +import { KEEP_LONGER_TOLERANCE_SECONDS, type MediaImportChallenge } from "../lib/mediaImport"; +import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; +import { mediaImportSidecar } from "../lib/mediaImport-server"; +import { removeMediaFile, renameMediaFile } from "../lib/mediaTier-server"; +import { savedVideoPath } from "../lib/savedVideo"; +import { loadSavedVideo } from "../lib/savedVideo-server"; + +export const LANDED_KEPT_SUFFIX = ".landed-kept"; + +export type LandedGuardDeps = { + // Seconds of a media file (null: not measurable). + measure: (file: string) => Promise<number | null>; + now?: () => Date; +}; + +export type LandedGuardPlan = { videoDir: string; asides: string[] }; + +// attach-media too: a container attached from a local archive is a recording +// somebody kept on purpose (keepReason "pin"), as an import is. +const LANDED_BY: ReadonlySet<string> = new Set(["import-media", "record-live", "attach-media"]); + +// Was this video's source landed (rather than downloaded)? +export async function isLandedVideo(videoDir: string): Promise<boolean> { + if ((await mediaImportSidecar.load(videoDir))?.entries.some((e) => e.kept === "new")) return true; + const pointer = await loadSavedVideo(videoDir); + return pointer?.origin?.requestedBy !== undefined && LANDED_BY.has(pointer.origin.requestedBy); +} + +async function recordChallenge(videoDir: string, c: MediaImportChallenge): Promise<void> { + const prev = await mediaImportSidecar.load(videoDir); + if (!prev) return; + await mediaImportSidecar.write(videoDir, { ...prev, challenges: [...(prev.challenges ?? []), c].slice(-50) }); +} + +// Before a managed download of a landed video: set its audio aside. Null for +// any other video (the download is then an ordinary one). A leftover aside +// from a run cut short is put back first. +export async function prepareLandedGuard(videoDir: string, onLog: (s: string) => void): Promise<LandedGuardPlan | null> { + let entries = await readdir(videoDir).catch(() => [] as string[]); + for (const left of entries.filter((n) => n.endsWith(LANDED_KEPT_SUFFIX))) { + const name = left.slice(0, -LANDED_KEPT_SUFFIX.length); + if (entries.includes(name)) await removeMediaFile(videoDir, name); + await renameMediaFile(videoDir, left, name); + onLog(`Put back ${name}, set aside by an interrupted download.\n`); + } + if (!(await isLandedVideo(videoDir))) return null; + entries = await readdir(videoDir).catch(() => [] as string[]); + const asides: string[] = []; + for (const name of entries.filter(isRealAudioFile)) { + await renameMediaFile(videoDir, name, name + LANDED_KEPT_SUFFIX); + asides.push(name); + } + if (asides.length) { + onLog(`This video's source was landed (import or live recording): ${asides.join(", ")} is set aside; the longer recording stays.\n`); + } + return { videoDir, asides }; +} + +// After the download: keep the longer audio. +export async function settleLandedGuard( + plan: LandedGuardPlan, + deps: LandedGuardDeps, + onLog: (s: string) => void, +): Promise<void> { + const { videoDir, asides } = plan; + if (asides.length === 0) return; + const entries = await readdir(videoDir).catch(() => [] as string[]); + const fresh = pickPreferredAudio(entries.filter(isRealAudioFile)); + const restore = async () => { + for (const name of asides) { + if (entries.includes(name)) await removeMediaFile(videoDir, name); + await renameMediaFile(videoDir, name + LANDED_KEPT_SUFFIX, name); + } + }; + if (!fresh) { + await restore(); + onLog(`No new audio: the landed ${asides.join(", ")} is back.\n`); + return; + } + const kept = pickPreferredAudio(asides) ?? asides[0]!; + const newSeconds = await deps.measure(path.join(videoDir, fresh)); + const keptSeconds = await deps.measure(path.join(videoDir, kept + LANDED_KEPT_SUFFIX)); + const newWins = + newSeconds !== null && (keptSeconds === null || newSeconds > keptSeconds + KEEP_LONGER_TOLERANCE_SECONDS); + if (newWins) { + for (const name of asides) await removeMediaFile(videoDir, name + LANDED_KEPT_SUFFIX); + } else { + for (const name of entries.filter(isRealAudioFile)) await removeMediaFile(videoDir, name); + await restore(); + } + const line = + `The download's ${fresh} (${newSeconds ?? "?"} s) against the landed ${kept} (${keptSeconds ?? "?"} s): ` + + `kept the ${newWins ? "download's" : "landed"} one.`; + onLog(`${line}\n`); + await recordChallenge(videoDir, { + at: (deps.now?.() ?? new Date()).toISOString(), + by: "download", + what: "audio", + newSeconds, + landedSeconds: keptSeconds, + kept: newWins ? "download" : "landed", + }); +} + +// Before a downloaded container is extracted and persisted: does a landed +// container in the store, as long or longer, win? Then the caller discards the +// new one (and extracts nothing from it). +export async function landedContainerWins( + videoDir: string, + newContainer: string, + deps: LandedGuardDeps, + onLog: (s: string) => void, +): Promise<boolean> { + const pointer = await loadSavedVideo(videoDir); + if (!pointer?.origin?.requestedBy || !LANDED_BY.has(pointer.origin.requestedBy)) return false; + const landedSeconds = await deps.measure(savedVideoPath(pointer)); + if (landedSeconds === null) return false; + const newSeconds = await deps.measure(newContainer); + const landedWins = newSeconds === null || newSeconds <= landedSeconds + KEEP_LONGER_TOLERANCE_SECONDS; + onLog( + `The store holds a landed ${pointer.file} (${landedSeconds} s); the download's container is ${newSeconds ?? "?"} s: ` + + `${landedWins ? "the landed one stays and the download's is discarded" : "the download's is longer and replaces it"}.\n`, + ); + await recordChallenge(videoDir, { + at: (deps.now?.() ?? new Date()).toISOString(), + by: "download", + what: "container", + newSeconds, + landedSeconds, + kept: landedWins ? "landed" : "download", + }); + return landedWins; +} diff --git a/common/ytdlp/liveSniff.mjs b/common/ytdlp/liveSniff.mjs @@ -0,0 +1,80 @@ +// FIND A LIVE PAGE'S PLAYLIST THE WAY ITS PLAYER DOES — record-live's path B +// (controller/recordLive.ts), when yt-dlp's own requests are refused. +// +// node liveSniff.mjs <monorepoRoot> <pageUrl> [waitMs] +// +// Opens the page in Chromium, keeps every .m3u8 URL the page requests, closes +// the browser and prints one JSON line: {ok, status, playlists, error?}. +// +// HEADED, UNDER A VIRTUAL DISPLAY. Measured 2026-10-22: Rumble's Cloudflare +// answers 403 to headless Chromium (old and new headless, with or without the +// operator's Firefox cookies and user agent) and 200 to a headed Chromium. So +// the caller runs this under `xvfb-run -a` (no window on the operator's +// screen) and it launches headed with `--ozone-platform=x11`. With no DISPLAY +// it falls back to headless and says so. +// +// Plain JS: run by bare `node`, Playwright resolved from the workspace package +// that installs it (editor/), as social/playwrightRuntime.ts does. + +import { createRequire } from "node:module"; +import path from "node:path"; + +const [root, pageUrl, waitRaw] = process.argv.slice(2); +const waitMs = Number(waitRaw) > 0 ? Number(waitRaw) : 12000; + +function out(o) { + process.stdout.write(`${JSON.stringify(o)}\n`); +} + +function loadChromium() { + for (const dir of [path.join(root, "editor"), path.join(root, "export"), root, process.cwd()]) { + try { + const req = createRequire(path.join(dir, "__resolve__.cjs")); + const m = req("@playwright/test"); + if (m?.chromium) return m.chromium; + } catch { + /* next */ + } + } + return null; +} + +const chromium = loadChromium(); +if (!chromium || !pageUrl) { + out({ ok: false, status: null, playlists: [], error: chromium ? "no page URL" : "Playwright is not installed in this checkout" }); + process.exit(0); +} + +const headed = Boolean(process.env.DISPLAY); +let browser = null; +const playlists = []; +try { + browser = await chromium.launch({ + headless: !headed, + args: ["--disable-blink-features=AutomationControlled", ...(headed ? ["--ozone-platform=x11"] : [])], + }); + const ctx = await browser.newContext({}); + const page = await ctx.newPage(); + page.on("request", (r) => { + const u = r.url(); + if (/\.m3u8(\?|$)/i.test(u) && !playlists.includes(u)) playlists.push(u); + }); + const res = await page.goto(pageUrl, { waitUntil: "domcontentloaded", timeout: 45000 }); + const status = res ? res.status() : null; + // The player asks for its playlist a few seconds after the page loads. + const until = Date.now() + waitMs; + while (Date.now() < until && !playlists.some((u) => /chunklist|\/media\/hls\//i.test(u))) { + await page.waitForTimeout(500); + } + out({ + ok: playlists.length > 0, + status, + playlists, + headed, + ...(playlists.length ? {} : { error: status && status >= 400 ? `the page answered HTTP ${status}` : "the page asked for no playlist" }), + }); +} catch (err) { + out({ ok: false, status: null, playlists, headed, error: String(err?.message ?? err).slice(0, 300) }); +} finally { + await browser?.close().catch(() => {}); +} diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts @@ -110,6 +110,9 @@ test("a traversing slug is refused at the door, on every route that takes one", ["persist-videos", { items: [{ slug: "../../escape", id: "abc123" }] }], ["fetch-chat", { slug: "../../escape", id: "abc123" }], ["find-clips", { slug: "../../escape", id: "abc123" }], + ["import-media", { slug: "../../escape", path: "/tmp/ops-api-never.mp4", id: "abc123" }], + ["record-live", { slug: "../../escape", url: "https://rumble.com/v1abcde-x.html" }], + ["keep-videos", { slug: "../../escape", ids: ["abc123"] }], ]; for (const [action, data] of cases) { const { status, body } = await callPost((await route(action)).POST!, data); diff --git a/editor/app/api/ops/import-media/route.ts b/editor/app/api/ops/import-media/route.ts @@ -0,0 +1,28 @@ +import { IMPORT_MEDIA_BODY_KEYS } from "yt-dlp-transcript-common/lib/mediaImport"; +import { importMediaAction } from "../../../channels/[slug]/liveMediaActions"; +import { jobResponse, ops, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, path, url? | id? | meta?: {title, date?, duration?, description?}, +// move?, replace?, audio?, transcribe?, doNotClean?, note?, dryRun? } +// -> { ok: true, jobId } +// +// A FILE FROM OUTSIDE THE ARCHIVE MADE A NORMAL TRANSCRIBED ITEM +// (controller/importMedia.ts; plans/live-capture.md): the record — `url` (one +// metadata-only pass, under the id the archive keys the page by: Rumble's URL +// id), `id` (a record already here) or `meta` (by hand) — then the landing +// record-live shares: ffprobe (an unreadable file is refused), keep the longer +// over a container already stored (`replace` lands it anyway), a `-c copy` +// remux to mp4 when it is not a stored container already (never a re-encode), +// the saved-video store, audio.<fmt>, the archive line, media-import.json. +// `move` removes the original once the landed copy verifies. `transcribe` +// queues a transcribe-one job (held by any pause). `doNotClean` sets the +// video's marker with `note`. `dryRun` says what it would do and writes +// nothing. A directory, a .zip or a .7z goes to attach-media's walk. +export async function POST(request: Request) { + return ops(request, IMPORT_MEDIA_BODY_KEYS, async (body) => { + reqSlug(body, "slug"); + return jobResponse(await importMediaAction(body)); + }); +} diff --git a/editor/app/api/ops/keep-videos/route.ts b/editor/app/api/ops/keep-videos/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; -import { keepVideosAction } from "../../../channels/[slug]/videos/[id]/videoActions"; -import { OpsInputError, ops, optBool, optString, opsFail, reqSlug, reqString } from "../_lib"; +import { keepVideoIdsAction, keepVideosAction } from "../../../channels/[slug]/videos/[id]/videoActions"; +import { OpsInputError, ops, optBool, optString, opsFail, reqSlug, reqString, reqStringArray } from "../_lib"; export const dynamic = "force-dynamic"; @@ -8,6 +8,8 @@ export const dynamic = "force-dynamic"; // -> { ok: true, pattern, fields, considered, matched: [{ id, title, // downloaded, alreadyKept, marked }], marked, alreadyKept, // notDownloaded, unscanned, noMetadata, dryRun } +// POST { slug, ids: string[], note?, dryRun? } +// -> { ok: true, ids, marked, alreadyKept, pending, pendingAll, dryRun } // // AN ADAPTER: one call to keepVideosAction, the bulk form of the video page's // "Do not clean" toggle. It writes the same per-video do-not-clean.json marker @@ -25,10 +27,29 @@ export const dynamic = "force-dynamic"; // again. A fresh channel wants `metadata-scan` FIRST — an id with no dir and no // scan entry has no text to match, and is only counted (`unscanned`). // +// `ids` NAMES VIDEOS, HELD OR NOT (plans/live-capture.md). A held one is marked +// now; one the channel does not hold yet (a live stream, a VOD not fetched) is +// recorded as PENDING in channels/<slug>/pending-keep.json and marked the moment +// its record is first written — a download, an import-media, a record-live. +// `pendingAll` lists every pending entry of the channel. +// // `dryRun: true` answers the same question and writes nothing. export async function POST(request: Request) { - return ops(request, ["slug", "match", "fields", "note", "dryRun"], async (body) => { + return ops(request, ["slug", "match", "ids", "fields", "note", "dryRun"], async (body) => { const slug = reqSlug(body, "slug"); + if (body.ids !== undefined) { + if (body.match !== undefined || body.fields !== undefined) { + throw new OpsInputError('Send "ids" or "match" (with "fields"), not both'); + } + const result = await keepVideoIdsAction({ + slug, + ids: reqStringArray(body, "ids"), + note: optString(body, "note"), + dryRun: optBool(body, "dryRun"), + }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json({ ok: true, ...result.result }); + } const pattern = reqString(body, "match"); const raw = body.fields; let fields: ("title" | "description")[] | undefined; diff --git a/editor/app/api/ops/record-live/route.ts b/editor/app/api/ops/record-live/route.ts @@ -0,0 +1,23 @@ +import { RECORD_LIVE_BODY_KEYS } from "yt-dlp-transcript-common/controller/recordLive"; +import { recordLiveAction } from "../../../channels/[slug]/liveMediaActions"; +import { jobResponse, ops, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, url? | id?, fromStart? (true), maxHeight? (720; null = tallest), +// transcribe?, doNotClean?, note?, dryRun? } -> { ok: true, jobId } +// +// A LIVE STREAM RECORDED UNTIL IT ENDS (controller/recordLive.ts; +// plans/live-capture.md): yt-dlp `--live-from-start` (Rumble's DVR playlist +// holds the stream from its start for its first 4 hours); on Rumble, when +// yt-dlp is refused, the page's own playlist found by a browser and recorded +// by ffmpeg; on Kick, the ongoing VOD polled from its first segment beside the +// channel's live stream. Then the longest part lands as the video's source, +// as import-media lands a file. One job per stream on its own queue; Cancel +// stops the recorders with SIGINT and lands what they have. +export async function POST(request: Request) { + return ops(request, RECORD_LIVE_BODY_KEYS, async (body) => { + reqSlug(body, "slug"); + return jobResponse(await recordLiveAction(body)); + }); +} diff --git a/editor/app/channels/[slug]/components/ChannelMediaTools.tsx b/editor/app/channels/[slug]/components/ChannelMediaTools.tsx @@ -6,6 +6,7 @@ import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActio import { cancelJobAction } from "../../../jobs/actions"; import { attachMediaAction } from "../attachMediaActions"; import { preparePlayableAction } from "../playableActions"; +import { ImportFileForm, RecordLiveForm } from "./LiveMediaTools"; import { readResultMarker } from "../../../lib/resultMarker"; import { MEDIA_SUMMARY_MARKER, @@ -50,6 +51,8 @@ export function ChannelMediaTools({ slug }: { slug: string }) { <details aria-label="channel media tools" className="rounded border border-border p-3"> <summary className="cursor-pointer text-sm font-semibold">Media for the whole channel</summary> <div className="mt-3 flex flex-col gap-5"> + <ImportFileForm slug={slug} /> + <RecordLiveForm slug={slug} /> <AttachArchive slug={slug} /> <PlayableCopies slug={slug} /> </div> diff --git a/editor/app/channels/[slug]/components/KeepMatchingControl.tsx b/editor/app/channels/[slug]/components/KeepMatchingControl.tsx @@ -3,8 +3,89 @@ import Link from "next/link"; import { useEffect, useState, useTransition } from "react"; import { Button } from "yt-dlp-transcript-common/components/ui/button"; -import type { KeepVideosResult } from "yt-dlp-transcript-common/controller/keepVideosMatching"; -import { keepVideosAction } from "../videos/[id]/videoActions"; +import type { KeepVideosByIdsResult, KeepVideosResult } from "yt-dlp-transcript-common/controller/keepVideosMatching"; +import type { PendingKeepEntry } from "yt-dlp-transcript-common/lib/pendingKeep-server"; +import { keepVideoIdsAction, keepVideosAction, pendingKeepAction } from "../videos/[id]/videoActions"; + +// "Keep videos by id" (plans/live-capture.md; `pnpm ops keep-videos {ids}`): +// a held video is marked now; one the channel does not hold yet — a live +// stream, a VOD not fetched — is PENDING, and marked when its record is first +// written. The channel's pending ids are listed. +export function KeepByIdControl({ slug }: { slug: string }) { + const [hydrated, setHydrated] = useState(false); + const [ids, setIds] = useState(""); + const [note, setNote] = useState(""); + const [pendingList, setPendingList] = useState<PendingKeepEntry[] | null>(null); + const [result, setResult] = useState<KeepVideosByIdsResult | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, start] = useTransition(); + useEffect(() => { + setHydrated(true); + void pendingKeepAction(slug).then(setPendingList, () => setPendingList([])); + }, [slug]); + const list = ids + .split(/[\s,]+/) + .map((s) => s.trim()) + .filter(Boolean); + const go = () => + start(async () => { + setError(null); + const res = await keepVideoIdsAction({ slug, ids: list, ...(note.trim() ? { note: note.trim() } : {}) }); + if (!res.ok) { + setError(res.error); + return; + } + setResult(res.result); + setPendingList(res.result.pendingAll); + }); + return ( + <div aria-label="keep videos by id" className="flex flex-col gap-2 rounded border border-border p-3"> + <h4 className="text-sm font-semibold">Keep videos by id</h4> + <div className="flex flex-wrap items-center gap-3 text-sm"> + <input + value={ids} + onChange={(e) => setIds(e.target.value)} + aria-label="keep ids" + placeholder="ids, e.g. v7h8pxg (held or not yet)" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-72 max-w-full" + /> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + aria-label="keep ids note" + placeholder="note (optional)" + className="rounded border border-border bg-card px-2 py-1 text-sm w-56 max-w-full" + /> + <Button type="button" size="sm" disabled={!hydrated || busy || list.length === 0} onClick={go}> + Keep them + </Button> + </div> + {error && ( + <p role="alert" className="text-xs text-destructive"> + {error} + </p> + )} + {result && ( + <p role="status" className="text-xs"> + {result.marked.length} kept now, {result.alreadyKept.length} already kept, {result.pending.length} pending (not here yet) + </p> + )} + {pendingList && pendingList.length > 0 && ( + <div className="text-xs" aria-label="pending keep ids"> + <p className="text-muted-foreground">Kept when they arrive:</p> + <ul> + {pendingList.map((e) => ( + <li key={e.id}> + <span className="font-mono">{e.id}</span> + {e.note ? ` — ${e.note}` : ""} + </li> + ))} + </ul> + </div> + )} + </div> + ); +} // "Keep videos matching" (release 32; `pnpm ops keep-videos` before it): the // do-not-clean marker on every video of the channel whose title (or diff --git a/editor/app/channels/[slug]/components/LiveMediaTools.tsx b/editor/app/channels/[slug]/components/LiveMediaTools.tsx @@ -0,0 +1,171 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { importMediaAction, recordLiveAction } from "../liveMediaActions"; + +// "Import a file" and "Record live" (plans/live-capture.md) — the forms over +// `pnpm ops import-media` and `pnpm ops record-live`, on the channel page +// (a new record: the source page's URL, or a title by hand) and on a video's +// page (this record). Import previews first (its dry run) and is armed by a +// preview of the same settings; a recording starts at once and runs until the +// stream ends — its job's Cancel stops it and lands what it has. + +const input = "rounded border border-border bg-card px-2 py-1 text-sm"; + +export function ImportFileForm({ slug, videoId }: { slug: string; videoId?: string }) { + const [file, setFile] = useState(""); + const [url, setUrl] = useState(""); + const [title, setTitle] = useState(""); + const [date, setDate] = useState(""); + const [newId, setNewId] = useState(""); + const [move, setMove] = useState(false); + const [replace, setReplace] = useState(false); + const [transcribe, setTranscribe] = useState(false); + const [keep, setKeep] = useState(false); + const [note, setNote] = useState(""); + const body = (dryRun: boolean): Record<string, unknown> => ({ + slug, + path: file.trim(), + ...(videoId ? { id: videoId } : url.trim() ? { url: url.trim() } : {}), + ...(!videoId && !url.trim() && title.trim() + ? { meta: { title: title.trim(), ...(date ? { date } : {}) }, ...(newId.trim() ? { id: newId.trim() } : {}) } + : {}), + ...(move ? { move: true } : {}), + ...(replace ? { replace: true } : {}), + ...(transcribe ? { transcribe: true } : {}), + ...(keep ? { doNotClean: true } : {}), + ...(note.trim() ? { note: note.trim() } : {}), + ...(dryRun ? { dryRun: true } : {}), + }); + const key = JSON.stringify(body(false)); + const [previewed, setPreviewed] = useState<string | null>(null); + const ready = file.trim().startsWith("/") && (Boolean(videoId) || Boolean(url.trim()) || Boolean(title.trim())); + return ( + <div className="flex flex-col gap-2" aria-label="import a file"> + <h4 className="text-sm font-semibold">Import a file</h4> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">File (absolute path; a .part or .ts recording is remuxed)</span> + <input value={file} onChange={(e) => setFile(e.target.value)} aria-label="import file path" className={`${input} w-96 max-w-full font-mono`} /> + </label> + {!videoId && ( + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Its source page (the record is read from it)</span> + <input value={url} onChange={(e) => setUrl(e.target.value)} aria-label="import source url" className={`${input} w-96 max-w-full font-mono`} /> + </label> + )} + </div> + {!videoId && !url.trim() && ( + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Or, with no source page: a title</span> + <input value={title} onChange={(e) => setTitle(e.target.value)} aria-label="import title" className={`${input} w-72 max-w-full`} /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Date</span> + <input type="date" value={date} onChange={(e) => setDate(e.target.value)} aria-label="import date" className={input} /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Id (optional: else the file name)</span> + <input value={newId} onChange={(e) => setNewId(e.target.value)} aria-label="import id" className={`${input} w-48 font-mono`} /> + </label> + </div> + )} + <div className="flex flex-wrap gap-4 text-sm"> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={move} onChange={(e) => setMove(e.target.checked)} aria-label="move the file" /> + Move (remove the original once the copy verifies) + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} aria-label="replace a longer container" /> + Replace even a longer saved container + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={transcribe} onChange={(e) => setTranscribe(e.target.checked)} aria-label="queue a transcription" /> + Queue its transcription + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} aria-label="do not clean" /> + Do not clean + </label> + <input value={note} onChange={(e) => setNote(e.target.value)} aria-label="import note" placeholder="note (optional)" className={`${input} w-56 max-w-full`} /> + </div> + <StreamActionLog + trigger={() => importMediaAction(body(true))} + cancelAction={cancelJobAction} + buttonLabel="Preview import" + runningLabel="Reading the file…" + label={`Preview import into ${slug}${videoId ? `/${videoId}` : ""}`} + disabled={!ready} + onSettled={(started) => setPreviewed(started ? key : null)} + /> + <StreamActionLog + trigger={() => importMediaAction(body(false))} + cancelAction={cancelJobAction} + buttonLabel="Import" + runningLabel="Importing…" + label={`Import into ${slug}${videoId ? `/${videoId}` : ""}`} + disabled={!ready || previewed !== key} + /> + {ready && previewed !== key && <p className="text-xs text-muted-foreground">Preview these settings first.</p>} + </div> + ); +} + +export function RecordLiveForm({ slug, videoId }: { slug: string; videoId?: string }) { + const [url, setUrl] = useState(""); + const [fromStart, setFromStart] = useState(true); + const [best, setBest] = useState(false); + const [transcribe, setTranscribe] = useState(false); + const [keep, setKeep] = useState(false); + const [note, setNote] = useState(""); + const body: Record<string, unknown> = { + slug, + ...(videoId ? { id: videoId } : { url: url.trim() }), + ...(fromStart ? {} : { fromStart: false }), + ...(best ? { maxHeight: null } : {}), + ...(transcribe ? { transcribe: true } : {}), + ...(keep ? { doNotClean: true } : {}), + ...(note.trim() ? { note: note.trim() } : {}), + }; + return ( + <div className="flex flex-col gap-2" aria-label="record live"> + <h4 className="text-sm font-semibold">Record live</h4> + {!videoId && ( + <label className="flex flex-col gap-0.5 text-sm"> + <span className="text-xs text-muted-foreground">The live stream&apos;s page (a Rumble video, a Kick channel or its VOD)</span> + <input value={url} onChange={(e) => setUrl(e.target.value)} aria-label="live stream url" className={`${input} w-96 max-w-full font-mono`} /> + </label> + )} + <div className="flex flex-wrap gap-4 text-sm"> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={fromStart} onChange={(e) => setFromStart(e.target.checked)} aria-label="record from the start" /> + From the start + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={best} onChange={(e) => setBest(e.target.checked)} aria-label="best quality" /> + Tallest quality (else 720p) + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={transcribe} onChange={(e) => setTranscribe(e.target.checked)} aria-label="queue a transcription when it ends" /> + Queue its transcription when it ends + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} aria-label="do not clean the recording" /> + Do not clean + </label> + <input value={note} onChange={(e) => setNote(e.target.value)} aria-label="record note" placeholder="note (optional)" className={`${input} w-56 max-w-full`} /> + </div> + <StreamActionLog + trigger={() => recordLiveAction(body)} + cancelAction={cancelJobAction} + buttonLabel="Record live" + runningLabel="Recording…" + label={`Record live into ${slug}${videoId ? `/${videoId}` : ""}`} + disabled={!videoId && !/^https?:\/\//.test(url.trim())} + /> + </div> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx @@ -1,7 +1,7 @@ "use client"; import { useState } from "react"; -import { KeepMatchingControl } from "../KeepMatchingControl"; +import { KeepByIdControl, KeepMatchingControl } from "../KeepMatchingControl"; import { ChannelMediaTools } from "../ChannelMediaTools"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; @@ -71,6 +71,7 @@ export function CleanupStage({ return ( <div className="flex flex-col gap-6"> <KeepMatchingControl slug={slug} /> + <KeepByIdControl slug={slug} /> {(keepLatest > 0 || savedCount > 0) && ( <RetentionSection slug={slug} diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts @@ -0,0 +1,91 @@ +"use server"; + +// A FILE OR A LIVE STREAM MADE A NORMAL TRANSCRIBED ITEM (plans/live-capture.md): +// +// importMediaAction `pnpm ops import-media`, "Import a file" on the channel +// and video pages — controller/importMedia.ts. A +// directory, a .zip or a .7z goes to attach-media's walk +// instead (attachMediaAction). +// recordLiveAction `pnpm ops record-live`, "Record live" — controller/ +// recordLive.ts. +// +// Both land through controller/landMedia.ts, and with `transcribe: true` ask +// for a transcribe-one job (whisperVideoAction) once the audio is in place — +// held by any pause like every transcription; nothing here lifts one. +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +import { stat } from "node:fs/promises"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy"; +import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport"; +import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia"; +import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { attachMediaAction } from "./attachMediaActions"; +import { whisperVideoAction } from "./videos/[id]/videoActions"; + +const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +async function requestTranscription(slug: string, id: string): Promise<{ ok: boolean; jobId?: string; error?: string }> { + const r = await whisperVideoAction(slug, id); + if (!r.ok) return { ok: false, error: r.error }; + void r.stream.cancel(); + return { ok: true, jobId: r.jobId }; +} + +export async function importMediaAction(body: Record<string, unknown>): Promise<StreamActionResult> { + const req = parseImportRequest(body); + if ("error" in req) return { ok: false, error: req.error }; + if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, req.slug); + if (!config) return { ok: false, error: `Channel "${req.slug}" not found` }; + const st = await stat(req.path).catch(() => null); + if (!st) return { ok: false, error: `${req.path} is not there` }; + if (isArchivePath(req.path, st.isDirectory())) { + // A directory or an archive: attach-media's walk finds the file(s). + if (req.url || req.meta || req.move || req.audio === false || req.transcribe || req.doNotClean) { + return { + ok: false, + error: + `${req.path} is a directory or an archive: it is attached by attach-media's walk, which takes "id" (or none), ` + + `"replace" and "dryRun" only — import one file from it to give "url", "meta", "move" or the rest`, + }; + } + return attachMediaAction(req.slug, { + source: req.path, + ...(req.id ? { match: escapeRegex(req.id) } : { createRecords: true }), + ...(req.replace ? { replace: true } : {}), + ...(req.dryRun ? { dryRun: true } : {}), + }); + } + return runImportMediaJob({ + paths, + request: req, + channelConfig: config, + cookiePolicy: resolveCookiePolicy(getSettings(), config), + requestTranscription, + afterRun: () => safeRevalidate([`/channels/${req.slug}`, `/channels/${req.slug}/videos/${req.id ?? ""}`]), + }); +} + +export async function recordLiveAction(body: Record<string, unknown>): Promise<StreamActionResult> { + const req = parseRecordLiveRequest(body); + if ("error" in req) return { ok: false, error: req.error }; + if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, req.slug); + if (!config) return { ok: false, error: `Channel "${req.slug}" not found` }; + return runRecordLiveJob({ + paths, + request: req, + channelConfig: config, + cookiePolicy: resolveCookiePolicy(getSettings(), config), + requestTranscription, + afterRun: () => safeRevalidate([`/channels/${req.slug}`]), + }); +} diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx @@ -5,6 +5,7 @@ import { useEffect, useState, useTransition } from "react"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { Button } from "yt-dlp-transcript-common/components/ui/button"; import { cancelJobAction } from "../../../../../jobs/actions"; +import { ImportFileForm, RecordLiveForm } from "../../../components/LiveMediaTools"; import { archiveOrgRefreshAction, attachVideoMediaAction, @@ -41,6 +42,8 @@ export function VideoMediaTools({ <details aria-label="media tools" className="rounded-lg border border-border bg-card p-3"> <summary className="cursor-pointer text-sm font-semibold">Media tools</summary> <div className="mt-3 flex flex-col gap-4"> + <ImportFileForm slug={slug} videoId={videoId} /> + <RecordLiveForm slug={slug} videoId={videoId} /> <AttachFromArchive slug={slug} videoId={videoId} saved={saved} /> <div className="flex flex-col gap-2"> <h4 className="text-sm font-semibold">Live chat replay</h4> diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -35,9 +35,12 @@ import { windowInFlight } from "yt-dlp-transcript-common/jobs/windowJobs"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { setDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server"; +import { loadPendingKeep, type PendingKeepEntry } from "yt-dlp-transcript-common/lib/pendingKeep-server"; import { KeepVideosError, + keepVideosByIds, keepVideosMatching, + type KeepVideosByIdsResult, type KeepVideosField, type KeepVideosResult, } from "yt-dlp-transcript-common/controller/keepVideosMatching"; @@ -1060,6 +1063,44 @@ export async function keepVideosAction(input: { return { ok: true, result }; } +// KEEP THESE IDS (keep-videos {ids}): a held video is marked now; one the +// channel does not hold yet is recorded as pending and marked when its record +// is first written (common/lib/pendingKeep-server.ts). +export async function keepVideoIdsAction(input: { + slug: string; + ids: string[]; + note?: string; + dryRun?: boolean; +}): Promise<{ ok: true; result: KeepVideosByIdsResult } | { ok: false; error: string }> { + let result: KeepVideosByIdsResult; + try { + result = await keepVideosByIds({ + paths: getPaths(), + channelSlug: input.slug, + ids: input.ids, + note: input.note, + dryRun: input.dryRun, + }); + } catch (e) { + if (e instanceof KeepVideosError || e instanceof ChannelMediaUnreachableError) { + return { ok: false, error: e.message }; + } + throw e; + } + if (!result.dryRun && (result.marked.length > 0 || result.pending.length > 0)) { + for (const id of result.marked) revalidatePath(`/channels/${input.slug}/videos/${id}`); + revalidatePath(`/channels/${input.slug}`); + if (result.marked.length > 0) requestChannelSnapshot(getPaths(), input.slug); + } + return { ok: true, result }; +} + +// The channel's pending "Do not clean" entries (ids asked for before their +// records existed). +export async function pendingKeepAction(slug: string): Promise<PendingKeepEntry[]> { + return loadPendingKeep(getPaths(), slug); +} + // Opt this video in/out of the truncated/incomplete-transcript check. When // enabled, the snapshot's incompleteTranscript + shortAudio buckets and the // video panel's "looks truncated" banner suppress this id (for videos that diff --git a/editor/e2e/fixtures/bin/fake-ffmpeg.mjs b/editor/e2e/fixtures/bin/fake-ffmpeg.mjs @@ -93,5 +93,16 @@ if (out === "/dev/null") { process.exit(0); } +// A STREAM-COPY REMUX (`-c copy … -f mp4|matroska`, the landing's finalize — +// controller/landMedia.ts): the same bytes, the `__FORMAT=…__` marker now the +// output's, so fake-ffprobe reads the copy as the same length in its new box. +if (arg("-c") === "copy" && srcBuf) { + const to = arg("-f") === "matroska" ? "matroska,webm" : "mov,mp4,m4a,3gp,3g2,mj2"; + const text = srcBuf.toString("utf8"); + await writeFile(out, /__FORMAT=[\w,]+__/.test(text) ? text.replace(/__FORMAT=[\w,]+__/, `__FORMAT=${to}__`) : `__FORMAT=${to}__ ${text}`); + process.stdout.write(`[fake-ffmpeg] remuxed ${src} -> ${out}\n`); + process.exit(0); +} + await writeFile(out, `fake-ffmpeg transcoded from ${src}\n`); process.stdout.write(`[fake-ffmpeg] wrote ${out}\n`); diff --git a/editor/e2e/fixtures/bin/fake-ffprobe.mjs b/editor/e2e/fixtures/bin/fake-ffprobe.mjs @@ -30,6 +30,27 @@ async function main() { const m = buf.match(/__DUR=([0-9]+(?:\.[0-9]+)?)__/); // No marker -> report a long duration so isShortAudio() stays false. const seconds = m ? m[1] : "100000"; + // `-show_format -show_streams -of json` (the landing's probe, + // controller/landMedia.ts): the format a `__FORMAT=<name>__` marker names + // (default an mp4), one h264 and one aac stream. `__NOTMEDIA__` is a file + // ffprobe cannot read. + if (argv.includes("-show_format")) { + if (buf.includes("__NOTMEDIA__")) { + process.stderr.write(`${file}: Invalid data found when processing input\n`); + process.exit(1); + } + const f = buf.match(/__FORMAT=([\w,]+)__/); + process.stdout.write( + JSON.stringify({ + format: { format_name: f ? f[1] : "mov,mp4,m4a,3gp,3g2,mj2", duration: seconds }, + streams: [ + { codec_type: "video", codec_name: "h264" }, + { codec_type: "audio", codec_name: "aac" }, + ], + }) + "\n", + ); + return; + } process.stdout.write(`${seconds}\n`); } diff --git a/editor/e2e/live-capture.spec.ts b/editor/e2e/live-capture.spec.ts @@ -0,0 +1,83 @@ +import { test, expect } from "@playwright/test"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { channelStage, resetData, testPaths } from "./helpers"; + +// plans/live-capture.md: the video page's "Import a file" — a recording made by +// hand (an MPEG-TS `.part`) previewed, then landed as the video's source: the +// saved-video store, audio, media-import.json, the "Do not clean" marker, the +// original moved. And the channel's "Keep videos by id" recording an id the +// channel does not hold yet as pending. Synthetic files; the fake ffprobe +// reads `__FORMAT=…__` / `__DUR=…__` markers and the fake ffmpeg's remux +// copies them. Nothing is fetched. + +const SLUG = "test-transcribe"; // an Odysee channel (one-transcribe-channel) +const ID = "v9import01"; +const channelDir = () => join(testPaths().transcriptsDir, "channels", SLUG); + +test.beforeEach(async () => { + await resetData("one-transcribe-channel"); +}); + +test("Import a file: previewed, then landed as the video's source with its audio, kept, the original moved", async ({ page: p }) => { + test.setTimeout(90_000); + const dir = join(channelDir(), "data", ID); + await mkdir(dir, { recursive: true }); + await writeFile( + join(dir, "metadata.info.json"), + // The page URL names this id (an Odysee claim id is what follows the + // last ":"), so the snapshot's reconcile pass leaves the dir where it is. + JSON.stringify({ id: ID, title: `Synthetic ${ID}`, webpage_url: `https://odysee.com/@example:1/synthetic:${ID}`, duration: 1200 }), + ); + // Outside the channel and the store: a recording made by hand. + const srcDir = join(testPaths().transcriptsDir, "import-src"); + await mkdir(srcDir, { recursive: true }); + const src = join(srcDir, "stream.from-start.mp4.part"); + await writeFile(src, "__FORMAT=mpegts__ __DUR=1200__ synthetic recording bytes\n"); + + await p.goto(`/channels/${SLUG}/videos/${ID}`); + const tools = p.getByRole("group", { name: "media tools" }); + await tools.locator("summary").click(); + const form = tools.getByLabel("import a file"); + await expect(form.getByRole("button", { name: "Import", exact: true })).toBeDisabled(); + await form.getByLabel("import file path").fill(src); + await form.getByLabel("move the file").check(); + await form.getByLabel("do not clean").check(); + await form.getByLabel("import note").fill("keep this one"); + await form.getByRole("button", { name: "Preview import" }).click(); + const preview = form.getByRole("log", { name: `Preview import into ${SLUG}/${ID} output`, exact: true }); + await expect(preview).toContainText("remuxed", { timeout: 30_000 }); + await expect(preview).toContainText("dry run"); + // A dry run lands nothing and moves nothing. + expect(await readdir(dir)).not.toContain("saved-video.json"); + await readFile(src); + + await expect(form.getByRole("button", { name: "Import", exact: true })).toBeEnabled(); + await form.getByRole("button", { name: "Import", exact: true }).click(); + const run = form.getByRole("log", { name: `Import into ${SLUG}/${ID} output`, exact: true }); + await expect(run).toContainText("@@import-media", { timeout: 30_000 }); + await expect(run).toContainText("Stored"); + + const pointer = JSON.parse(await readFile(join(dir, "saved-video.json"), "utf8")); + expect(pointer.file).toBe("source-media.mp4"); + expect(pointer.origin.requestedBy).toBe("import-media"); + const prov = JSON.parse(await readFile(join(dir, "media-import.json"), "utf8")); + expect(prov.entries[0].source.name).toBe("stream.from-start.mp4.part"); + expect(prov.entries[0].finalized).toBe("remuxed"); + expect(prov.entries[0].kept).toBe("new"); + expect(await readdir(dir)).toEqual(expect.arrayContaining(["do-not-clean.json"])); + expect((await readdir(dir)).some((n) => /^audio\./.test(n))).toBe(true); + expect(await readdir(srcDir)).toEqual([]); +}); + +test("Keep videos by id: a video the channel does not hold yet is pending, and listed", async ({ page: p }) => { + await p.goto(channelStage(SLUG, "cleanup")); + const box = p.getByLabel("keep videos by id"); + await box.getByLabel("keep ids", { exact: true }).fill("v9notyet01"); + await box.getByLabel("keep ids note").fill("keep when it lands"); + await box.getByRole("button", { name: "Keep them" }).click(); + await expect(box.getByRole("status")).toContainText("1 pending (not here yet)"); + await expect(box.getByLabel("pending keep ids")).toContainText("v9notyet01 — keep when it lands"); + const pending = JSON.parse(await readFile(join(channelDir(), "pending-keep.json"), "utf8")); + expect(pending.entries.map((e: { id: string }) => e.id)).toEqual(["v9notyet01"]); +}); diff --git a/plans/live-capture.md b/plans/live-capture.md @@ -0,0 +1,131 @@ +# Live capture — record a live stream from its start; import a file (lane `lane/live-capture`) + +Asked by the operator on 2026-10-22: start downloading a currently active Rumble stream (and the Kick workaround of +downloading the channel and the VOD at the same time), from the stream's start; then "the ability to take an +external archive and turn it into a transcribed item … in general, not just a one-off"; then keep markers for a +video that is not here yet. + +## Findings (measured 2026-10-22) + +**Rumble.** The embed JSON of a live DVR stream (`live: 2`, `livestream_has_dvr: true`) names one HLS master, +`https://rumble.com/live-hls-dvr/<key>/playlist.m3u8`, whose variants are `chunklist[_<q>]_i0_DVR.m3u8` on +`*.cdn.rumble.cloud`. A DVR media playlist has no `EXT-X-PLAYLIST-TYPE`, 2-second segments +(`media_<sid>_<q>_<n>.ts`) and starts at `EXT-X-MEDIA-SEQUENCE:1` — the broadcast's first segment. + +| Stream | Elapsed | Playlist | Holds | +|---|---|---|---| +| v7h8pxg (The Quartering) | 18 min | seq 1 … 550, 1100 s | the whole stream; segment 1 served (200) | +| v7h7ktg (LFA TV, ~7 h) | ~7 h | seq 5313 … 12511, 7199 segments | the last 4 h (window starts 4 h before now) | +| v35waq4 (RT, 24/7) | days | seq 70054 … 77255, 7202 segments | the last 4 h | + +- **The DVR playlist reaches the start for a stream under ~4 hours old**; past that it is a sliding window of + ~7200 segments (4 h). The non-DVR chunklist holds ~2 minutes. +- Segments older than the window are still served for a while: on LFA the first served segment rolled from 327 to + 352 over ~100 s, ~6.8 h behind the live edge. Not used (see Owed). +- The master and the CDN chunklists answer a plain request with a browser UA (no cookies, no Cloudflare); + `rumble.com` pages and the embed JSON are behind Cloudflare (yt-dlp needs `--impersonate`). +- yt-dlp downloads live HLS with its ffmpeg downloader; ffmpeg's hls demuxer starts at `live_start_index -3` — + why a by-hand recording "started from the point I started". With `-live_start_index 0` it starts at the first + listed segment (verified: the patched fork opened `media_…_360p_1.ts`; the operator's own + `--downloader-args "ffmpeg_i:-live_start_index 0"` recording "worked"). +- A browser fallback: Rumble's Cloudflare answers **403** to headless Chromium (old and new headless, with or + without the operator's Firefox cookies and UA) and **200** to a headed Chromium under `xvfb-run`, which sees + the master playlist. Playwright's Firefox is not installed for the workspace's version. + +**Kick.** The channel's live playlist (IVS, `playback_url`) holds ~30 s (6 s segments). The ongoing stream's VOD +(`kick.com/<channel>/videos/<uuid>`; the uuid is the livestream's id in `web.kick.com/api/v1/livestreams`) 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 (and yt-dlp, which treats the VOD as live) reads one +snapshot and stops — the operator's VOD download stops at "now", hence the second download of the channel. +Polling the VOD playlist and appending each new segment records the whole stream in one file. + +## Rulings + +- **The fork** (`~/Projects/yt-dlp-patched`, branch `live-from-start`, fast-forwarded into `patched`): + `RumbleEmbedIE` marks a live stream's HLS formats `is_from_start` with `downloader_options.ffmpeg_args = + ['-live_start_index', '0']` when `--live-from-start` is passed and the stream has DVR (`livestream_has_dvr`, or + a `live-hls-dvr` / `_DVR.m3u8` URL) — the Twitch/openrec idiom. Without `--live-from-start` nothing changes; a + stream without DVR with it is yt-dlp's own "no formats that can be downloaded from the start". Test: + `test/test_rumble_live.py`. Local only, never upstreamed. +- **record-live** (`common/controller/recordLive.ts`, job `record-live`, `needsMedia`, queue + `record-live:<slug>:<id>`, never a platform's queue, never the heavy slot): `{slug, url | id, fromStart (true), + maxHeight (720; null = tallest), transcribe?, doNotClean?, note?, dryRun?}`. + - The record first: `data/<id>/` and one `refreshVideoMetadata` pass (writer `refresh`, requestedBy + `record-live`). The id is `dataDirIdForUrl` — Rumble's URL id (`v7h8pxg`), not the embed id the metadata + carries (`v7f2czy`). A Kick channel URL is resolved to its ongoing VOD (`yt-dlp --flat-playlist + --playlist-items 1 kick.com/<ch>/videos`); the VOD uuid is the id. Not `is_live`/`is_upcoming`/`post_live` + → refused. + - Path A: `yt-dlp --live-from-start` with the channel's args (cookies, Rumble's impersonation, the pinned UA), + `--downloader-args "ffmpeg_i:-live_start_index 0 -m3u8_hold_counters 180 -seg_max_retry 10"`, + `--hls-use-mpegts --no-part --fixup never`, `-f best[height<=720]/best`, `--wait-for-video 60` only for an + upcoming stream. yt-dlp answering "no formats … from the start" → once more with `--no-live-from-start` + (ffmpeg still told index 0). + - Path B (Rumble, when the metadata pass or path A is refused — 403/Unable to extract): `liveSniff.mjs` under + `xvfb-run -a` (headed Chromium), through the heavy slot with `--estimate 1000`; the master's variant by + height (fetched plainly), else the page's DVR chunklist; ffmpeg `-live_start_index 0 -c copy -f mpegts` with + reconnect and segment retries. + - Kick: the VOD poller (`pollEventPlaylist`, every 20 s, three tries a segment, a missing one a counted gap) + and, beside it, yt-dlp on `kick.com/<channel>` (`--no-live-from-start`). The poller ends 2 min after the live + lane ends without growth, or after 10 min without growth. + - Parts are MPEG-TS staging files `.<id>.live-<stamp>.<tag>.ts` beside the store dir (the store's disk; its + root must exist, not be mid-move, and have ≥ 20 GB free). When the stream ends the metadata is read again and + the LONGEST part — with any an interrupted run left — is landed; the rest are removed. + - Cancel: the recorders get SIGINT (yt-dlp asks its ffmpeg to `q`), SIGKILL after 60 s; what was recorded is + landed, the job ends `cancelled`. Progress lines are thinned to one per 5 minutes in the log. + - `live-recording.json` beside the record: status, url, platform, parts (method, url, fromStart, times, + seconds, bytes, note), the landed part, what the landing kept, the playlist's reach. +- **import-media** (`common/controller/importMedia.ts`, job `import-media`, `needsMedia`, queue + `import-media:<slug>`): `{slug, path, url | id | meta {title, date?, duration?, description?}, move?, replace?, + audio?, transcribe?, doNotClean?, note?, dryRun?}`. `url` makes or refreshes the record (one metadata-only pass; + a held or cooling platform refuses a NEW record before any job, an existing one lands without the refresh); + `meta` writes a record by hand (`extractor: "import"`, history writer `import-media`), id = `id` or the file's + name, never over an existing record. A directory, .zip or .7z goes to attach-media (`id` → `match`, else + `createRecords`). +- **The landing** (`common/controller/landMedia.ts`, shared): ffprobe — unreadable or no audio → refused; a file + inside `channels/` or the store → refused (import); KEEP THE LONGER over a stored container (2 s slack, a tie + and an unmeasurable store keep what is there; `replace` overrides); finalize into `.<id>.land-<pid>.part` on the + store's disk — attach-media's hashed copy (`copyFileHashed`; a rename when `move` on the same disk) or `-c copy` remux (mp4 +faststart; mkv when mp4 + cannot hold the codecs) through the heavy slot; verify bytes (copy) or ffprobe + length (remux); + `persistSourceVideo` (`source-media.<ext>`, `keepReason: "pin"`, `origin.requestedBy` import-media|record-live); + `move` removes the original only after the verify; `audio.<fmt>` (channel's format, mp3 default) by + `transcodeAudio` from the stored container (the tier hook runs there) when there is none or the one there is + shorter (a shorter one of another name is removed with `removeMediaFile`); the channel's `archive` gains + `<extractor> <id>` (not for a record by hand); `media-import.json` gains the entry (source path, original name, + bytes, moved, url, finalized, container, kept, existingSeconds, audio, note; 50 kept). +- **import-media composes the existing steps** — the record by `refreshVideoMetadata` (the refresh-metadata op's + pass, into a new `data/<id>/`), the container by attach-media's copy and provenance (`copyFileHashed`, pointer + origin `{kind: "local-archive", archive: <dir>, entry: <file>, sha256, attachedAt}` with `requestedBy: + "import-media"`) through `persistSourceVideo`, the marker by `setDoNotClean` (keep-videos' writer); a directory or + archive is attach-media itself. Its own: one FILE path, the `.part`/`.ts` remux, `move` after the verify, keep the + longer, audio, the pending keep marker. A container attach-media attached is protected by the same guard as an + imported one (`requestedBy: "attach-media"` counts as landed). +- v7h8pxg (the 2026-10-22 recording) was attached by hand before this lane (attach-media + refresh-metadata + + keep-videos): nothing to import. +- **The hand-off**: the log says what takes the audio — the transcription lane's rules (a leaf matching the + channel), or that it does not — and names every hold (workers paused, lane held, channel paused). Nothing lifts a + pause. `transcribe: true` queues `whisper-video` (the video page's Transcribe), held like any. +- **A later download never clobbers a longer landed recording** (`common/ytdlp/landedGuard.ts`): for a video with + a landed entry (or a pointer whose origin is import-media/record-live), downloadOneManaged sets its real audio + aside (`.landed-kept`, a scratch name) and keeps the longer after the download; finalizeAppExtraction discards a + downloaded container that is not longer than the landed one (and extracts nothing from it). Each decision is a + `challenges` entry in media-import.json. +- **Keep markers ahead of the record**: `keep-videos {slug, ids, note?, dryRun?}` marks a held id now; an id not + held is PENDING in `channels/<slug>/pending-keep.json` (`{entries: [{id, note, at}]}`) and marked when its + record is first written — after every managed download (downloadOneManaged), an import-media landing, a + record-live landing (`applyPendingKeep`, which drops the entry). `pendingAll` and the channel's Cleanup stage + (**Keep videos by id**) list them. `doNotClean: true` + `note` on import-media and record-live set the marker. +- UI: channel page → Media for the whole channel → **Import a file**, **Record live**; video page → Media tools → + the same two for that record; Cleanup stage → **Keep videos by id**. The UI does not list live items, so there + is no per-item live button. + +## Owed + +- Rumble beyond the 4 h window: segments older than the playlist's window stay served ~6.8 h (rolling); a backfill + that enumerates `media_<sid>_<q>_<n>.ts` below the window's first sequence and prepends them was not built. +- A recording is a job of the editor's process: an editor restart (graceful) cancels it — the recorder gets + SIGINT and the part stays on the store's disk; the next `record-live` of the stream lands the longest of all + parts (from the start again, while the DVR window still holds it). A restart that kills the process outright + leaves the part too. +- The e2e covers Import a file and Keep videos by id; Record live is covered by unit tests only (no fake live + yt-dlp in the fixtures). +- attach-media (a directory/archive) lands containers without audio; an import of one file does both. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -42,6 +42,11 @@ // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait +// pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait +// pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait +// pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}' +// pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}' +// pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}' // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}' // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait @@ -364,6 +369,14 @@ const ACTIONS = [ // directory, a zip read in place, a 7z ({slug, source, items?, match?, // createRecords?, replace?, dryRun?}): one job, nothing fetched. "attach-media", + // ONE FILE FROM OUTSIDE THE ARCHIVE MADE A NORMAL TRANSCRIBED ITEM, and A + // LIVE STREAM RECORDED from its start (plans/live-capture.md): import-media + // ({slug, path, url? | id? | meta?, move?, replace?, audio?, transcribe?, + // doNotClean?, note?, dryRun?}) and record-live ({slug, url? | id?, + // fromStart?, maxHeight?, transcribe?, doNotClean?, note?, dryRun?}), each a + // job; both land through the same code. + "import-media", + "record-live", // A channel's saved containers remuxed losslessly into browser-playable // copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}). "prepare-playable", @@ -1161,7 +1174,11 @@ export function usage() { ' channel whose title or description matches a download-filter pattern:', ' {"slug", "match", "fields"?: ["title" | "description"], "note"?,', ' "dryRun"?}. A match not held is reported in "notDownloaded", never', - " created; a fresh channel wants metadata-scan first.", + " created; a fresh channel wants metadata-scan first. Or by id:", + ' {"slug", "ids": [...], "note"?, "dryRun"?} — a held video is marked now,', + " one not held yet (a live stream, a VOD not fetched) is PENDING and marked", + " when its record is first written (a download, an import, a recording);", + ' "pendingAll" lists the channel\'s pending ids.', "", 'channel-config changes a channel as its Configure form does: {"slug"} and', ' any of "patch" (form field names; "" clears one), "sites" (the WHOLE', @@ -1370,6 +1387,33 @@ export function usage() { " ambiguous) and the held videos with no media in it, and writes nothing.", " The log ends with a summary: line; a re-run resumes.", "", + 'import-media makes ONE file from outside the archive a normal transcribed', + ' item: {"slug", "path"} (absolute) and which record — "url" (the source', + " page: one metadata-only pass makes or refreshes the record, under the id", + ' the archive keys it by — Rumble\'s URL id), "id" (a record already here)', + ' or "meta": {"title", "date"?, "duration"?, "description"?} (by hand).', + " ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to", + " mp4 (+faststart), never re-encoded. It lands in the saved-video store", + " only when longer than a container already there (\"replace\": true lands", + ' it anyway), then audio.<fmt>, the archive line and media-import.json.', + ' "move": true removes the original once the copy verifies; "audio":', + ' false lands the container only; "transcribe": true queues a', + ' transcribe-one job (held by any pause; without it the transcription lane', + ' takes it by its rules); "doNotClean": true marks it, with "note".', + ' "dryRun": true says what it would do and writes nothing. A directory, a', + ' .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only).', + "", + 'record-live records a live stream until it ends, then lands it as', + ' import-media lands a file: {"slug", "url"} (or "id" of a record here),', + ' "fromStart"? (true: yt-dlp --live-from-start — Rumble\'s DVR playlist', + ' holds a stream\'s first 4 hours), "maxHeight"? (720; null = the tallest),', + ' "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused', + " yt-dlp falls back to the page's own playlist (a browser under xvfb, then", + ' ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is', + " polled from its first segment beside the channel's live stream. One job", + " per stream; job cancel stops it with SIGINT and lands what it has; the", + " longest part wins. Refused for a stream that is not live.", + "", 'prepare-playable remuxes each of a channel\'s saved containers, losslessly', ' (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes', ' one single-file torrent per copy, under playable/ beside the saved-video',