Archilyzer · Source

archilyzer

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

commit 401a7097de8bbc68732db7dd7584284e152e5222
parent 59a17713f344255baad3b1a188d3789bdc00364a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 20:59:51 -0500

compact-saved-videos: re-encode a saved video to AV1, verified, resumable

A deliberately stored container (a pin, an explicit persist, a requested or
landed one; never keep-latest) is re-encoded with SVT-AV1 (settings
savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's
height, Kick and Twitch above 30 fps to 30, every audio stream copied) in
keyframe-aligned chunks under the store's own .compact-scratch/, each chunk one
heavy-slot admission (1.5 GB, niced, waiting for render mode), its frame count
checked, its state recorded so a cancel, a drain or a restart resumes. The disk
floor is checked before the first chunk and before each one.

The re-encode becomes the active copy, under its own name, only when every
check passes: a full decode, the length within a frame, the frame count the fps
change gives, the audio packets identical, VMAF (SSIM without libvmaf) on
excerpts spread through the file, windows cut through the evidence cutter from
both copies, and the recording clock re-measured against it. A failure leaves
the original active and untouched and records why. The swap is one locked
pointer write, only if the pointer still names the encoded bytes. Then, each a
step of its own: the copy is read back from disk, and under dropOriginal
"after-verify" the original is dropped -- never for a video not known to be on
its platform, which waits for a person's review.

The ops action (an explicit list or the selector: platform, height, video
bitrate; dryRun prints each line with its estimate and disk), the job kind on
one `compact` queue, its replay, `get compaction-review`,
`review-compacted-original`, drop-saved-alternate's confirmOriginal; the video
page and /saved-videos say a copy is a re-encode and carry the review; the
channel opt-out excludeFromCompaction; SETTINGS.md, CHANNEL.md, COMMANDS.md,
OPERATING.md and the changelog.

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

Diffstat:
MCHANNEL.md | 1+
MCOMMANDS.md | 11++++++++++-
MOPERATING.md | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MSETTINGS.md | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/compactSavedVideos.test.ts | 675+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/compactSavedVideos.ts | 1104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 20++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 4++++
Mcommon/lib/channelConfigSchema.ts | 1+
Acommon/lib/compactMedia-server.ts | 518+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 5+++++
Meditor/CHANGELOG.md | 14++++++++++++++
Aeditor/app/api/ops/compact-saved-videos/route.test.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/compact-saved-videos/route.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/compaction-review/route.ts | 33+++++++++++++++++++++++++++++++++
Meditor/app/api/ops/drop-saved-alternate/route.ts | 12+++++++++---
Aeditor/app/api/ops/review-compacted-original/route.ts | 25+++++++++++++++++++++++++
Meditor/app/api/ops/saved-alternates/route.ts | 4+++-
Meditor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx | 113++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 35++++++++++++++++++++++++++++++++---
Meditor/app/jobs/jobReplayRegistry.ts | 16++++++++++++++++
Aeditor/app/saved-videos/compactActions.ts | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/saved-videos/page.tsx | 43+++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
Msettings.json.example | 23+++++++++++++++++++++++
27 files changed, 3141 insertions(+), 24 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -43,6 +43,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `remoteArchive` | config | A remote-only channel's archive: the origin whose corpus.json names it. | | `remoteUrl` | config | A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: a remote-only channel has no `url`, so nothing syncs it. | | `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. | +| `excludeFromCompaction` | config | Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false. | | `cleanAfterCaptureUnverified` | config | Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel ("no source to check: clean by hand") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held. | | `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. | | `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -156,6 +156,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, &lt;id&gt;-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/&lt;id&gt;/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` | | `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (&lt;id&gt;-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` | | `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. | | +| `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, the audio copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: pinned, an explicit persist, a requested or landed container -- never a keep-latest one); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs against what is free, or why it is skipped -- and starts nothing. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true runs one whose last checks failed. One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a re-run resumes. Under dropOriginal "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not known to be on its platform (get compaction-review). | | +| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy: {"slug", "id", "note"?}. It changes nothing on disk; it is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not known to be on its platform. | | | `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` | | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | @@ -199,7 +201,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | -| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. | | +| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes, and a video not known to be on its platform needs its review recorded first. | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | | `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` | | `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -&gt; {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | @@ -251,6 +253,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get settings [<key>] pnpm ops get storage | sites | workers | auto-queue | scheduler pnpm ops get saved-alternates [<slug>] + pnpm ops get compaction-review [<slug>] pnpm ops get services pnpm ops get x-session [<slug>] pnpm ops get x-run [<run id>] @@ -309,6 +312,12 @@ get saved-alternates [<slug>] lists every saved video holding two copies: replaced). Each video: its line, the active copy, the alternates (height, seconds, origin, keptAs). Once one is checked, `drop-saved-alternate` deletes it. +get compaction-review [<slug>] lists every compacted saved video and what + its original waits for: "awaiting-review" (not known to be on its + platform: a person reviews the compacted copy first, with + review-compacted-original), "reviewed", "kept" (dropOriginal "keep"), + "drop-pending" or "dropped". Each: its line (a re-encode, of what, how), + availability, the original's entry, sizes, checks and the re-check. get sites lists every site: id, title, siteUrl, Pages project, audience, listed, search, publish policy, channels, citedChannels. (`get publish` is the status.) diff --git a/OPERATING.md b/OPERATING.md @@ -1133,6 +1133,65 @@ pnpm wt prune --dry-run [--json] # w - **Not done by it**: the clip-window cache (`evict-clips`: re-fetching is paced), a project's only preview, other sessions' job directories, anything under `transcripts/`. +### Compact saved videos + +```sh +pnpm ops compact-saved-videos --json '{"select":true,"dryRun":true}' # what the selector picks, each with its estimate +pnpm ops compact-saved-videos --json '{"items":[{"slug":"example","id":"<videoId>"}],"dryRun":true}' +pnpm ops compact-saved-videos --json '{"items":[{"slug":"example","id":"<videoId>"}]}' --wait +pnpm ops get compaction-review # what each original waits for +pnpm ops review-compacted-original --json '{"slug":"example","id":"<videoId>","note":"watched it"}' +pnpm ops drop-saved-alternate --json '{"slug":"example","id":"<videoId>","file":"source-media.mp4","confirmOriginal":true}' +``` + +- **What it does.** A saved container is re-encoded to AV1: SVT-AV1 preset 8, crf 36, a keyframe every 5 s, the + source's height, every audio stream copied bit for bit. Kick and Twitch above 30 fps go to 30. The re-encode + becomes the active copy under its own name, `source-media.compact-av1-<stamp>.mp4`, never the original's: the + backup mirror is additive, and the same name would overwrite the backed-up original. The original stays beside it + as the alternate `"keptAs": "original"`. The pointer's `compacted` block records the source (sha256, bytes, + height, fps, codec, bitrate), the encoder and its settings, and every check's numbers. The video page, /saved-videos, + `get saved-alternates` and a playable copy (`playable.json` `"note": "re-encoded copy"`, `compactedFrom`) all say + it is a re-encode. A clip window cut from it says so in its provenance (`fromReencode`). +- **Deliberately stored videos only.** That is a pointer with `keepReason` `"pin"` (a pin, and every landed + container: an import, a live recording, attach-media), `"override"` (an explicit persist: Persist source video, + persist-videos, the whole-recording fetch), or any `origin` (a container somebody requested). A keep-latest + container with no origin is never compacted, and neither is a legacy pointer with neither. Neither is the audio + beside the record. +- **The selector** (`"select": true`, `"slugs"` narrows it) also needs the platform in `savedVideoCompaction.platforms` + (default Kick, Twitch, Rumble; YouTube is left alone), a video bitrate of at least `minVideoMbps` (3) and a height of + at least `minHeight` (720). An explicit `items` list is not held to those three. Always skipped: already compacted, + already AV1, audio-only, a channel with `excludeFromCompaction` (CHANNEL.md), and one whose last checks failed + (`"retryFailed": true` runs it again). +- **The dry run** prints one line per video: length, height, fps, codec, video bitrate, size, then the estimate + (size and hours, from the measured ratios) and the disk it needs against what is free. A skipped video gets the + reason. A last line gives the total. Nothing is written. +- **The run.** One job per channel on the `compact` queue, one video at a time. The source's packets are scanned + once. Chunks of `chunkMinutes` (10) start on source keyframes, in `<store dir>/.compact-scratch/` on the store's + drive. Each chunk is one heavy-slot admission (1.5 GB, niced), so it waits while render mode holds the machine. + Its frame count is checked; a short or long chunk is encoded once more. Cancel and drain stop between chunks, + and a re-run (or the boot pass after a restart) resumes at the first chunk not done. The disk floor is checked + before the first chunk and before each one: two outputs, less what the chunks hold, plus 2 GiB. +- **The checks.** Every one must pass, or the original stays active and untouched, the re-encode is removed, and the + reason is in the log, the result and `.compact-scratch/failed.json`: + - a full decode without an error; + - the video's length within a frame of the source's; + - the frame count the fps change gives; + - the audio packets identical (bytes and timing); + - VMAF on `qualitySamples` (12) 2-second excerpts spread through the file, mean at least `vmafMinMean` (90) and no + excerpt below `vmafMinSample` (85); SSIM where this ffmpeg has no libvmaf; + - three windows cut through the evidence cutter from both copies and compared; + - the recording clock (`clock.json`) re-measured against the re-encode, within its tolerance of the old map, + then written for the new file. +- **The original.** With `dropOriginal: "after-verify"` (the default), a separate step runs after the pointer + names the re-encode. It reads the re-encode back from disk (size, sha256, container, length), then drops the + original. A video whose availability is not public or unlisted, or unknown, is never dropped this way. It waits in + `get compaction-review` (and on /saved-videos) as "compacted, original awaiting review". Watch the compacted copy, + record the review (the video page's **Review the compacted copy**, or `review-compacted-original`), then drop the + original with `"confirmOriginal": true`. `"keep"` keeps every original until a person drops it. Nothing else + deletes an original. The prune keeps a video that holds one, unpersist brings it back as the source, and a + persist that would land on its name moves it aside first. +- **Not automatic.** There is no lane: compaction runs only when it is asked. + ## Publish ```sh diff --git a/SETTINGS.md b/SETTINGS.md @@ -41,6 +41,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`socialLinks`](#sociallinks) | `[]` | | [`homepageUrl`](#homepageurl) | `""` | | [`savedVideoBackup`](#savedvideobackup) | object — see below | +| [`savedVideoCompaction`](#savedvideocompaction) | object — see below | | [`storage`](#storage) | object — see below | | [`buildPipeline`](#buildpipeline) | object — see below | | [`digest`](#digest) | object — see below | @@ -625,6 +626,57 @@ Default: } ``` +## `savedVideoCompaction` + +Compacting a saved video (`pnpm ops compact-saved-videos`, controller/compactSavedVideos.ts): a deliberately stored container re-encoded to AV1 (SVT-AV1, a keyframe every 5 s, the source's height, the audio copied), verified, and made the active copy, the original kept beside it as `keptAs: "original"` until it is dropped. Runs only when asked — there is no lane. These keys are the selector, the encode, the checks' thresholds and when the original goes. See SavedVideoCompactionSettings and OPERATING.md, "Compact saved videos". + +#### `savedVideoCompaction` + +| Key | Default | Description | +|---|---|---| +| `platforms` | list — see below | The selector's platforms (as the URL names them): a deliberately stored container on one of these, above `minVideoMbps` and at least `minHeight` tall, is what `compact-saved-videos {"select": true}` picks. An explicit `items` list is not held to it. Default ["kick", "twitch", "rumble"]; YouTube is left alone. | +| `minVideoMbps` | `3` | The selector's floor: the stored VIDEO stream's bitrate (Mbit/s, the container's bytes less its audio, over its length) at or above which a container is a candidate. Default 3 (Rumble's high-bitrate half; Kick and Twitch store 5–6). | +| `minHeight` | `720` | The selector's other floor: a container shorter than this (pixels) is already light. Default 720. | +| `crf` | `36` | SVT-AV1's crf. Default 36 (operator ruling: about 0.64 × the source's video bitrate at VMAF 94 on the measured sample). 20–55. | +| `preset` | `8` | SVT-AV1's preset. Default 8. 4–12. | +| `maxFps` | `30` | The frame rate a source above it is brought down to, on `maxFpsPlatforms` only (operator ruling: Kick and Twitch above 30 fps go to 30). 0 = never change the frame rate. | +| `maxFpsPlatforms` | list — see below | The platforms `maxFps` applies to. Default ["kick", "twitch"]; a Rumble 60 fps stream keeps its 60. | +| `chunkMinutes` | `10` | The encode's chunk, in minutes of the source: each chunk starts on a source keyframe, takes the heavy slot on its own, and is what a restart resumes from. Default 10; 1–60. | +| `qualitySamples` | `12` | How many 2-second excerpts, spread through the file, the quality check scores (VMAF, or SSIM where this ffmpeg has no libvmaf). Default 12; 3–60. | +| `vmafMinMean` | `90` | The VMAF the excerpts' mean must reach (against the stored source). Default 90. | +| `vmafMinSample` | `85` | The VMAF no single excerpt may fall below. Default 85. | +| `ssimMinMean` | `0.95` | Without libvmaf: the SSIM the excerpts' mean must reach. Default 0.95. | +| `ssimMinSample` | `0.9` | Without libvmaf: the SSIM no excerpt may fall below. Default 0.9. | +| `dropOriginal` | `"after-verify"` | "after-verify" (default, operator ruling): once every check passed and the pointer names the compacted copy, a separate step reads that copy back from disk (size, sha256, container, length) and then drops the original — except for a video gone from its platform (availability not public or unlisted, or unknown), whose original waits for a person's review (`get compaction-review`, `review-compacted-original`, then `drop-saved-alternate` with `confirmOriginal`). "keep": every original stays until a person drops it. | + +Default: + +```json +{ + "platforms": [ + "kick", + "twitch", + "rumble" + ], + "minVideoMbps": 3, + "minHeight": 720, + "crf": 36, + "preset": 8, + "maxFps": 30, + "maxFpsPlatforms": [ + "kick", + "twitch" + ], + "chunkMinutes": 10, + "qualitySamples": 12, + "vmafMinMean": 90, + "vmafMinSample": 85, + "ssimMinMean": 0.95, + "ssimMinSample": 0.9, + "dropOriginal": "after-verify" +} +``` + ## `storage` Where a channel's downloaded media goes when it is relocated off the corpus disk. A DEFAULT ONLY: the relocate controller never reads it and always takes an explicit root, so this is the value the per-channel Storage panel prefills and the /channels bulk move falls back to. Blank = no default. See StorageSettings. diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts @@ -0,0 +1,675 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { execa } from "execa"; +import type { Paths } from "../lib/paths"; +import { + compactOne, + compactSavedVideos, + listCompactionReview, + planCompaction, + type CompactDeps, +} from "./compactSavedVideos"; +import { encodeChunkArgs, ffmpegHas, type ChunkPlan, type EncodeSettings } from "../lib/compactMedia-server"; +import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, type SavedVideoCompactionSettings } from "../lib/savedVideoCompaction"; +import { loadSavedVideo, savedVideoPointerPath } from "../lib/savedVideo-server"; +import { compactedOriginalOf } from "../lib/savedVideo"; +import { CLOCK_FILE, CLOCK_VERSION } from "../lib/recordingClock.mjs"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compactSavedVideos.test.ts +// +// The compaction job's flow over a temp store, on a few seconds of lavfi test +// pattern and tone made here by ffmpeg. The encoder is STUBBED in the flow +// tests (x264 ultrafast, same frame counts and the same chunking), so they run +// without libsvtav1 and in seconds; one test runs the real SVT-AV1 encode and +// every real check, skipped where this ffmpeg has no libsvtav1. Skipped +// altogether without ffmpeg/ffprobe. + +async function have(bin: string): Promise<boolean> { + return execa(bin, ["-version"]).then( + () => true, + () => false, + ); +} +const tools = (await have("ffmpeg")) && (await have("ffprobe")); +const svt = tools && (await ffmpegHas("ffmpeg", "encoders", "libsvtav1")); +const vmaf = tools && (await ffmpegHas("ffmpeg", "filters", "libvmaf")); +const NO_TOOLS = !tools && "ffmpeg/ffprobe not installed"; + +const ORIGINAL = "source-media.mp4"; + +// 6 s of 320×180 at 60 fps, a keyframe every 2 s, AAC tone. +async function makeSource(file: string, seconds = 6): Promise<void> { + await execa("ffmpeg", [ + "-nostdin", "-v", "error", "-y", + "-f", "lavfi", "-i", `testsrc=size=320x180:rate=60:duration=${seconds}`, + "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, + "-c:v", "libx264", "-preset", "ultrafast", "-g", "120", "-keyint_min", "120", "-sc_threshold", "0", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-b:a", "64k", "-shortest", file, + ]); +} + +const sha = async (file: string) => createHash("sha256").update(await readFile(file)).digest("hex"); + +type Fx = { + root: string; + paths: Paths; + videoDir: string; + storeDir: string; + source: string; + sourceSha: string; + pointerText: () => Promise<string>; +}; + +let cachedSource: string | null = null; + +async function withVideo( + opts: { platform?: string; keepReason?: string; slug?: string; id?: string } = {}, + fn: (f: Fx) => Promise<void>, +): Promise<void> { + const root = await mkdtemp(path.join(tmpdir(), "compact-")); + const paths = { + transcriptsDir: root, + channelsDir: path.join(root, "channels"), + savedVideosDir: path.join(root, "saved-videos"), + ffmpegBin: "ffmpeg", + ffprobeBin: "ffprobe", + monorepoRoot: "", + } as Paths; + const slug = opts.slug ?? "kick"; + const id = opts.id ?? "v1"; + const videoDir = path.join(paths.channelsDir, slug, "data", id); + const storeDir = path.join(paths.savedVideosDir, slug, id); + await mkdir(videoDir, { recursive: true }); + await mkdir(storeDir, { recursive: true }); + await writeFile( + path.join(paths.channelsDir, slug, "config.json"), + JSON.stringify({ handling: "transcribe", platform: opts.platform ?? "kick", name: slug }), + ); + if (!cachedSource) { + cachedSource = path.join(await mkdtemp(path.join(tmpdir(), "compact-src-")), ORIGINAL); + await makeSource(cachedSource); + } + const source = path.join(storeDir, ORIGINAL); + await writeFile(source, await readFile(cachedSource)); + const bytes = (await stat(source)).size; + await writeFile( + savedVideoPointerPath(videoDir), + JSON.stringify({ + storedAt: "2026-11-01T00:00:00.000Z", + dir: storeDir, + file: ORIGINAL, + bytes, + keepReason: opts.keepReason ?? "pin", + format: { preset: "original", height: 180, vcodec: "avc1" }, + }) + "\n", + ); + try { + await fn({ + root, + paths, + videoDir, + storeDir, + source, + sourceSha: await sha(source), + // The pointer as it was, but for the source's sha256 the run may record + // on it (what the backup step does): that one must be the file's own. + pointerText: async () => { + const raw = JSON.parse(await readFile(savedVideoPointerPath(videoDir), "utf8")); + if (raw.sha256 !== undefined) assert.equal(raw.sha256, await sha(source)); + delete raw.sha256; + return JSON.stringify(raw); + }, + }); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +// Chunks of 2 s (the settings' floor is a minute; the controller takes what +// it is given), three quality samples, thresholds a synthetic pattern meets. +const SETTINGS: SavedVideoCompactionSettings = { + ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, + chunkMinutes: 2 / 60, + qualitySamples: 3, + vmafMinMean: 0, + vmafMinSample: 0, + ssimMinMean: 0, + ssimMinSample: 0, +}; + +// x264 in SVT-AV1's place: the same seek, frame count and fps filter. +async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }): Promise<void> { + const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); + const i = args.indexOf("libsvtav1"); + args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "30"); + await execa("ffmpeg", args); +} + +function flowDeps(extra: CompactDeps = {}): CompactDeps { + return { + availability: async () => "public", + freeBytes: async () => 1e15, + encodeChunk: x264Chunk, + score: async () => 95, + cutCompare: async () => 0.99, + hasVmaf: async () => true, + ...extra, + }; +} + +function logger() { + const lines: string[] = []; + return { lines, onLog: (l: string) => lines.push(l.trimEnd()) }; +} + +async function listTree(dir: string): Promise<string[]> { + const out: string[] = []; + const walk = async (d: string) => { + for (const e of await readdir(d, { withFileTypes: true })) { + const p = path.join(d, e.name); + if (e.isDirectory()) await walk(p); + else { + const s = await stat(p); + out.push(`${path.relative(dir, p)} ${s.size} ${s.mtimeMs}`); + } + } + }; + await walk(dir); + return out.sort(); +} + +test("the real encode: SVT-AV1, every check, swapped, re-checked, the original dropped after", { skip: NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1") }, async () => { + await withVideo({}, async ({ paths, videoDir, storeDir, sourceSha }) => { + const log = logger(); + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: log.onLog, + deps: { availability: async () => "public", freeBytes: async () => 1e15 }, + }); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const p = (await loadSavedVideo(videoDir))!; + assert.match(p.file, /^source-media\.compact-av1-\d{14}\.mp4$/); + assert.equal(p.sha256, await sha(path.join(storeDir, p.file))); + const c = p.compacted!; + assert.equal(c.checks.passed, true); + assert.equal(c.checks.decoded, true); + // 60 -> 30 fps on Kick: 360 source frames give 180. + assert.deepEqual(c.checks.frames, [360, 180, 180]); + assert.ok(Math.abs(c.checks.seconds[0] - c.checks.seconds[1]) <= c.checks.secondsTolerance); + assert.equal(c.checks.audio, "identical"); + assert.equal(c.checks.quality.metric, vmaf ? "vmaf" : "ssim"); + assert.equal(c.checks.quality.samples, 3); + assert.ok(c.checks.quality.mean > 0); + assert.equal(c.checks.cuts.length, 3); + for (const cut of c.checks.cuts) assert.ok(cut.ssim >= 0.9, JSON.stringify(cut)); + assert.equal(c.result.vcodec, "av1"); + assert.equal(c.result.fps, 30); + assert.equal(c.source.sha256, sourceSha); + assert.equal(c.settings.crf, 36); + assert.equal(c.settings.preset, 8); + assert.equal(c.chunks, 3); + assert.equal(c.recheck?.ok, true); + // After-verify on a video still on its platform: dropped, after the re-check. + assert.equal(c.originalDropped?.sha256, sourceSha); + assert.equal(compactedOriginalOf(p), null); + await assert.rejects(stat(path.join(storeDir, ORIGINAL))); + await assert.rejects(stat(path.join(storeDir, ".compact-scratch"))); + assert.equal(p.format?.vcodec, "av1"); + const recheckAt = log.lines.findIndex((l) => /re-checked from disk/.test(l)); + const dropAt = log.lines.findIndex((l) => /the original source-media\.mp4 dropped/.test(l)); + assert.ok(recheckAt > 0 && dropAt > recheckAt, log.lines.join("\n")); + }); +}); + +test("a killed chunk: the run stops, and the next run resumes at the first chunk not done", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths, videoDir, storeDir, pointerText }) => { + const before = await pointerText(); + const ac = new AbortController(); + const first: number[] = []; + const r1 = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + signal: ac.signal, + deps: flowDeps({ + encodeChunk: async (o) => { + first.push(o.chunk.index); + if (o.chunk.index === 1) { + await writeFile(o.out, "half a chunk"); + ac.abort(); + throw new Error("killed"); + } + await x264Chunk(o); + }, + }), + }); + assert.deepEqual(r1, { status: "stopped", reason: "cancelled" }); + assert.deepEqual(first, [0, 1]); + assert.equal(await pointerText(), before, "the pointer is untouched"); + const scratch = path.join(storeDir, ".compact-scratch"); + const files = await readdir(scratch); + assert.ok(files.includes("chunk-0000.mkv")); + assert.ok(!files.some((f) => f.endsWith(".part")), files.join(",")); + const state = JSON.parse(await readFile(path.join(scratch, "state.json"), "utf8")); + assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, false, false]); + + const second: number[] = []; + const log = logger(); + const r2 = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: log.onLog, + deps: flowDeps({ + encodeChunk: async (o) => { + second.push(o.chunk.index); + await x264Chunk(o); + }, + }), + }); + assert.equal(r2.status, "compacted", log.lines.join("\n")); + assert.deepEqual(second, [1, 2]); + assert.ok(log.lines.some((l) => /resuming — 1\/3 chunk\(s\) already encoded/.test(l))); + assert.ok((await loadSavedVideo(videoDir))!.compacted); + }); +}); + +test("an encoder that dies (not a cancel) keeps the chunks done for the re-run", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths, storeDir, pointerText }) => { + const before = await pointerText(); + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps({ + encodeChunk: async (o) => { + if (o.chunk.index === 2) throw new Error("ffmpeg failed (exit 137)"); + await x264Chunk(o); + }, + }), + }); + assert.equal(r.status, "failed"); + assert.equal(await pointerText(), before); + const state = JSON.parse(await readFile(path.join(storeDir, ".compact-scratch", "state.json"), "utf8")); + assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, true, false]); + }); +}); + +test("the disk floor: refused before the first chunk, and stopped between chunks with the rest resumable", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths, storeDir, pointerText }) => { + const before = await pointerText(); + let encoded = 0; + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps({ freeBytes: async () => 1000, encodeChunk: async (o) => { encoded += 1; await x264Chunk(o); } }), + }); + assert.equal(r.status, "stopped"); + assert.match((r as { reason: string }).reason, /the store's disk has 1000 B free; kick\/v1 needs about/); + assert.equal(encoded, 0); + assert.equal(await pointerText(), before); + + // Room for the plan and the first chunk only. + let calls = 0; + const r2 = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps({ freeBytes: async () => (++calls <= 3 ? 1e15 : 1000) }), + }); + assert.equal(r2.status, "stopped"); + const state = JSON.parse(await readFile(path.join(storeDir, ".compact-scratch", "state.json"), "utf8")); + assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, false, false]); + assert.equal(await pointerText(), before); + }); +}); + +test("a failed verification leaves the original active and untouched, the re-encode removed, the reason recorded", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths, storeDir, source, sourceSha, pointerText }) => { + const before = await pointerText(); + const log = logger(); + const r = await compactOne({ + paths, + settings: { ...SETTINGS, vmafMinMean: 90, vmafMinSample: 85 }, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: log.onLog, + deps: flowDeps({ score: async () => 42 }), + }); + assert.equal(r.status, "failed"); + assert.match((r as { reason: string }).reason, /verification failed: VMAF 42\.00 mean/); + assert.equal(await pointerText(), before); + assert.equal(await sha(source), sourceSha); + assert.deepEqual(await readdir(path.join(storeDir, ".compact-scratch")), ["failed.json"]); + assert.deepEqual((await readdir(storeDir)).sort(), [".compact-scratch", ORIGINAL]); + assert.ok(log.lines.some((l) => /NOT compacted .*The original stays the active copy, untouched/.test(l))); + + // The next plan says why; retryFailed runs it again. + const plan = await planCompaction({ paths, settings: { ...SETTINGS, vmafMinMean: 90, vmafMinSample: 85 }, items: [{ slug: "kick", id: "v1" }], deps: flowDeps() }); + assert.equal(plan.items[0].compact, false); + assert.match(plan.items[0].reason!, /last compaction failed its checks .*retryFailed/); + const again = await planCompaction({ paths, settings: { ...SETTINGS, vmafMinMean: 90, vmafMinSample: 85 }, items: [{ slug: "kick", id: "v1" }], retryFailed: true, deps: flowDeps() }); + assert.equal(again.items[0].compact, true); + }); +}); + +test("an audio stream that is not the source's fails the check", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths, pointerText }) => { + const before = await pointerText(); + let n = 0; + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps({ + audioHash: async () => ({ data: `d${n++}`, timing: "t", firstPts: 0, packets: 10 }), + }), + }); + assert.equal(r.status, "failed"); + assert.match((r as { reason: string }).reason, /the audio is not the source's packet for packet/); + assert.equal(await pointerText(), before); + }); +}); + +test("a video gone from its platform (or unknown) is compacted but its original is never dropped automatically", { skip: NO_TOOLS }, async () => { + for (const availability of [null, "deleted"] as const) { + await withVideo({}, async ({ paths, videoDir, storeDir }) => { + const log = logger(); + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: log.onLog, + deps: flowDeps({ availability: async () => availability }), + }); + assert.equal(r.status, "compacted", log.lines.join("\n")); + assert.equal((r as { dropped: boolean }).dropped, false); + assert.equal((r as { review: string }).review, "awaiting-review"); + const p = (await loadSavedVideo(videoDir))!; + assert.equal(compactedOriginalOf(p)?.file, ORIGINAL); + await stat(path.join(storeDir, ORIGINAL)); + assert.ok(log.lines.some((l) => /is NOT dropped — it waits for a person's review/.test(l))); + const rows = await listCompactionReview({ paths, dropOriginal: "after-verify", deps: { availability: async () => availability } }); + assert.equal(rows.length, 1); + assert.equal(rows[0].state, "awaiting-review"); + // And a second run does not touch it: already compacted. + const again = await planCompaction({ paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], deps: flowDeps() }); + assert.deepEqual([again.items[0].compact, again.items[0].reason], [false, "already compacted"]); + }); + } +}); + +test("after-verify drops the original only after the swap was written and the copy re-checked from disk", { skip: NO_TOOLS }, async () => { + // The re-check reads a different sha256 from disk: the original stays. + await withVideo({}, async ({ paths, videoDir, storeDir }) => { + const log = logger(); + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: log.onLog, + deps: flowDeps({ + sha256: async (file) => (/compact-av1/.test(path.basename(file)) ? "0".repeat(64) : sha(file)), + }), + }); + assert.equal(r.status, "compacted"); + assert.equal((r as { dropped: boolean }).dropped, false); + const p = (await loadSavedVideo(videoDir))!; + assert.equal(p.compacted?.recheck?.ok, false); + assert.match(p.compacted?.recheck?.why ?? "", /sha256/); + await stat(path.join(storeDir, ORIGINAL)); + assert.ok(log.lines.some((l) => /re-check after the swap FAILED/.test(l))); + }); + // The re-check holds: at the moment the drop step reads availability the + // pointer already names the re-encode and the original is still on disk. + await withVideo({}, async ({ paths, videoDir, storeDir }) => { + const seen: { file: string; original: boolean }[] = []; + let calls = 0; + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps({ + availability: async () => { + if (++calls > 1) { + seen.push({ + file: (await loadSavedVideo(videoDir))!.file, + original: await stat(path.join(storeDir, ORIGINAL)).then(() => true, () => false), + }); + } + return "public"; + }, + }), + }); + assert.equal(r.status, "compacted"); + assert.equal((r as { dropped: boolean }).dropped, true); + assert.equal(seen.length, 1); + assert.match(seen[0].file, /compact-av1/); + assert.equal(seen[0].original, true); + const p = (await loadSavedVideo(videoDir))!; + assert.ok(p.compacted?.recheck?.ok); + assert.ok(p.compacted!.originalDropped!.at >= p.compacted!.recheck!.at); + }); +}); + +test('dropOriginal "keep": the original stays', { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths, storeDir }) => { + const r = await compactOne({ + paths, + settings: { ...SETTINGS, dropOriginal: "keep" }, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps(), + }); + assert.deepEqual([r.status, (r as { review: string }).review], ["compacted", "kept"]); + await stat(path.join(storeDir, ORIGINAL)); + }); +}); + +test("the selector picks only deliberately stored + platform + bitrate; an explicit list only refuses keep-latest", async () => { + const root = await mkdtemp(path.join(tmpdir(), "compact-select-")); + try { + const paths = { + transcriptsDir: root, + channelsDir: path.join(root, "channels"), + savedVideosDir: path.join(root, "saved-videos"), + ffmpegBin: "ffmpeg", + ffprobeBin: "ffprobe", + monorepoRoot: "", + } as Paths; + const videos: [string, string, string, string, number][] = [ + // slug, platform, id, keepReason, video kbps + ["kick", "kick", "pinned-hi", "pin", 5200], + ["kick", "kick", "latest-hi", "keep-latest", 5200], + ["kick", "kick", "pinned-lo", "pin", 640], + ["tube", "youtube", "pinned-hi", "pin", 5200], + ["rumble", "rumble", "persisted-hi", "override", 3400], + ]; + const kbps = new Map<string, number>(); + for (const [slug, platform, id, keepReason, k] of videos) { + const videoDir = path.join(paths.channelsDir, slug, "data", id); + const storeDir = path.join(paths.savedVideosDir, slug, id); + await mkdir(videoDir, { recursive: true }); + await mkdir(storeDir, { recursive: true }); + await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", platform })); + await writeFile(path.join(storeDir, ORIGINAL), "bytes"); + kbps.set(path.join(storeDir, ORIGINAL), k); + await writeFile( + savedVideoPointerPath(videoDir), + JSON.stringify({ storedAt: "x", dir: storeDir, file: ORIGINAL, bytes: 5_000_000_000, keepReason }), + ); + } + const deps: CompactDeps = { + availability: async () => "public", + freeBytes: async () => 1e13, + probe: async (file) => ({ + hasVideo: true, vcodec: "h264", width: 1920, height: 1080, fps: 60, seconds: 7200, + videoKbps: kbps.get(file) ?? null, audioKbps: 155, videoStart: 0, audioStreams: 1, bytes: 5_000_000_000, + }), + }; + const plan = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, select: true, deps }); + const pick = Object.fromEntries(plan.items.map((i) => [`${i.slug}/${i.id}`, i.compact ? "compact" : i.reason])); + assert.deepEqual(pick, { + "kick/latest-hi": "an automatic keep-latest container (compaction is for deliberately stored videos only)", + "kick/pinned-hi": "compact", + "kick/pinned-lo": "0.64 Mbit/s video is below minVideoMbps 3", + "rumble/persisted-hi": "compact", + "tube/pinned-hi": "platform youtube is not selected", + }); + assert.equal(plan.willCompact, 2); + const kickLine = plan.items.find((i) => i.id === "pinned-hi" && i.slug === "kick")!.line; + assert.match(kickLine, /^kick\/pinned-hi: 2h00m 1080p60 h264 5\.20 Mbit\/s 4\.66 GB → est\. .* AV1 crf 36 at 30 fps .*est\. .* needs .* free \(.* free\) — would compact$/); + // Rumble keeps its 60 fps. + assert.doesNotMatch(plan.items.find((i) => i.slug === "rumble")!.line, /at 30 fps/); + assert.match(plan.lines.at(-1)!, /^total: 2 container\(s\)/); + // An explicit list: YouTube and the low bitrate are a person's call; keep-latest never. + const explicit = await planCompaction({ + paths, + settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, + items: [{ slug: "tube", id: "pinned-hi" }, { slug: "kick", id: "pinned-lo" }, { slug: "kick", id: "latest-hi" }], + deps, + }); + assert.deepEqual(explicit.items.map((i) => i.compact), [true, true, false]); + // A channel that opts out. + await writeFile(path.join(paths.channelsDir, "kick", "config.json"), JSON.stringify({ handling: "transcribe", platform: "kick", excludeFromCompaction: true })); + const out = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, items: [{ slug: "kick", id: "pinned-hi" }], deps }); + assert.match(out.items[0].reason!, /opts out/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a dry run (the plan) writes nothing", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ root, paths }) => { + const before = await listTree(root); + const plan = await planCompaction({ paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], deps: { availability: async () => null } }); + assert.equal(plan.items[0].compact, true); + assert.match(plan.items[0].line, /0m 180p60 h264 .* → est\. .* needs .* free/); + assert.match(plan.items[0].line, /not known to be on its platform \(availability unknown\): its original waits for a review/); + assert.deepEqual(await listTree(root), before); + }); +}); + +test("the recording clock: re-measured against the re-encode and kept, or a moved map fails the check", { skip: NO_TOOLS }, async () => { + for (const shift of [0, 0.5]) { + await withVideo({}, async ({ paths, videoDir, pointerText }) => { + const audio = path.join(videoDir, "audio.mp3"); + await writeFile(audio, "cue audio"); + const p = (await loadSavedVideo(videoDir))!; + const clock = { + version: CLOCK_VERSION, + id: "c1", + createdAt: "2026-11-01T00:00:00.000Z", + source: { file: "audio.mp3", bytes: (await stat(audio)).size }, + target: { file: ORIGINAL, bytes: p.bytes }, + method: "xcorr", + params: { tolerance: 0.08 }, + anchors: [{ at: 2, offset: 1.25, ok: true }, { at: 4, offset: 1.25, ok: true }], + segments: [{ from: 0, to: 6, offset: 1.25, rate: 0 }], + gaps: [], + residual: { rms: 0.001 }, + ok: true, + }; + await writeFile(path.join(videoDir, CLOCK_FILE), JSON.stringify(clock)); + const before = await pointerText(); + const r = await compactOne({ + paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + deps: flowDeps({ + measureClock: async (o) => + ({ ...clock, id: "c2", target: { file: path.basename(o.container), bytes: o.targetBytes }, segments: [{ from: 0, to: 6, offset: 1.25 + shift, rate: 0 }] }) as never, + }), + }); + const written = JSON.parse(await readFile(path.join(videoDir, CLOCK_FILE), "utf8")); + if (shift === 0) { + assert.equal(r.status, "compacted"); + const after = (await loadSavedVideo(videoDir))!; + assert.equal(after.compacted?.checks.clock, "kept"); + assert.equal(written.target.file, after.file); + assert.equal(written.target.bytes, after.bytes); + } else { + assert.equal(r.status, "failed"); + assert.match((r as { reason: string }).reason, /the recording clock moved/); + assert.equal(await pointerText(), before); + assert.equal(written.id, "c1"); + } + }); + } +}); + +test("compactSavedVideos runs a list one at a time and a drain stops between videos", { skip: NO_TOOLS }, async () => { + await withVideo({}, async ({ paths }) => { + const drain = new AbortController(); + drain.abort(); + const r = await compactSavedVideos({ + paths, + settings: SETTINGS, + items: [{ slug: "kick", id: "v1" }], + mode: "explicit", + onLog: () => {}, + drainSignal: drain.signal, + deps: flowDeps(), + }); + assert.equal(r.stopped, "drained"); + assert.equal(r.compacted.length, 0); + }); +}); + +test("each chunk goes through the heavy slot's gate with its estimate, niced", { skip: NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1") }, async () => { + await withVideo({}, async ({ root, paths }) => { + // A stand-in for scripts/queue-lock.mjs: records each argv, runs the rest. + const repo = path.join(root, "repo"); + await mkdir(path.join(repo, "scripts"), { recursive: true }); + const marker = path.join(root, "gate.jsonl"); + await writeFile( + path.join(repo, "scripts", "queue-lock.mjs"), + `import { appendFileSync } from "node:fs";\nimport { spawnSync } from "node:child_process";\n` + + `const argv = process.argv.slice(2);\nappendFileSync(${JSON.stringify(marker)}, JSON.stringify(argv) + "\\n");\n` + + `const at = argv.indexOf("--");\nconst r = spawnSync(argv[at + 1], argv.slice(at + 2), { stdio: "inherit" });\nprocess.exit(r.status ?? 1);\n`, + ); + const r = await compactOne({ + paths: { ...paths, monorepoRoot: repo } as Paths, + settings: SETTINGS, + item: { slug: "kick", id: "v1" }, + mode: "explicit", + onLog: () => {}, + // The real chunk encoder; the scoring stubbed (it would take the gate too). + deps: { availability: async () => "public", freeBytes: async () => 1e15, score: async () => 95, cutCompare: async () => 0.99 }, + }); + assert.equal(r.status, "compacted"); + const runs = (await readFile(marker, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]); + const chunks = runs.filter((a) => a.includes("libsvtav1")); + assert.equal(chunks.length, 3); + for (const a of chunks) assert.deepEqual(a.slice(0, 7), ["--heavy", "--estimate", "1500", "--", "nice", "-n", "10"]); + // The full decode is admitted too. + assert.ok(runs.some((a) => a.includes("-xerror"))); + }); +}); diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts @@ -0,0 +1,1104 @@ +// COMPACT A SAVED VIDEO (the `compact-saved-videos` job; the pure half is +// lib/savedVideoCompaction.ts, the ffmpeg half lib/compactMedia-server.ts). +// +// One video at a time, each the same steps: +// +// 1. DECIDE. The pointer, the container, one ffprobe, the channel's opt-out +// and the selector (explicit list: deliberately stored only; selector: and +// platform, height and video bitrate). A dry run stops here and prints the +// estimate and the disk it needs. +// 2. ENCODE IN CHUNKS, in `<store dir>/.compact-scratch/` (the store's own +// drive). The source's packets are scanned once (frame count, keyframes); +// chunks of about `chunkMinutes` start on source keyframes; each is one +// heavy-slot admission (waiting while render mode holds the machine), its +// frame count checked, then recorded in `state.json` — a restart resumes +// at the first chunk not done. Cancel and drain are honoured between +// chunks; the disk floor before the first and before each one. +// 3. MUX: the chunks joined, every audio stream of the SOURCE copied. +// 4. VERIFY — every check must pass or the original stays active, untouched, +// and the output is removed (the reason in the log, the result and +// `failed.json`): a full decode; the video's length within a frame; the +// frame count the fps change gives; the audio packets identical; VMAF (or +// SSIM) on excerpts spread through the file; a window cut from each copy +// through the evidence cutter, compared; the recording clock re-measured +// against the re-encode and within its tolerance of the old map. +// 5. SWAP, in one locked pointer write: the re-encode (its OWN name, +// `source-media.compact-av1-<stamp>.mp4`) becomes `file`; the original +// joins `alternates` as `keptAs: "original"`; `compacted` records every +// number. Only if the pointer still names the bytes that were encoded. +// 6. RECHECK, a separate step: the pointer and the re-encode read back from +// disk (size, sha256, container, length). +// 7. DROP THE ORIGINAL, another separate step, only under `dropOriginal: +// "after-verify"`, only when the recheck passed, and NEVER for a video not +// known to be on its platform: that one is left for a person's review +// (`get compaction-review`). + +import path from "node:path"; +import { createReadStream } from "node:fs"; +import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Availability } from "../lib/availability"; +import { readChannelConfig } from "./channels"; +import { listSavedVideos } from "./savedVideoInventory"; +import { channelPlatform } from "../ytdlp/channelArgs"; +import { detectPlatform } from "../lib/platform"; +import { + compactedLine, + compactedOriginalOf, + savedVideoPath, + type SavedVideoAlternate, + type SavedVideoCompacted, + type SavedVideoCompactedChecks, + type SavedVideoPointer, +} from "../lib/savedVideo"; +import { + SavedAlternateRefusal, + dropSavedAlternate, + loadSavedVideo, + savedVideoPointerPath, + updateSavedVideoChecksum, +} from "../lib/savedVideo-server"; +import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; +import { getFreeBytes } from "../lib/diskSpace"; +import { formatBytes } from "../lib/format"; +import { + COMPACTION_SCRATCH_DIRNAME, + COMPACTION_STATE_FILENAME, + COMPACTION_TOOL, + compactedFileName, + COMPACTION_DISK_MARGIN_BYTES, + compactionFreeNeeded, + decideCompaction, + estimateCompaction, + isStillOnPlatform, + sanitizeSavedVideoCompaction, + targetFps, + type CompactionEstimate, + type CompactionReviewState, + type SavedVideoCompactionSettings, +} from "../lib/savedVideoCompaction"; +import { + CHUNK_ESTIMATE_MB, + audioPacketsHash, + compareCuts, + concatList, + countVideoFrames, + encodeChunkArgs, + ffmpegHas, + ffmpegVersionLine, + fullDecode, + muxArgs, + planChunks, + probeCompactionSource, + runHeavyFfmpeg, + sampleTimes, + scanVideoPackets, + scoreExcerpt, + type AudioHash, + type ChunkPlan, + type EncodeSettings, + type PacketScan, + type SourceProbe, +} from "../lib/compactMedia-server"; +import { planRecordingClock, measureRecordingClock, recordingClockSidecar } from "../lib/recordingClock-server"; +import { clockOffsetAt, type RecordingClock } from "../lib/recordingClock.mjs"; +import "../lib/childKillGuard"; + +export type CompactItem = { slug: string; id: string }; + +export const COMPACT_GOP_SECONDS = 5; +export const COMPACT_PIX_FMT = "yuv420p"; +const EXCERPT_SECONDS = 2; +const CUT_SECONDS = 3; +const CUT_SAMPLES = 3; +// A window cut from each copy, compared on a 320-px picture: a cut landing a +// frame or more off, or a broken picture, falls well under this. +export const CUT_SSIM_MIN = 0.9; +export const FAILED_FILENAME = "failed.json"; + +// --- deps (a test replaces what it judges) ---------------------------------- + +export type CompactDeps = { + now?: () => Date; + freeBytes?: (dir: string) => Promise<number>; + availability?: (videoDir: string) => Promise<Availability | null>; + probe?: (file: string) => Promise<SourceProbe | null>; + scan?: (file: string, signal?: AbortSignal) => Promise<PacketScan>; + encodeChunk?: (o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string; signal?: AbortSignal }) => Promise<void>; + countFrames?: (file: string) => Promise<number>; + mux?: (o: { list: string; src: string; videoStart: number; out: string; signal?: AbortSignal }) => Promise<void>; + fullDecode?: (file: string, signal?: AbortSignal) => Promise<{ ok: boolean; why?: string }>; + audioHash?: (file: string, signal?: AbortSignal) => Promise<AudioHash>; + hasVmaf?: () => Promise<boolean>; + score?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>; + cutCompare?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<number>; + measureClock?: (o: { videoDir: string; source: string; container: string; sourceBytes: number; targetBytes: number; transcribedAt: string | null; extra: number[]; signal?: AbortSignal }) => Promise<RecordingClock>; + sha256?: (file: string, signal?: AbortSignal) => Promise<string>; + encoderBanner?: () => Promise<string>; +}; + +async function sha256File(file: string, signal?: AbortSignal): Promise<string> { + const h = createHash("sha256"); + for await (const chunk of createReadStream(file, { highWaterMark: 1 << 20, ...(signal ? { signal } : {}) })) { + h.update(chunk as Buffer); + } + return h.digest("hex"); +} + +function resolveDeps(paths: Paths, deps: CompactDeps = {}): Required<CompactDeps> { + return { + now: deps.now ?? (() => new Date()), + freeBytes: deps.freeBytes ?? getFreeBytes, + availability: deps.availability ?? ((d) => resolveEffectiveAvailability(d).catch(() => null)), + probe: deps.probe ?? ((f) => probeCompactionSource(paths.ffprobeBin, f)), + scan: deps.scan ?? ((f, s) => scanVideoPackets(paths.ffprobeBin, f, s)), + encodeChunk: + deps.encodeChunk ?? + (async (o) => { + await runHeavyFfmpeg(paths, encodeChunkArgs(o.src, o.chunk, o.settings, o.out), { + estimateMB: CHUNK_ESTIMATE_MB, + ...(o.signal ? { signal: o.signal } : {}), + }); + }), + countFrames: deps.countFrames ?? ((f) => countVideoFrames(paths.ffprobeBin, f)), + mux: + deps.mux ?? + (async (o) => { + await runHeavyFfmpeg(paths, muxArgs(o.list, o.src, o.videoStart, o.out), { + estimateMB: 300, + nice: true, + ...(o.signal ? { signal: o.signal } : {}), + }); + }), + fullDecode: deps.fullDecode ?? ((f, s) => fullDecode(paths, f, s)), + audioHash: deps.audioHash ?? ((f, s) => audioPacketsHash(paths.ffmpegBin, f, s)), + hasVmaf: deps.hasVmaf ?? (() => ffmpegHas(paths.ffmpegBin, "filters", "libvmaf")), + score: deps.score ?? ((o) => scoreExcerpt(paths, o)), + cutCompare: deps.cutCompare ?? ((o) => compareCuts(paths, o)), + measureClock: + deps.measureClock ?? + ((o) => + measureRecordingClock({ + ffmpegBin: paths.ffmpegBin, + ffprobeBin: paths.ffprobeBin, + ...o, + write: false, + })), + sha256: deps.sha256 ?? sha256File, + encoderBanner: deps.encoderBanner ?? (() => ffmpegVersionLine(paths.ffmpegBin)), + }; +} + +// --- the plan (and the dry run) ---------------------------------------------- + +export type CompactPlanItem = { + slug: string; + id: string; + compact: boolean; + reason?: string; + platform: string | null; + // Availability's word: still on the platform (public / unlisted) or not + // (anything else, or unknown — counted as gone). + onPlatform: boolean; + availability: Availability | null; + source?: { + file: string; + bytes: number; + vcodec: string | null; + height: number | null; + fps: number | null; + seconds: number | null; + videoMbps: number | null; + }; + fps?: number | null; + estimate?: CompactionEstimate; + needsFreeBytes?: number; + freeBytes?: number; + line: string; +}; + +export type CompactPlan = { + items: CompactPlanItem[]; + willCompact: number; + totals: { bytes: number; estimate: [number, number]; hours: [number, number] }; + lines: string[]; +}; + +function hms(seconds: number | null | undefined): string { + if (!seconds) return "?"; + const h = Math.floor(seconds / 3600); + const m = Math.round((seconds % 3600) / 60); + return h ? `${h}h${String(m).padStart(2, "0")}m` : `${m}m`; +} + +function hoursRange([a, b]: [number, number]): string { + const f = (x: number) => (x < 1 ? `${Math.max(1, Math.round(x * 60))} min` : `${x.toFixed(x < 10 ? 1 : 0)} h`); + return `${f(a)}–${f(b)}`; +} + +// The video's platform: its own URL's when its record names one (a channel +// may hold another platform's videos), else the channel's. +async function videoPlatform(videoDir: string, config: ChannelConfig): Promise<string | null> { + const read = await readJsonFile(path.join(videoDir, "metadata.info.json")); + if (read.ok && read.value && typeof read.value === "object") { + const url = (read.value as { webpage_url?: unknown }).webpage_url; + if (typeof url === "string") { + const p = detectPlatform(url); + if (p) return p; + } + } + return channelPlatform(config); +} + +async function lastFailure(dir: string): Promise<{ at: string; reason: string; settingsKey: string } | null> { + const read = await readJsonFile(path.join(dir, COMPACTION_SCRATCH_DIRNAME, FAILED_FILENAME)); + if (!read.ok || !read.value || typeof read.value !== "object") return null; + const r = read.value as Record<string, unknown>; + return typeof r.reason === "string" + ? { at: String(r.at ?? ""), reason: r.reason, settingsKey: String(r.settingsKey ?? "") } + : null; +} + +export function settingsKeyOf(s: SavedVideoCompactionSettings, fps: number | null): string { + return JSON.stringify({ crf: s.crf, preset: s.preset, fps, chunkMinutes: s.chunkMinutes, gop: COMPACT_GOP_SECONDS, pix: COMPACT_PIX_FMT }); +} + +export async function planOne(opts: { + paths: Paths; + item: CompactItem; + mode: "explicit" | "select"; + settings: SavedVideoCompactionSettings; + retryFailed?: boolean; + deps: Required<CompactDeps>; +}): Promise<CompactPlanItem & { pointer?: SavedVideoPointer; probe?: SourceProbe | null; videoDir: string }> { + const { item, settings, deps } = opts; + const videoDir = path.join(opts.paths.channelsDir, item.slug, "data", item.id); + const base = { slug: item.slug, id: item.id, platform: null, onPlatform: false, availability: null, videoDir }; + const skip = (reason: string, extra: Partial<CompactPlanItem> = {}) => ({ + ...base, + ...extra, + compact: false, + reason, + line: `${item.slug}/${item.id}: ${extra.line ?? ""}${extra.line ? " " : ""}skipped (${reason})`, + }); + const config = await readChannelConfig(opts.paths, item.slug); + if (!config) return skip(`no channel "${item.slug}"`); + const pointer = await loadSavedVideo(videoDir); + if (!pointer) return skip("no saved video"); + const platform = await videoPlatform(videoDir, config); + const availability = await deps.availability(videoDir); + const onPlatform = isStillOnPlatform(availability); + const container = savedVideoPath(pointer); + const present = await stat(container).then((s) => s.isFile(), () => false); + const probe = present && !pointer.compacted ? await deps.probe(container) : null; + const facts = { platform, onPlatform, availability }; + const decision = decideCompaction({ + pointer, + platform, + channelExcluded: config.excludeFromCompaction === true, + mode: opts.mode, + containerPresent: present, + probe, + settings, + }); + const mbps = probe?.videoKbps != null ? probe.videoKbps / 1000 : null; + const brief = probe + ? `${hms(probe.seconds)} ${probe.height ?? "?"}p${probe.fps ? Math.round(probe.fps) : ""} ${probe.vcodec ?? "?"} ${mbps !== null ? `${mbps.toFixed(2)} Mbit/s` : "? Mbit/s"} ${formatBytes(pointer.bytes)}` + : ""; + if (!decision.ok) return { ...skip(decision.reason, { ...facts, line: brief ? `${brief} —` : "" }), pointer, probe }; + const failed = await lastFailure(pointer.dir); + const fps = targetFps(probe!.fps, platform, settings); + if (failed && failed.settingsKey === settingsKeyOf(settings, fps) && !opts.retryFailed) { + return { + ...skip(`its last compaction failed its checks on ${failed.at.slice(0, 10)}: ${failed.reason}; "retryFailed": true runs it again`, { + ...facts, + line: `${brief} —`, + }), + pointer, + probe, + }; + } + const estimate = estimateCompaction({ probe: probe!, crf: settings.crf, fps }); + const freeBytes = await deps.freeBytes(pointer.dir); + const needsFreeBytes = compactionFreeNeeded(estimate.bytes[1], 0); + const pct = (b: number) => Math.round((1 - b / pointer.bytes) * 100); + const gone = onPlatform + ? "" + : `; not known to be on its platform (availability ${availability ?? "unknown"}): its original waits for a review`; + const room = freeBytes >= needsFreeBytes; + const line = + `${item.slug}/${item.id}: ${brief} → est. ${formatBytes(estimate.bytes[0])}–${formatBytes(estimate.bytes[1])} ` + + `AV1 crf ${settings.crf}${fps ? ` at ${fps} fps` : ""} (−${pct(estimate.bytes[1])}…${pct(estimate.bytes[0])}%), ` + + `est. ${hoursRange(estimate.hours)}, needs ${formatBytes(needsFreeBytes)} free (${formatBytes(freeBytes)} free)` + + (room ? " — would compact" : " — NOT ENOUGH FREE SPACE: would stop before it") + + gone; + return { + ...base, + ...facts, + compact: true, + source: { + file: pointer.file, + bytes: pointer.bytes, + vcodec: probe!.vcodec, + height: probe!.height, + fps: probe!.fps, + seconds: probe!.seconds, + videoMbps: mbps, + }, + fps, + estimate, + needsFreeBytes, + freeBytes, + line, + pointer, + probe, + }; +} + +// Every candidate: an explicit list, or (`select`) every saved video the +// selector picks, across channels (or `slugs`). +export async function planCompaction(opts: { + paths: Paths; + settings: SavedVideoCompactionSettings; + items?: CompactItem[]; + select?: boolean; + slugs?: string[]; + retryFailed?: boolean; + deps?: CompactDeps; +}): Promise<CompactPlan> { + const deps = resolveDeps(opts.paths, opts.deps); + let items = opts.items ?? []; + const mode: "explicit" | "select" = opts.select ? "select" : "explicit"; + if (opts.select) { + const listed = opts.slugs?.length + ? (await Promise.all(opts.slugs.map((s) => listSavedVideos({ paths: opts.paths, channelSlug: s })))).flat() + : await listSavedVideos({ paths: opts.paths }); + items = listed.map((e) => ({ slug: e.slug, id: e.videoId })); + } + const out: CompactPlanItem[] = []; + for (const item of items) { + const { pointer: _p, probe: _q, videoDir: _d, ...row } = await planOne({ + paths: opts.paths, + item, + mode, + settings: opts.settings, + retryFailed: opts.retryFailed, + deps, + }); + out.push(row); + } + const will = out.filter((i) => i.compact); + const totals = { + bytes: will.reduce((n, i) => n + (i.source?.bytes ?? 0), 0), + estimate: [ + will.reduce((n, i) => n + (i.estimate?.bytes[0] ?? 0), 0), + will.reduce((n, i) => n + (i.estimate?.bytes[1] ?? 0), 0), + ] as [number, number], + hours: [ + will.reduce((n, i) => n + (i.estimate?.hours[0] ?? 0), 0), + will.reduce((n, i) => n + (i.estimate?.hours[1] ?? 0), 0), + ] as [number, number], + }; + const lines = [ + ...out.map((i) => i.line), + `total: ${will.length} container(s), ${formatBytes(totals.bytes)} → est. ${formatBytes(totals.estimate[0])}–${formatBytes(totals.estimate[1])}, ` + + `est. ${hoursRange(totals.hours)} of encoding; ${out.length - will.length} skipped`, + ]; + return { items: out, willCompact: will.length, totals, lines }; +} + +// --- the run ------------------------------------------------------------------- + +type ChunkState = { index: number; from: number; to: number; sourceFrames: number; expectedFrames: number; file: string; bytes?: number; done: boolean }; + +type CompactState = { + version: 1; + sourceFile: string; + sourceBytes: number; + settingsKey: string; + sourceSha256?: string; + startedAt: string; + sourceFrames: number; + sourceFirstPts: number; + sourceLastPts: number; + sourceFrameStep: number; + chunks: ChunkState[]; +}; + +export type CompactOneResult = + | { status: "compacted"; line: string; pointer: SavedVideoPointer; dropped: boolean; review: CompactionReviewState } + | { status: "skipped"; reason: string } + | { status: "failed"; reason: string } + | { status: "stopped"; reason: string }; + +class VerifyFailure extends Error { + constructor( + message: string, + readonly checks: Partial<SavedVideoCompactedChecks> = {}, + ) { + super(message); + } +} + +function round(n: number, d = 3): number { + const f = 10 ** d; + return Math.round(n * f) / f; +} + +async function loadState(file: string): Promise<CompactState | null> { + const read = await readJsonFile(file); + if (!read.ok || !read.value || typeof read.value !== "object") return null; + const s = read.value as CompactState; + return s.version === 1 && Array.isArray(s.chunks) ? s : null; +} + +export type CompactRunOptions = { + paths: Paths; + settings: SavedVideoCompactionSettings; + onLog: (line: string) => void; + signal?: AbortSignal; + drainSignal?: AbortSignal; + deps?: CompactDeps; +}; + +export async function compactOne( + opts: CompactRunOptions & { item: CompactItem; mode: "explicit" | "select"; retryFailed?: boolean }, +): Promise<CompactOneResult> { + const log = (s: string) => opts.onLog(s.endsWith("\n") ? s : `${s}\n`); + const deps = resolveDeps(opts.paths, opts.deps); + const { settings: s, signal } = opts; + const planned = await planOne({ paths: opts.paths, item: opts.item, mode: opts.mode, settings: s, retryFailed: opts.retryFailed, deps }); + const tag = `${opts.item.slug}/${opts.item.id}`; + if (!planned.compact || !planned.pointer || !planned.probe) { + log(planned.line); + return { status: "skipped", reason: planned.reason ?? "not a candidate" }; + } + const pointer = planned.pointer; + const probe = planned.probe; + const videoDir = planned.videoDir; + const src = savedVideoPath(pointer); + const fps = planned.fps ?? null; + const settingsKey = settingsKeyOf(s, fps); + const scratch = path.join(pointer.dir, COMPACTION_SCRATCH_DIRNAME); + const stateFile = path.join(scratch, COMPACTION_STATE_FILENAME); + const estHigh = planned.estimate!.bytes[1]; + log(planned.line.replace(/ — would compact/, "")); + + // The disk floor: before the first chunk and before every one. + const floor = async (written: number): Promise<string | null> => { + const free = await deps.freeBytes(pointer.dir); + const need = compactionFreeNeeded(estHigh, written); + return free < need + ? `the store's disk has ${formatBytes(free)} free; ${tag} needs about ${formatBytes(need)} more ` + + `(its chunks and the muxed copy side by side, plus a ${formatBytes(COMPACTION_DISK_MARGIN_BYTES)} margin)` + : null; + }; + + await assertSavedVideosStoreWritable(opts.paths, pointer.dir); + await mkdir(scratch, { recursive: true }); + let state = await loadState(stateFile); + if (state && (state.sourceFile !== pointer.file || state.sourceBytes !== pointer.bytes || state.settingsKey !== settingsKey)) { + log(`${tag}: the scratch state is for another source or other settings — discarded, starting over.`); + await rm(scratch, { recursive: true, force: true }); + await mkdir(scratch, { recursive: true }); + state = null; + } + const writeState = async () => writeJsonAtomic(stateFile, state); + + try { + if (!state) { + const low = await floor(0); + if (low) return { status: "stopped", reason: low }; + log(`${tag}: scanning ${pointer.file}'s packets (frame count, keyframes)…`); + const scan = await deps.scan(src, signal); + const plan = planChunks(scan, s.chunkMinutes * 60, fps); + if (!plan.length) return { status: "failed", reason: "the source has no video packets" }; + const n = scan.pts.length; + state = { + version: 1, + sourceFile: pointer.file, + sourceBytes: pointer.bytes, + settingsKey, + startedAt: deps.now().toISOString(), + sourceFrames: n, + sourceFirstPts: scan.pts[0], + sourceLastPts: scan.pts[n - 1], + sourceFrameStep: n > 1 ? scan.pts[n - 1] - scan.pts[n - 2] : 1 / (probe.fps ?? 30), + chunks: plan.map((c) => ({ ...c, file: `chunk-${String(c.index).padStart(4, "0")}.mkv`, done: false })), + }; + await writeState(); + log(`${tag}: ${n} frames, ${plan.length} chunk(s) of about ${s.chunkMinutes} min, each starting on a source keyframe.`); + } else { + const done = state.chunks.filter((c) => c.done).length; + log(`${tag}: resuming — ${done}/${state.chunks.length} chunk(s) already encoded.`); + } + if (!state.sourceSha256) { + if (pointer.sha256) { + state.sourceSha256 = pointer.sha256; + } else { + log(`${tag}: hashing ${pointer.file} (${formatBytes(pointer.bytes)}) — the original's sha256 is recorded with the re-encode.`); + state.sourceSha256 = await deps.sha256(src, signal); + await updateSavedVideoChecksum(videoDir, state.sourceSha256, pointer.file); + } + await writeState(); + } + + // ---- 2. the chunks ---- + const enc: EncodeSettings = { + preset: s.preset, + crf: s.crf, + gopSeconds: COMPACT_GOP_SECONDS, + pixFmt: COMPACT_PIX_FMT, + fps, + sourceFps: probe.fps ?? 30, + }; + for (const c of state.chunks) { + if (c.done) { + const ok = await stat(path.join(scratch, c.file)).then((st) => st.size === c.bytes, () => false); + if (ok) continue; + log(`${tag}: chunk ${c.index} is recorded done but its file is not as recorded — encoding it again.`); + c.done = false; + } + if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; + if (opts.drainSignal?.aborted) { + log(`${tag}: drained — ${state.chunks.filter((x) => !x.done).length} chunk(s) left for the next run.`); + return { status: "stopped", reason: "drained" }; + } + const written = state.chunks.reduce((n, x) => n + (x.done ? (x.bytes ?? 0) : 0), 0); + const low = await floor(written); + if (low) { + log(`${tag}: stopped — ${low}. A re-run resumes.`); + return { status: "stopped", reason: low }; + } + await assertSavedVideosStoreWritable(opts.paths, pointer.dir); + const out = path.join(scratch, c.file); + const part = `${out}.part`; + await rm(part, { force: true }); + log(`${tag}: chunk ${c.index + 1}/${state.chunks.length} (${c.from.toFixed(1)}–${c.to.toFixed(1)} s, ${c.expectedFrames} frames)…`); + // A chunk short or long is encoded once more; twice is a verdict. + for (let attempt = 1; ; attempt += 1) { + try { + await deps.encodeChunk({ src, chunk: c, settings: enc, out: part, signal }); + } catch (err) { + await rm(part, { force: true }).catch(() => {}); + if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; + throw err; + } + const frames = await deps.countFrames(part); + if (frames === c.expectedFrames) break; + await rm(part, { force: true }); + if (attempt >= 2) { + throw new VerifyFailure(`chunk ${c.index} holds ${frames} frames, not the ${c.expectedFrames} expected (encoded twice)`); + } + log(`${tag}: chunk ${c.index} holds ${frames} frames, not ${c.expectedFrames} — encoding it again.`); + } + await rename(part, out); + c.bytes = (await stat(out)).size; + c.done = true; + await writeState(); + } + + // ---- 3. the mux ---- + if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; + const listFile = path.join(scratch, "chunks.txt"); + await writeFile(listFile, concatList(state.chunks.map((c) => path.join(scratch, c.file)))); + const muxed = path.join(scratch, "compacted.mp4"); + await rm(muxed, { force: true }); + log(`${tag}: joining ${state.chunks.length} chunk(s), the source's audio copied…`); + await deps.mux({ list: listFile, src, videoStart: probe.videoStart, out: muxed, signal }); + + // ---- 4. verify ---- + const { checks, fresh: freshClock } = await verify({ ...opts, deps, tag, state, src, muxed, probe, fps, videoDir, pointer, scratch, log }); + + // ---- 5. the swap ---- + const at = deps.now(); + const resultSha = await deps.sha256(muxed, signal); + const resultProbe = await deps.probe(muxed); + const resultBytes = (await stat(muxed)).size; + await assertSavedVideosStoreWritable(opts.paths, pointer.dir); + const name = compactedFileName(at, await readdir(pointer.dir).catch(() => [])); + const final = path.join(pointer.dir, name); + const encoder = await deps.encoderBanner().catch(() => "ffmpeg"); + const original: SavedVideoAlternate = { + file: pointer.file, + bytes: pointer.bytes, + storedAt: pointer.storedAt, + setAsideAt: at.toISOString(), + ...(probe.seconds ? { seconds: probe.seconds } : {}), + ...(probe.height ? { height: probe.height } : {}), + ...(probe.vcodec ? { vcodec: probe.vcodec } : {}), + ...(pointer.origin ? { origin: pointer.origin } : {}), + ...(pointer.format?.preset ? { preset: pointer.format.preset } : {}), + keptAs: "original", + sha256: state.sourceSha256!, + }; + const compacted: SavedVideoCompacted = { + at: at.toISOString(), + tool: COMPACTION_TOOL, + encoder, + settings: { + codec: "av1", + encoder: "libsvtav1", + preset: s.preset, + crf: s.crf, + gopSeconds: COMPACT_GOP_SECONDS, + pixFmt: COMPACT_PIX_FMT, + fps, + audio: "copy", + chunkSeconds: s.chunkMinutes * 60, + }, + source: { + file: pointer.file, + bytes: pointer.bytes, + sha256: state.sourceSha256!, + ...(probe.vcodec ? { vcodec: probe.vcodec } : {}), + ...(probe.height ? { height: probe.height } : {}), + ...(probe.fps ? { fps: probe.fps } : {}), + ...(probe.seconds ? { seconds: probe.seconds } : {}), + frames: state.sourceFrames, + ...(probe.videoKbps ? { videoKbps: probe.videoKbps } : {}), + ...(pointer.format ? { format: pointer.format } : {}), + }, + result: { + file: name, + bytes: resultBytes, + sha256: resultSha, + vcodec: resultProbe?.vcodec ?? "av1", + ...(resultProbe?.height ? { height: resultProbe.height } : {}), + ...(resultProbe?.fps ? { fps: resultProbe.fps } : {}), + ...(resultProbe?.seconds ? { seconds: resultProbe.seconds } : {}), + frames: checks.frames[1], + ...(resultProbe?.videoKbps ? { videoKbps: resultProbe.videoKbps } : {}), + }, + checks, + chunks: state.chunks.length, + }; + const pointerFile = savedVideoPointerPath(videoDir); + const swapped = await withJsonFileLock(pointerFile, async () => { + const read = await readJsonFile(pointerFile); + const raw = read.ok && read.value && typeof read.value === "object" ? { ...(read.value as Record<string, unknown>) } : null; + if (!raw || raw.file !== pointer.file || raw.bytes !== pointer.bytes || raw.dir !== pointer.dir) { + return false; + } + await rename(muxed, final); + raw.file = name; + raw.bytes = resultBytes; + raw.sha256 = resultSha; + raw.compacted = compacted; + raw.probed = { + ...(resultProbe?.seconds ? { seconds: resultProbe.seconds } : {}), + ...(resultProbe?.height ? { height: resultProbe.height } : {}), + }; + // `format` says what the ACTIVE copy is: the same asked-for preset, + // the re-encode's height and codec (the download's is in + // `compacted.source.format`). + if (raw.format && typeof raw.format === "object") { + raw.format = { + ...(raw.format as Record<string, unknown>), + ...(resultProbe?.height ? { height: resultProbe.height } : {}), + vcodec: "av1", + }; + } + raw.alternates = [...(Array.isArray(raw.alternates) ? raw.alternates : []), original]; + await writeJsonAtomic(pointerFile, raw); + return true; + }); + if (!swapped) { + await rm(muxed, { force: true }); + return { status: "failed", reason: "the saved copy changed while it was being compacted (the pointer names other bytes now): nothing swapped" }; + } + // The clock map, measured against the re-encode during the checks, is now + // the one about the active copy. + if (checks.clock === "kept" && freshClock) { + await recordingClockSidecar.write(videoDir, { + ...freshClock, + target: { file: name, bytes: resultBytes }, + }); + } + await rm(scratch, { recursive: true, force: true }); + const swappedPointer = (await loadSavedVideo(videoDir))!; + log( + `compacted ${tag}: ${formatBytes(pointer.bytes)} ${probe.vcodec ?? "?"} ${probe.height ?? "?"}p${probe.fps ? Math.round(probe.fps) : ""} → ` + + `${formatBytes(resultBytes)} AV1 crf ${s.crf}${fps ? ` ${fps} fps` : ""} (${Math.round((resultBytes / pointer.bytes) * 100)}%), ` + + `${checks.frames[1]}/${checks.frames[2]} frames, audio copied (identical), ${checks.quality.metric.toUpperCase()} ` + + `${checks.quality.mean.toFixed(checks.quality.metric === "vmaf" ? 1 : 3)} (worst excerpt ${checks.quality.min.toFixed(checks.quality.metric === "vmaf" ? 1 : 3)}); ` + + `the original is kept as ${pointer.file} until it is dropped.`, + ); + + // ---- 6 and 7: the recheck, then the drop — each its own step ---- + const after = await afterSwap({ paths: opts.paths, videoDir, settings: s, deps, log, tag, signal }); + return { status: "compacted", line: `compacted ${tag}`, pointer: (await loadSavedVideo(videoDir)) ?? swappedPointer, ...after }; + } catch (err) { + if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; + if (!(err instanceof VerifyFailure)) { + // Not a verdict on the re-encode (ffmpeg died, a disk error, the store + // started moving): the chunks already encoded stay for the re-run; only + // a half-written mux goes. + await rm(path.join(scratch, "compacted.mp4"), { force: true }).catch(() => {}); + const reason = (err as Error).message; + log(`${tag}: NOT compacted — ${reason}. The original stays the active copy, untouched; a re-run resumes from the chunks done.`); + return { status: "failed", reason }; + } + const reason = `verification failed: ${err.message}`; + // A VERDICT: the original stays active and untouched; the output goes, and + // the reason stays beside the source for the next plan. + await rm(scratch, { recursive: true, force: true }).catch(() => {}); + await mkdir(scratch, { recursive: true }).catch(() => {}); + await writeJsonAtomic(path.join(scratch, FAILED_FILENAME), { + at: deps.now().toISOString(), + reason: err.message, + settingsKey, + checks: err.checks, + }).catch(() => {}); + log(`${tag}: NOT compacted — ${reason}. The original stays the active copy, untouched; the re-encode was removed.`); + return { status: "failed", reason }; + } +} + +async function verify(o: { + paths: Paths; + settings: SavedVideoCompactionSettings; + deps: Required<CompactDeps>; + tag: string; + state: CompactState; + src: string; + muxed: string; + probe: SourceProbe; + fps: number | null; + videoDir: string; + pointer: SavedVideoPointer; + scratch: string; + log: (s: string) => void; + signal?: AbortSignal; +}): Promise<{ checks: SavedVideoCompactedChecks; fresh: RecordingClock | null }> { + const { deps, tag, state, settings: s, log, signal } = o; + const checks: Partial<SavedVideoCompactedChecks> = { passed: false }; + const fail = (why: string): never => { + throw new VerifyFailure(why, checks); + }; + let fresh: RecordingClock | null = null; + log(`${tag}: verifying — a full decode first…`); + const dec = await deps.fullDecode(o.muxed, signal); + checks.decoded = dec.ok; + if (!dec.ok) fail(`the re-encode does not decode cleanly: ${dec.why ?? "errors"}`); + + // Length and frames, from both files' packets. + const outScan = await deps.scan(o.muxed, signal); + const n = outScan.pts.length; + const outStep = n > 1 ? outScan.pts[n - 1] - outScan.pts[n - 2] : 1 / (o.fps ?? o.probe.fps ?? 30); + const srcSeconds = state.sourceLastPts + state.sourceFrameStep - state.sourceFirstPts; + const outSeconds = n ? outScan.pts[n - 1] + outStep - outScan.pts[0] : 0; + const frameTol = 1 / (o.fps ?? o.probe.fps ?? 30) + 1e-3; + checks.seconds = [round(srcSeconds), round(outSeconds)]; + checks.secondsTolerance = round(frameTol, 4); + const expected = state.chunks.reduce((x, c) => x + c.expectedFrames, 0); + checks.frames = [state.sourceFrames, n, expected]; + if (n !== expected) fail(`the re-encode holds ${n} frames, not the ${expected} the source's ${state.sourceFrames} give${o.fps ? ` at ${o.fps} fps` : ""}`); + if (Math.abs(outSeconds - srcSeconds) > frameTol) { + fail(`the re-encode's video lasts ${outSeconds.toFixed(3)} s, the source's ${srcSeconds.toFixed(3)} s (more than a frame apart)`); + } + if (n && Math.abs(outScan.pts[0] - state.sourceFirstPts) > frameTol / 2) { + fail(`the re-encode's first frame is at ${outScan.pts[0].toFixed(3)} s, the source's at ${state.sourceFirstPts.toFixed(3)} s`); + } + log(`${tag}: ${n}/${expected} frames, ${outSeconds.toFixed(3)} s against ${srcSeconds.toFixed(3)} s.`); + + // The audio, copied: identical packets, identical timing. + const [a, b] = await Promise.all([deps.audioHash(o.src, signal), deps.audioHash(o.muxed, signal)]); + checks.audio = "identical"; + checks.audioHash = b.data; + if (a.packets !== b.packets || a.data !== b.data || a.timing !== b.timing || a.firstPts !== b.firstPts) { + fail( + `the audio is not the source's packet for packet (${a.packets} → ${b.packets} packets` + + `${a.data !== b.data ? ", different bytes" : ""}${a.timing !== b.timing || a.firstPts !== b.firstPts ? ", different timing" : ""})`, + ); + } + log(`${tag}: audio identical (${b.packets} packets).`); + + // Quality on excerpts spread through the file. + const metric: "vmaf" | "ssim" = (await deps.hasVmaf().catch(() => false)) ? "vmaf" : "ssim"; + const outFps = o.fps ?? o.probe.fps ?? 30; + const times = sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps); + const scores: number[] = []; + for (const at of times) { + if (signal?.aborted) throw new Error("cancelled"); + scores.push(await deps.score({ compacted: o.muxed, source: o.src, at, seconds: EXCERPT_SECONDS, fps: o.fps, metric, scratchDir: o.scratch, signal })); + } + const mean = scores.reduce((x, y) => x + y, 0) / Math.max(1, scores.length); + const min = Math.min(...scores); + const [minMean, minSample] = metric === "vmaf" ? [s.vmafMinMean, s.vmafMinSample] : [s.ssimMinMean, s.ssimMinSample]; + checks.quality = { metric, mean: round(mean), min: round(min), samples: scores.length, minMean, minSample }; + if (mean < minMean || min < minSample) { + fail(`${metric.toUpperCase()} ${mean.toFixed(2)} mean, ${min.toFixed(2)} at its worst excerpt (needs ${minMean} and ${minSample})`); + } + log(`${tag}: ${metric.toUpperCase()} ${mean.toFixed(2)} mean over ${scores.length} excerpts, worst ${min.toFixed(2)}.`); + + // A real window cut from each, compared. + const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps); + checks.cuts = []; + checks.cutSsimMin = CUT_SSIM_MIN; + for (const at of cutTimes) { + const ssim = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, seconds: CUT_SECONDS, fps: o.fps, scratchDir: o.scratch, signal }); + checks.cuts.push({ at, ssim: round(ssim, 4) }); + if (ssim < CUT_SSIM_MIN) fail(`a window cut at ${at.toFixed(1)} s from the re-encode differs from the same cut of the original (SSIM ${ssim.toFixed(3)} < ${CUT_SSIM_MIN})`); + } + log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter match the original's.`); + + // The recording clock. + checks.clock = "none"; + const plan = await planRecordingClock(o.videoDir).catch(() => null); + if (plan?.kind === "current") { + const old = plan.clock; + const targetBytes = (await stat(o.muxed)).size; + const okAnchors = (old.anchors ?? []).filter((x: { ok?: boolean }) => x.ok).map((x: { at: number }) => x.at); + fresh = await deps.measureClock({ + videoDir: o.videoDir, + source: plan.source, + container: o.muxed, + sourceBytes: old.source.bytes, + targetBytes, + transcribedAt: old.cues?.transcribedAt ?? null, + extra: okAnchors, + signal, + }); + const tol = old.params?.tolerance ?? 0.08; + const now = fresh; + const moved = okAnchors.find((t: number) => Math.abs(clockOffsetAt(old, t).offset - clockOffsetAt(now, t).offset) > tol); + if (now.ok !== old.ok || moved !== undefined) { + fail( + moved !== undefined + ? `the recording clock moved: at ${moved.toFixed(1)} s the map against the re-encode is ${clockOffsetAt(now, moved).offset.toFixed(3)} s, against the original ${clockOffsetAt(old, moved).offset.toFixed(3)} s` + : `the recording clock's map is ${now.ok ? "ok" : "NOT ok"} against the re-encode and ${old.ok ? "ok" : "NOT ok"} against the original`, + ); + } + checks.clock = "kept"; + log(`${tag}: the recording clock re-measured against the re-encode: within ${tol} s of the old map at ${okAnchors.length} anchor(s).`); + } else if (plan?.kind === "measure") { + checks.clock = "stale"; + } + checks.passed = true; + return { checks: checks as SavedVideoCompactedChecks, fresh }; +} + +// --- after the swap ------------------------------------------------------------ + +// THE SECOND CHECK (a step of its own): the pointer read back from disk, and +// the file it names — its size, its sha256 against the recorded one, the +// container opening, its length against the verified one. Recorded as +// `compacted.recheck`. Answers the verified sha256 when it held. +export async function recheckCompactedCopy(opts: { + paths: Paths; + videoDir: string; + deps?: CompactDeps; + signal?: AbortSignal; + record?: boolean; +}): Promise<{ ok: true; sha256: string } | { ok: false; why: string }> { + const deps = resolveDeps(opts.paths, opts.deps); + const pointer = await loadSavedVideo(opts.videoDir); + const c = pointer?.compacted; + let res: { ok: true; sha256: string } | { ok: false; why: string }; + if (!pointer || !c) { + res = { ok: false, why: "the pointer names no compacted copy" }; + } else if (pointer.file !== c.result.file) { + res = { ok: false, why: `the pointer names ${pointer.file}, not the compacted ${c.result.file}` }; + } else { + const file = savedVideoPath(pointer); + const st = await stat(file).catch(() => null); + if (!st?.isFile()) res = { ok: false, why: `${file} is not there` }; + else if (st.size !== pointer.bytes || st.size !== c.result.bytes) res = { ok: false, why: `${pointer.file} is ${st.size} bytes, ${c.result.bytes} recorded` }; + else { + const sha = await deps.sha256(file, opts.signal); + const p = await deps.probe(file); + const want = c.result.seconds; + if (sha !== pointer.sha256 || sha !== c.result.sha256) res = { ok: false, why: `${pointer.file}'s sha256 is ${sha.slice(0, 12)}…, ${c.result.sha256.slice(0, 12)}… recorded` }; + else if (!p || !p.hasVideo) res = { ok: false, why: `${pointer.file} does not open as a video` }; + else if (want && p.seconds && Math.abs(p.seconds - want) > Math.max(0.05, c.checks.secondsTolerance)) { + res = { ok: false, why: `${pointer.file} lasts ${p.seconds} s, ${want} s recorded` }; + } else res = { ok: true, sha256: sha }; + } + } + if (opts.record !== false && pointer?.compacted) { + const pointerFile = savedVideoPointerPath(opts.videoDir); + await withJsonFileLock(pointerFile, async () => { + const read = await readJsonFile(pointerFile); + if (!read.ok || !read.value || typeof read.value !== "object") return; + const raw = { ...(read.value as Record<string, unknown>) }; + if (!raw.compacted || typeof raw.compacted !== "object") return; + raw.compacted = { + ...(raw.compacted as Record<string, unknown>), + recheck: { at: deps.now().toISOString(), ok: res.ok, ...(res.ok ? {} : { why: res.why }) }, + }; + await writeJsonAtomic(pointerFile, raw); + }); + } + return res; +} + +export function reviewStateOf(pointer: SavedVideoPointer, onPlatform: boolean, dropOriginal: SavedVideoCompactionSettings["dropOriginal"]): CompactionReviewState | null { + if (!pointer.compacted) return null; + const original = compactedOriginalOf(pointer); + if (!original) return "dropped"; + if (!onPlatform) return original.review ? "reviewed" : "awaiting-review"; + if (original.review) return "reviewed"; + return dropOriginal === "keep" ? "kept" : "drop-pending"; +} + +async function afterSwap(o: { + paths: Paths; + videoDir: string; + settings: SavedVideoCompactionSettings; + deps: Required<CompactDeps>; + log: (s: string) => void; + tag: string; + signal?: AbortSignal; +}): Promise<{ dropped: boolean; review: CompactionReviewState }> { + const { log, tag } = o; + const recheck = await recheckCompactedCopy({ paths: o.paths, videoDir: o.videoDir, deps: o.deps, ...(o.signal ? { signal: o.signal } : {}) }); + const pointer = (await loadSavedVideo(o.videoDir))!; + const original = compactedOriginalOf(pointer); + const availability = await o.deps.availability(o.videoDir); + const onPlatform = isStillOnPlatform(availability); + if (!recheck.ok) { + log(`${tag}: the re-check after the swap FAILED (${recheck.why}): the original ${original?.file ?? "?"} is kept.`); + return { dropped: false, review: reviewStateOf(pointer, onPlatform, o.settings.dropOriginal) ?? "drop-pending" }; + } + log(`${tag}: re-checked from disk: ${pointer.file} is ${pointer.bytes} bytes, sha256 ${recheck.sha256.slice(0, 12)}…, opens and lasts as verified.`); + if (!original) return { dropped: false, review: "dropped" }; + if (o.settings.dropOriginal !== "after-verify") { + log(`${tag}: dropOriginal is "keep": the original ${original.file} stays until a person drops it.`); + return { dropped: false, review: reviewStateOf(pointer, onPlatform, "keep")! }; + } + if (!onPlatform) { + log( + `${tag}: not known to be on its platform (availability ${availability ?? "unknown"}): the original ${original.file} ` + + "is NOT dropped — it waits for a person's review (get compaction-review).", + ); + return { dropped: false, review: reviewStateOf(pointer, onPlatform, o.settings.dropOriginal)! }; + } + try { + const r = await dropSavedAlternate(o.videoDir, original.file, { + confirmOriginal: true, + verifiedActive: { sha256: recheck.sha256 }, + by: "compact-saved-videos (after-verify)", + availability, + paths: o.paths, + }); + log(`${tag}: the original ${original.file} dropped (${formatBytes(r.bytes)} freed; sha256 ${original.sha256?.slice(0, 12) ?? "?"}… recorded on the pointer).`); + return { dropped: true, review: "dropped" }; + } catch (err) { + if (!(err instanceof SavedAlternateRefusal)) throw err; + log(`${tag}: the original ${original.file} is kept: ${err.message}`); + return { dropped: false, review: reviewStateOf(pointer, onPlatform, o.settings.dropOriginal) ?? "drop-pending" }; + } +} + +// --- the job's body ------------------------------------------------------------ + +export type CompactSavedVideosResult = { + compacted: { slug: string; id: string; dropped: boolean; review: CompactionReviewState }[]; + skipped: { slug: string; id: string; reason: string }[]; + failed: { slug: string; id: string; reason: string }[]; + stopped?: string; +}; + +// Each item in turn, one at a time. +export async function compactSavedVideos( + opts: CompactRunOptions & { items: CompactItem[]; mode: "explicit" | "select"; retryFailed?: boolean }, +): Promise<CompactSavedVideosResult> { + const result: CompactSavedVideosResult = { compacted: [], skipped: [], failed: [] }; + for (const item of opts.items) { + if (opts.signal?.aborted) { + result.stopped = "cancelled"; + break; + } + if (opts.drainSignal?.aborted) { + result.stopped = "drained"; + break; + } + const r = await compactOne({ ...opts, item }); + if (r.status === "compacted") result.compacted.push({ ...item, dropped: r.dropped, review: r.review }); + else if (r.status === "skipped") result.skipped.push({ ...item, reason: r.reason }); + else if (r.status === "failed") result.failed.push({ ...item, reason: r.reason }); + else { + result.stopped = r.reason; + break; + } + } + opts.onLog( + `summary: ${JSON.stringify({ + compacted: result.compacted, + skipped: result.skipped.length, + failed: result.failed, + ...(result.stopped ? { stopped: result.stopped } : {}), + })}\n`, + ); + return result; +} + +// The settings in force for a run: settings.json's, each override applied +// through the same sanitizer. +export function effectiveCompactionSettings( + base: SavedVideoCompactionSettings, + overrides: Partial<Pick<SavedVideoCompactionSettings, "crf" | "preset" | "maxFps" | "chunkMinutes">> = {}, +): SavedVideoCompactionSettings { + return sanitizeSavedVideoCompaction({ ...base, ...Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined)) }); +} + +// --- the review list ------------------------------------------------------------- + +export type CompactionReviewRow = { + slug: string; + id: string; + state: CompactionReviewState; + line: string; + availability: Availability | null; + onPlatform: boolean; + original?: SavedVideoAlternate; + compactedAt: string; + bytes: number; + sourceBytes: number; + checksPassed: boolean; + recheck?: SavedVideoCompacted["recheck"]; +}; + +// Every compacted video, with what its original is waiting for. +export async function listCompactionReview(opts: { + paths: Paths; + dropOriginal: SavedVideoCompactionSettings["dropOriginal"]; + channelSlug?: string; + notAnswering?: string[]; + deps?: Pick<CompactDeps, "availability">; +}): Promise<CompactionReviewRow[]> { + const availabilityOf = opts.deps?.availability ?? ((d: string) => resolveEffectiveAvailability(d).catch(() => null)); + const entries = await listSavedVideos({ + paths: opts.paths, + ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}), + ...(opts.notAnswering ? { notAnswering: opts.notAnswering } : {}), + }); + const rows: CompactionReviewRow[] = []; + for (const e of entries) { + const c = e.pointer.compacted; + if (!c) continue; + const availability = await availabilityOf(e.videoDir); + const onPlatform = isStillOnPlatform(availability); + const original = compactedOriginalOf(e.pointer) ?? undefined; + rows.push({ + slug: e.slug, + id: e.videoId, + state: reviewStateOf(e.pointer, onPlatform, opts.dropOriginal)!, + line: compactedLine(e.pointer) ?? "", + availability, + onPlatform, + ...(original ? { original } : {}), + compactedAt: c.at, + bytes: e.pointer.bytes, + sourceBytes: c.source.bytes, + checksPassed: c.checks.passed, + ...(c.recheck ? { recheck: c.recheck } : {}), + }); + } + return rows; +} diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -1571,6 +1571,25 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "custom", needsMedia: true, }, + // COMPACT SAVED VIDEOS (controller/compactSavedVideos.ts): a deliberately + // stored container re-encoded to AV1 in keyframe-aligned chunks, verified, + // swapped in as the active copy, its original kept beside it (and dropped + // only in a later step, by the rules there). Media: it reads and writes the + // store. Drainable: it stops between chunks, and a re-run — a replay, or the + // boot pass after an interruption — resumes at the first chunk not encoded + // (`.compact-scratch/state.json`); a video already compacted is skipped. An + // INGEST kind: the pointer it rewrites is what a playable build reads. ONE + // QUEUE MACHINE-WIDE (`compact`), so one video at a time; each chunk also + // takes the heavy slot, so builds, e2e and renders interleave. + "compact-saved-videos": { + kind: "compact-saved-videos", + label: "Compact saved videos", + drainable: true, + replayable: true, + queueKeyStrategy: "custom", + needsMedia: true, + resumeOnBoot: true, + }, }; export function getJobKind(kind: string): JobKindMeta | undefined { @@ -1645,6 +1664,7 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ "attach-media", "import-local-media", "prepare-playable", + "compact-saved-videos", // A gone video's audio from a copy, and the copy's provenance (release 31). "fetch-copies", // One video's live chat replay, normalized into the cues the index reads diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -277,6 +277,7 @@ export type ChannelConfig = { remoteArchive?: string; remoteUrl?: string; excludeFromCleanup?: boolean; + excludeFromCompaction?: boolean; cleanAfterCaptureUnverified?: boolean; syncIntervalMinutes?: number; fullSweepIntervalMinutes?: number; @@ -362,6 +363,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { "a remote-only channel has no `url`, so nothing syncs it.", excludeFromCleanup: "Leave this channel's reclaimable bytes out of the aggregate \"cleanable data\" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes.", + excludeFromCompaction: + "Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false.", cleanAfterCaptureUnverified: "Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel (\"no source to check: clean by hand\") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held.", syncIntervalMinutes: @@ -591,6 +594,7 @@ export const CHANNEL_CONFIG_COERCIONS: { remoteArchive: trimmedNonBlank, remoteUrl: trimmedNonBlank, excludeFromCleanup: bool, + excludeFromCompaction: bool, cleanAfterCaptureUnverified: bool, syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES), fullSweepIntervalMinutes: zeroOrClamped( diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -72,6 +72,7 @@ export const channelConfigObjectSchema = z.object({ remoteArchive: field("remoteArchive"), remoteUrl: field("remoteUrl"), excludeFromCleanup: field("excludeFromCleanup"), + excludeFromCompaction: field("excludeFromCompaction"), cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"), syncIntervalMinutes: field("syncIntervalMinutes"), fullSweepIntervalMinutes: field("fullSweepIntervalMinutes"), diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts @@ -0,0 +1,518 @@ +// COMPACTING A SAVED VIDEO — the ffmpeg/ffprobe half +// (controller/compactSavedVideos.ts runs it; lib/savedVideoCompaction.ts is +// the pure half: settings, selector, estimate, names). +// +// Every function here reads or writes one file and answers a number; none of +// them knows about pointers. The encoder's runs, the full decode and the +// quality scoring each take the HEAVY SLOT (scripts/queue-lock.mjs --heavy +// --estimate <MB>, which also waits while render mode holds the machine) and +// run niced; the probes and the packet scans are demux-only and do not. +// +// SERVER-ONLY. + +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { readFile, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { execa } from "execa"; +import type { Paths } from "./paths"; +import type { CompactionProbe } from "./savedVideoCompaction"; +import { evidenceCutArgs } from "./evidenceClip-server"; +import "./childKillGuard"; + +// Memory each kind of run is admitted to the heavy slot with: one SVT-AV1 +// preset 8 1080p60 encode peaked at about 1.0 GB RSS (design note §3). +export const CHUNK_ESTIMATE_MB = 1500; +export const DECODE_ESTIMATE_MB = 800; +export const SCORE_ESTIMATE_MB = 1500; + +export type GatedPaths = Pick<Paths, "ffmpegBin" | "ffprobeBin" | "monorepoRoot">; + +async function gateOf(paths: Pick<Paths, "monorepoRoot">): Promise<string | null> { + if (!paths.monorepoRoot) return null; + const gate = path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs"); + return (await stat(gate).then((s) => s.isFile()).catch(() => false)) ? gate : null; +} + +// One ffmpeg run, behind the heavy slot when the checkout has the gate (a +// test's temp root has none: ffmpeg runs directly), niced. The gate forwards a +// cancel. Answers stderr; throws with its tail on a non-zero exit. +export async function runHeavyFfmpeg( + paths: GatedPaths, + args: string[], + opts: { estimateMB: number; signal?: AbortSignal; nice?: boolean }, +): Promise<string> { + const gate = await gateOf(paths); + const inner = [...(opts.nice !== false ? ["nice", "-n", "10"] : []), paths.ffmpegBin, ...args]; + const [bin, ...argv] = gate + ? [process.execPath, gate, "--heavy", "--estimate", String(opts.estimateMB), "--", ...inner] + : inner; + const r = await execa(bin, argv, { reject: false, ...(opts.signal ? { cancelSignal: opts.signal } : {}) }); + if (opts.signal?.aborted) throw new Error("cancelled"); + if (r.exitCode !== 0) { + const tail = String(r.stderr ?? "").trim().split("\n").slice(-3).join(" | "); + throw new Error(`ffmpeg failed (exit ${r.exitCode ?? "?"})${tail ? `: ${tail}` : ""}`); + } + return String(r.stderr ?? ""); +} + +// --- capability ------------------------------------------------------------- + +export async function ffmpegVersionLine(ffmpegBin: string): Promise<string> { + const r = await execa(ffmpegBin, ["-hide_banner", "-version"], { reject: false }); + return String(r.stdout ?? "").split("\n")[0]?.trim() || "ffmpeg (version unknown)"; +} + +export async function ffmpegHas(ffmpegBin: string, kind: "encoders" | "filters", name: string): Promise<boolean> { + const r = await execa(ffmpegBin, ["-hide_banner", `-${kind}`], { reject: false }); + return new RegExp(`\\s${name}\\s`).test(String(r.stdout ?? "")); +} + +// --- probing ---------------------------------------------------------------- + +function rate(v: unknown): number | null { + if (typeof v !== "string") return null; + const [n, d] = v.split("/").map(Number); + const x = d ? n / d : n; + return Number.isFinite(x) && x > 0 ? Number(x.toFixed(3)) : null; +} + +function numOr(v: unknown): number | null { + const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN; + return Number.isFinite(n) ? n : null; +} + +export type SourceProbe = CompactionProbe & { + videoStart: number; + audioStreams: number; + bytes: number; +}; + +// One ffprobe of a container: what the selector, the estimate and the encode +// need. Null when ffprobe cannot read it. +export async function probeCompactionSource(ffprobeBin: string, file: string): Promise<SourceProbe | null> { + const r = await execa(ffprobeBin, ["-v", "error", "-show_streams", "-show_format", "-of", "json", file], { + reject: false, + }); + if (r.exitCode !== 0) return null; + let doc: { + streams?: Record<string, unknown>[]; + format?: Record<string, unknown>; + }; + try { + doc = JSON.parse(String(r.stdout)); + } catch { + return null; + } + const streams = doc.streams ?? []; + const v = streams.find( + (s) => s.codec_type === "video" && !(s.disposition as { attached_pic?: number } | undefined)?.attached_pic, + ); + const audios = streams.filter((s) => s.codec_type === "audio"); + const bytes = numOr(doc.format?.size) ?? (await stat(file).then((s) => s.size).catch(() => 0)); + const seconds = numOr(doc.format?.duration); + const audioKbps = audios.reduce((n, a) => n + (numOr(a.bit_rate) ?? 0) / 1000, 0) || null; + let videoKbps = v ? (numOr(v.bit_rate) ?? null) : null; + if (videoKbps !== null) videoKbps /= 1000; + else if (v && seconds) { + // No per-stream bitrate (an mkv, a webm): the container's, less the audio. + videoKbps = Math.max(0, (bytes * 8) / seconds / 1000 - (audioKbps ?? 0)); + } + return { + hasVideo: v !== undefined, + vcodec: typeof v?.codec_name === "string" ? v.codec_name : null, + width: typeof v?.width === "number" ? v.width : null, + height: typeof v?.height === "number" ? v.height : null, + fps: v ? (rate(v.avg_frame_rate) ?? rate(v.r_frame_rate)) : null, + seconds: seconds && seconds > 0 ? seconds : null, + videoKbps: videoKbps !== null ? Number(videoKbps.toFixed(1)) : null, + audioKbps: audioKbps !== null ? Number(audioKbps.toFixed(1)) : null, + videoStart: (v ? numOr(v.start_time) : null) ?? 0, + audioStreams: audios.length, + bytes, + }; +} + +export type PacketScan = { + // Every video packet's pts (seconds), ascending. + pts: Float64Array; + // The keyframes' pts, ascending. + keyframes: number[]; +}; + +// The video stream's packets, demuxed (not decoded): the frame count and the +// keyframes a chunk may start on. About a minute on a 12 GB file. +export async function scanVideoPackets(ffprobeBin: string, file: string, signal?: AbortSignal): Promise<PacketScan> { + const all: number[] = []; + const keyframes: number[] = []; + await new Promise<void>((resolve, reject) => { + const child = spawn( + ffprobeBin, + ["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time,flags", "-of", "csv=p=0", file], + { stdio: ["ignore", "pipe", "pipe"] }, + ); + let carry = ""; + let err = ""; + const onAbort = () => child.kill("SIGKILL"); + signal?.addEventListener("abort", onAbort, { once: true }); + const take = (line: string) => { + const [t, flags] = line.split(","); + const x = Number(t); + if (!Number.isFinite(x)) return; + all.push(x); + if (flags?.includes("K")) keyframes.push(x); + }; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (d: string) => { + const lines = (carry + d).split("\n"); + carry = lines.pop() ?? ""; + for (const l of lines) take(l.trim()); + }); + child.stderr.on("data", (d: Buffer) => (err = (err + d.toString()).slice(-2000))); + child.on("error", reject); + child.on("close", (code) => { + signal?.removeEventListener("abort", onAbort); + if (carry.trim()) take(carry.trim()); + if (signal?.aborted) reject(new Error("cancelled")); + else if (code !== 0) reject(new Error(`ffprobe could not scan ${path.basename(file)}: ${err.trim()}`)); + else resolve(); + }); + }); + const pts = Float64Array.from(all).sort(); + keyframes.sort((a, b) => a - b); + return { pts, keyframes }; +} + +// The number of video packets (frames) in a file, demuxed. +export async function countVideoFrames(ffprobeBin: string, file: string): Promise<number> { + const r = await execa( + ffprobeBin, + ["-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", file], + { reject: false }, + ); + const n = Number(String(r.stdout ?? "").trim().split(/[\s,]/)[0]); + if (r.exitCode !== 0 || !Number.isFinite(n)) throw new Error(`ffprobe could not count the frames of ${path.basename(file)}`); + return n; +} + +// --- chunks ----------------------------------------------------------------- + +export type ChunkPlan = { + index: number; + // Source seconds: `from` is a keyframe's pts; `to` the next chunk's, or past + // the end for the last. + from: number; + to: number; + // Source frames in [from, to). + sourceFrames: number; + // Frames the chunk must hold: the source's, or the fps filter's count. + expectedFrames: number; +}; + +function countIn(pts: Float64Array, from: number, to: number): number { + // pts is sorted: two binary searches. + const lower = (x: number) => { + let lo = 0; + let hi = pts.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (pts[mid] < x) lo = mid + 1; + else hi = mid; + } + return lo; + }; + return lower(to) - lower(from); +} + +const EDGE = 1e-4; + +// Chunks of about `chunkSeconds`, each starting on a source keyframe. A chunk +// is never shorter than half the asked length unless it is the only one. +export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null): ChunkPlan[] { + const { pts, keyframes } = scan; + if (!pts.length) return []; + const first = pts[0]; + const end = pts[pts.length - 1] + 1; + const starts = [keyframes.length ? Math.min(keyframes[0], first) : first]; + for (const k of keyframes) { + if (k - starts[starts.length - 1] >= chunkSeconds - EDGE) starts.push(k); + } + const plans: ChunkPlan[] = []; + for (let i = 0; i < starts.length; i += 1) { + const from = starts[i]; + const to = i + 1 < starts.length ? starts[i + 1] : end; + const sourceFrames = countIn(pts, from - EDGE, to - EDGE); + plans.push({ + index: i, + from, + to, + sourceFrames, + expectedFrames: outFps ? framesAtFps(pts, from, to, outFps, i + 1 === starts.length) : sourceFrames, + }); + } + return plans; +} + +// The fps filter's frame count over a span: one frame per 1/fps step of the +// output clock, which starts at the span's first source frame. +function framesAtFps(pts: Float64Array, from: number, to: number, fps: number, last: boolean): number { + if (!last) return Math.round((to - from) * fps); + // The last chunk ends with the source's last frame, which lasts one source + // frame: the span is [from, lastPts + 1 source frame). + const n = pts.length; + const step = n > 1 ? pts[n - 1] - pts[n - 2] : 1 / fps; + return Math.round((pts[n - 1] + step - from) * fps); +} + +export type EncodeSettings = { + preset: number; + crf: number; + gopSeconds: number; + pixFmt: string; + // The output frame rate when the source's is capped, else null. + fps: number | null; + sourceFps: number; +}; + +// One chunk: an input seek to the chunk's keyframe (exact — a keyframe is a +// place the decoder can start), the video only, the frame count fixed, into a +// Matroska file the concat demuxer joins. +export function encodeChunkArgs(src: string, chunk: ChunkPlan, s: EncodeSettings, out: string): string[] { + const outFps = s.fps ?? s.sourceFps; + const gop = Math.max(1, Math.round(s.gopSeconds * outFps)); + return [ + "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-ss", Math.max(0, chunk.from - 0.001).toFixed(6), + "-i", src, + "-map", "0:v:0", "-an", "-sn", "-dn", + ...(s.fps ? ["-vf", `fps=${s.fps}`] : []), + "-frames:v", String(chunk.expectedFrames), + "-c:v", "libsvtav1", "-preset", String(s.preset), "-crf", String(s.crf), + "-g", String(gop), "-pix_fmt", s.pixFmt, + "-f", "matroska", out, + ]; +} + +// The chunks joined (concat demuxer, `-c copy`), the source's video start kept, +// and EVERY AUDIO STREAM OF THE SOURCE COPIED bit for bit — never re-encoded +// (a later transcription hears the same samples, at the same seconds). +export function muxArgs(listFile: string, src: string, videoStart: number, out: string): string[] { + return [ + "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + ...(videoStart > 0 ? ["-itsoffset", videoStart.toFixed(6)] : []), + "-f", "concat", "-safe", "0", "-i", listFile, + "-i", src, + "-map", "0:v:0", "-map", "1:a?", + "-c", "copy", + "-map_metadata", "1", + "-movflags", "+faststart", + "-f", "mp4", out, + ]; +} + +export function concatList(files: string[]): string { + return files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n"; +} + +// --- verification ----------------------------------------------------------- + +// Every frame of the video decoded, with ffmpeg told to stop at the first +// error (`-xerror`) and to print any. An empty stderr and a zero exit is a +// clean decode. +export async function fullDecode(paths: GatedPaths, file: string, signal?: AbortSignal): Promise<{ ok: boolean; why?: string }> { + try { + const err = await runHeavyFfmpeg( + paths, + ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", file, "-map", "0:v:0", "-map", "0:a?", "-f", "null", "-"], + { estimateMB: DECODE_ESTIMATE_MB, ...(signal ? { signal } : {}) }, + ); + const lines = err.split("\n").map((l) => l.trim()).filter(Boolean); + return lines.length ? { ok: false, why: lines.slice(-2).join(" | ") } : { ok: true }; + } catch (e) { + if (signal?.aborted) throw e; + return { ok: false, why: (e as Error).message }; + } +} + +export type AudioHash = { + // sha256 over every audio packet's (stream, size, md5) in order. + data: string; + // sha256 over every audio packet's (stream, pts, duration) relative to the + // first packet's pts, and that first pts. + timing: string; + firstPts: number | null; + packets: number; +}; + +// The audio packets of every audio stream, demuxed and copied (`-c copy`) into +// framemd5: what a copied track must reproduce exactly. +export async function audioPacketsHash(ffmpegBin: string, file: string, signal?: AbortSignal): Promise<AudioHash> { + const data = createHash("sha256"); + const timing = createHash("sha256"); + let first: number | null = null; + let packets = 0; + await new Promise<void>((resolve, reject) => { + const child = spawn( + ffmpegBin, + ["-nostdin", "-hide_banner", "-v", "error", "-i", file, "-map", "0:a?", "-c", "copy", "-f", "framemd5", "-"], + { stdio: ["ignore", "pipe", "pipe"] }, + ); + let carry = ""; + let err = ""; + const onAbort = () => child.kill("SIGKILL"); + signal?.addEventListener("abort", onAbort, { once: true }); + const take = (line: string) => { + if (!line || line.startsWith("#")) return; + const f = line.split(",").map((x) => x.trim()); + if (f.length < 6) return; + const [streamIdx, , pts, duration, size, md5] = f; + const p = Number(pts); + if (first === null) first = p; + packets += 1; + data.update(`${streamIdx},${size},${md5}\n`); + timing.update(`${streamIdx},${p - (first ?? 0)},${duration}\n`); + }; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (d: string) => { + const lines = (carry + d).split("\n"); + carry = lines.pop() ?? ""; + for (const l of lines) take(l.trim()); + }); + child.stderr.on("data", (d: Buffer) => (err = (err + d.toString()).slice(-2000))); + child.on("error", reject); + child.on("close", (code) => { + signal?.removeEventListener("abort", onAbort); + if (carry.trim()) take(carry.trim()); + if (signal?.aborted) reject(new Error("cancelled")); + else if (code !== 0) reject(new Error(`ffmpeg could not read the audio of ${path.basename(file)}: ${err.trim()}`)); + else resolve(); + }); + }); + return { data: data.digest("hex"), timing: timing.digest("hex"), firstPts: first, packets }; +} + +export type QualitySample = { at: number; score: number }; + +// One quality score of a 2-second excerpt of the re-encode against the same +// seconds of the source (both input-seeked to `at`; the source taken to the +// re-encode's frame rate first). VMAF where this ffmpeg has libvmaf, else SSIM. +export async function scoreExcerpt( + paths: GatedPaths, + opts: { + compacted: string; + source: string; + at: number; + seconds: number; + fps: number | null; + metric: "vmaf" | "ssim"; + scratchDir: string; + signal?: AbortSignal; + }, +): Promise<number> { + const ref = `[1:v]${opts.fps ? `fps=${opts.fps},` : ""}setpts=PTS-STARTPTS[r]`; + const dist = "[0:v]setpts=PTS-STARTPTS[d]"; + const log = path.join(opts.scratchDir, `vmaf-${Math.round(opts.at * 1000)}.json`); + const metric = + opts.metric === "vmaf" + ? `[d][r]libvmaf=log_fmt=json:log_path=${log.replace(/[:\\']/g, "\\$&")}:n_threads=4` + : "[d][r]ssim"; + const args = [ + "-nostdin", "-hide_banner", "-loglevel", "info", + "-ss", opts.at.toFixed(4), "-t", opts.seconds.toFixed(3), "-i", opts.compacted, + "-ss", opts.at.toFixed(4), "-t", opts.seconds.toFixed(3), "-i", opts.source, + "-lavfi", `${dist};${ref};${metric}`, + "-f", "null", "-", + ]; + const err = await runHeavyFfmpeg(paths, args, { + estimateMB: SCORE_ESTIMATE_MB, + ...(opts.signal ? { signal: opts.signal } : {}), + }); + if (opts.metric === "ssim") { + const m = /SSIM .*All:([0-9.]+)/.exec(err); + if (!m) throw new Error(`no SSIM in ffmpeg's output at ${opts.at.toFixed(1)} s`); + return Number(m[1]); + } + try { + const doc = JSON.parse(await readFile(log, "utf8")) as { pooled_metrics?: { vmaf?: { mean?: number } } }; + const mean = doc.pooled_metrics?.vmaf?.mean; + if (typeof mean !== "number") throw new Error("no pooled VMAF"); + return mean; + } catch (e) { + const m = /VMAF score: ([0-9.]+)/.exec(err); + if (m) return Number(m[1]); + throw new Error(`no VMAF for the excerpt at ${opts.at.toFixed(1)} s: ${(e as Error).message}`); + } finally { + await rm(log, { force: true }).catch(() => {}); + } +} + +// The excerpts' seconds: `n` spread through the file, away from its ends, each +// ON THE RE-ENCODE'S FRAME GRID less a quarter frame. A seek lands on the +// first frame at or after it, so both files start on the same picture; off the +// grid, a 30 fps copy's first frame is a 60 fps source's NEXT one, and a +// one-frame offset on moving content scores as a bad encode. +export function sampleTimes(seconds: number, n: number, excerpt: number, fps: number): number[] { + const usable = Math.max(0, seconds - excerpt - 0.5); + if (usable <= 0) return [0]; + const out: number[] = []; + for (let i = 0; i < n; i += 1) { + const t = Math.round((((i + 0.5) / n) * usable) * fps) / fps; + out.push(Number(Math.max(0, t - 0.25 / fps).toFixed(4))); + } + return [...new Set(out)]; +} + +// A REAL WINDOW CUT FROM EACH COPY through the evidence cutter +// (evidenceCutArgs: the input seek and the x264 re-encode every saved-video +// window goes through), and the two cuts compared on a downscaled picture +// (SSIM, 320 px wide, at the re-encode's frame rate): it succeeds from the +// re-encode and lands on the same frames as from the original. +export async function compareCuts( + paths: GatedPaths, + opts: { + compacted: string; + source: string; + at: number; + seconds: number; + fps: number | null; + scratchDir: string; + signal?: AbortSignal; + }, +): Promise<number> { + const a = path.join(opts.scratchDir, `cut-src-${Math.round(opts.at * 1000)}.mp4`); + const b = path.join(opts.scratchDir, `cut-out-${Math.round(opts.at * 1000)}.mp4`); + try { + for (const [file, out] of [ + [opts.source, a], + [opts.compacted, b], + ] as const) { + const r = await execa(paths.ffmpegBin, evidenceCutArgs(file, opts.at, opts.at + opts.seconds, "video", out), { + reject: false, + ...(opts.signal ? { cancelSignal: opts.signal } : {}), + }); + if (r.exitCode !== 0) { + throw new Error( + `the evidence cutter failed on ${path.basename(file)} at ${opts.at.toFixed(1)} s: ` + + String(r.stderr ?? "").trim().split("\n").slice(-2).join(" | "), + ); + } + } + const fps = opts.fps ? `fps=${opts.fps},` : ""; + const r = await execa( + paths.ffmpegBin, + [ + "-nostdin", "-hide_banner", "-loglevel", "info", + "-i", b, "-i", a, + "-lavfi", `[0:v]${fps}scale=320:-2,setpts=PTS-STARTPTS[d];[1:v]${fps}scale=320:-2,setpts=PTS-STARTPTS[r];[d][r]ssim`, + "-f", "null", "-", + ], + { reject: false, ...(opts.signal ? { cancelSignal: opts.signal } : {}) }, + ); + const m = /SSIM .*All:([0-9.]+)/.exec(String(r.stderr ?? "")); + if (r.exitCode !== 0 || !m) throw new Error(`could not compare the two cuts at ${opts.at.toFixed(1)} s`); + return Number(m[1]); + } finally { + await rm(a, { force: true }).catch(() => {}); + await rm(b, { force: true }).catch(() => {}); + } +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -33,6 +33,7 @@ import { REPORT_SCHEDULE_SETTINGS_FIELD_DOCS, DIGEST_SETTINGS_FIELD_DOCS, SAVED_VIDEO_BACKUP_SETTINGS_FIELD_DOCS, + SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS, SEEDER_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, ORPHEUS_TTS_SETTINGS_FIELD_DOCS, @@ -229,6 +230,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.savedVideoBackup), }, ], + savedVideoCompaction: [ + { + path: "savedVideoCompaction", + docs: SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.savedVideoCompaction), + }, + ], storage: [ { path: "storage", diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -35,6 +35,7 @@ import type { TtsSettings } from "./ttsSettings"; import type { ArchivesSettings } from "./archives/settings"; import type { RemoteArchive } from "./remoteArchives"; import type { ClipsSettings } from "./clipSettings"; +import type { SavedVideoCompactionSettings } from "./savedVideoCompaction"; import type { JobsSettings } from "./jobsSettings"; import type { ServiceCookiesSettings } from "./serviceCookieSettings"; import type { LookoutsSettings } from "./lookoutSettings"; @@ -108,6 +109,8 @@ type PreSchemaSiteSettings = { socialLinks: SocialLink[]; homepageUrl: string; savedVideoBackup: SavedVideoBackupSettings; + // Compacting saved videos (lane compact-store, 13 Nov 2026). + savedVideoCompaction: SavedVideoCompactionSettings; storage: StorageSettings; buildPipeline: BuildPipelineSettings; digest: DigestSettings; @@ -147,7 +150,7 @@ type PreSchemaSiteSettings = { type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 48 fields, in file order", () => { +test("SiteSettings keeps its 49 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -179,6 +182,7 @@ test("SiteSettings keeps its 48 fields, in file order", () => { "socialLinks", "homepageUrl", "savedVideoBackup", + "savedVideoCompaction", "storage", "buildPipeline", "digest", diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -84,6 +84,7 @@ import { sanitizeVoice, type VoiceSettings } from "./voiceSettings"; import { sanitizeArchives, type ArchivesSettings } from "./archives/settings"; import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives"; import { sanitizeClips, type ClipsSettings } from "./clipSettings"; +import { sanitizeSavedVideoCompaction, type SavedVideoCompactionSettings } from "./savedVideoCompaction"; import { sanitizeJobs, type JobsSettings } from "./jobsSettings"; import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings"; import { sanitizePrivacy, type PrivacySettings } from "./privacySettings"; @@ -115,6 +116,7 @@ export { export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings"; export { REMOTE_ARCHIVE_FIELD_DOCS, type RemoteArchive } from "./remoteArchives"; export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings"; +export { SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS, type SavedVideoCompactionSettings } from "./savedVideoCompaction"; export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings"; export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings"; export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings"; @@ -2027,6 +2029,9 @@ export const siteSettingsSchema = z.object({ savedVideoBackup: settingsField((v): SavedVideoBackupSettings => sanitizeSavedVideoBackup(v)).describe( "Backup configuration for the saved-video store (Phase 4 of the video-persistence feature). When enabled with a destination, the store is mirrored there (additively, no deletes) with a per-backup manifest, and the sync scheduler runs the backup on the configured cadence. See common/controller/backupSavedVideos.ts.", ), + savedVideoCompaction: settingsField((v): SavedVideoCompactionSettings => sanitizeSavedVideoCompaction(v)).describe( + "Compacting a saved video (`pnpm ops compact-saved-videos`, controller/compactSavedVideos.ts): a deliberately stored container re-encoded to AV1 (SVT-AV1, a keyframe every 5 s, the source's height, the audio copied), verified, and made the active copy, the original kept beside it as `keptAs: \"original\"` until it is dropped. Runs only when asked — there is no lane. These keys are the selector, the encode, the checks' thresholds and when the original goes. See SavedVideoCompactionSettings and OPERATING.md, \"Compact saved videos\".", + ), storage: settingsField((v): StorageSettings => sanitizeStorage(v)).describe( "Where a channel's downloaded media goes when it is relocated off the corpus disk. A DEFAULT ONLY: the relocate controller never reads it and always takes an explicit root, so this is the value the per-channel Storage panel prefills and the /channels bulk move falls back to. Blank = no default. See StorageSettings.", ), diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,20 @@ # Changelog ## [Unreleased] +- **A saved video can be compacted: re-encoded to AV1, verified, and said to be a re-encode everywhere.** + `pnpm ops compact-saved-videos` (`{"items": [...]}` or `{"select": true}`, `dryRun` first) re-encodes a deliberately + stored container with SVT-AV1 (settings `savedVideoCompaction`: crf 36, preset 8, a keyframe every 5 s, Kick and + Twitch above 30 fps to 30, the audio copied). It runs in resumable chunks, each through the heavy slot, as one job per + channel on the `compact` queue. The re-encode becomes the active copy only when every check passes: a full decode, + the length, the frame count, identical audio packets, VMAF on excerpts, windows cut through the evidence cutter, and + the recording clock re-measured. The original stays beside it as `"keptAs": "original"`. + - Under `dropOriginal: "after-verify"` (the default) the original is dropped in a later step, after the copy is read + back from disk. A video not known to be on its platform waits for a person's review instead + (`get compaction-review`, /saved-videos, the video page's **Review the compacted copy**). + - `drop-saved-alternate` drops an original only with `"confirmOriginal": true` and a fresh re-check of the + compacted copy. Nothing else deletes one: the prune keeps the video, unpersist brings the original back, and a + persist landing on its name moves it aside. + - A channel opts out with `excludeFromCompaction`. There is no lane: it runs only when asked. - **Clip windows can be asked for taller than 720, and the 720 window stays.** A `maxHeight` above 720 on fetch-windows, fetch-window or `fetch_clip` asks for a taller window, up to the new setting `clips.windowMaxHeight` (default 1080; a taller ask is held to it and the answer says so). With no `maxHeight` a diff --git a/editor/app/api/ops/compact-saved-videos/route.test.ts b/editor/app/api/ops/compact-saved-videos/route.test.ts @@ -0,0 +1,68 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/compact-saved-videos/route.test.ts" +// +// The body's shape and the refusals that come before any job, then a dry run +// that answers with the plan and writes nothing. Nothing is encoded. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "compact-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +const { POST } = await import("./route"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const videoDir = path.join(ROOT, "channels", "kick", "data", "aaaaaaaaaaa"); +await mkdir(videoDir, { recursive: true }); +await writeFile(path.join(ROOT, "channels", "kick", "config.json"), JSON.stringify({ handling: "transcribe", platform: "kick" })); +await writeFile( + path.join(videoDir, "saved-video.json"), + JSON.stringify({ storedAt: "x", dir: path.join(ROOT, "saved-videos", "kick", "aaaaaaaaaaa"), file: "source-media.mp4", bytes: 5, keepReason: "keep-latest" }), +); + +async function post(body: Record<string, unknown>) { + const res = await POST( + new Request("http://localhost/api/ops/compact-saved-videos", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as { ok?: boolean; error?: string; dryRun?: boolean; plan?: { items: { compact: boolean; reason?: string }[]; lines: string[] } } }; +} + +test("refusals before any job", async () => { + const cases: [Record<string, unknown>, RegExp][] = [ + [{}, /"items" is required/], + [{ items: [{ slug: "kick", id: "aaaaaaaaaaa" }], force: 1 }, /unknown key\(s\): force/], + [{ items: [{ slug: "kick", id: "../x" }] }, /not a video id|one path segment/], + [{ items: [{ slug: "kick", id: "aaaaaaaaaaa" }], crf: 5 }, /"crf" must be a number from 20 to 55/], + [{ items: [{ slug: "kick", id: "aaaaaaaaaaa" }], chunkMinutes: 0 }, /"chunkMinutes" must be a number from 1 to 60/], + [{ select: true, slugs: ["../x"] }, /not a valid channel slug/], + ]; + for (const [body, re] of cases) { + const r = await post(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(r.json.error!, re, JSON.stringify(body)); + } +}); + +test("a dry run answers the plan — a keep-latest container is skipped — and writes nothing", async () => { + const before = await readdir(ROOT, { recursive: true }); + const r = await post({ items: [{ slug: "kick", id: "aaaaaaaaaaa" }], dryRun: true }); + assert.equal(r.status, 200, JSON.stringify(r.json)); + assert.equal(r.json.dryRun, true); + assert.equal(r.json.plan!.items[0].compact, false); + assert.match(r.json.plan!.items[0].reason!, /keep-latest/); + assert.match(r.json.plan!.lines.at(-1)!, /^total: 0 container/); + assert.deepEqual((await readdir(ROOT, { recursive: true })).sort(), before.sort()); + // The selector over the whole store, the same. + const s = await post({ select: true, dryRun: true }); + assert.equal(s.status, 200, JSON.stringify(s.json)); + assert.equal(s.json.plan!.items.length, 1); +}); diff --git a/editor/app/api/ops/compact-saved-videos/route.ts b/editor/app/api/ops/compact-saved-videos/route.ts @@ -0,0 +1,63 @@ +import { NextResponse } from "next/server"; +import { compactSavedVideosAction } from "../../../saved-videos/compactActions"; +import { OpsInputError, ops, opsFail, optBool, reqSlugs, reqVideoItems, type OpsBody } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { items: [{ slug, id }, …] } | { select: true, slugs? }, +// dryRun?, retryFailed?, crf?, preset?, maxFps?, chunkMinutes? +// dryRun -> { ok: true, dryRun: true, plan: { items, willCompact, totals, lines } } +// else -> { ok: true, dryRun: false, plan, jobs: [{ slug, jobId }], jobIds, +// jobId (one job only), skipped: [{ slug, reason }] } +// +// Compact saved videos (controller/compactSavedVideos.ts): each one re-encoded +// to AV1 (settings.savedVideoCompaction: crf, preset, the frame-rate cap), +// verified, made the active copy, the original kept beside it as +// `keptAs: "original"` — dropped later in a step of its own when +// `dropOriginal` is "after-verify" and the video is still on its platform; +// otherwise it waits for a person (`get compaction-review`). `items` names the +// videos (deliberately stored only); `select` asks the selector (platform, +// height, video bitrate; `slugs` narrows it to those channels). The plan's +// `lines` say, per video, its size, bitrate, height, fps, the estimate (size, +// hours), the disk it needs against what is free, or why it is skipped. One +// job per channel on the `compact` queue; a re-run resumes. +function optNumber(body: OpsBody, key: string, lo: number, hi: number): number | undefined { + const v = body[key]; + if (v === undefined) return undefined; + if (typeof v !== "number" || !Number.isFinite(v) || v < lo || v > hi) { + throw new OpsInputError(`"${key}" must be a number from ${lo} to ${hi}`); + } + return v; +} + +export async function POST(request: Request) { + return ops( + request, + ["items", "select", "slugs", "dryRun", "retryFailed", "crf", "preset", "maxFps", "chunkMinutes"], + async (body) => { + const select = optBool(body, "select") === true; + const crf = optNumber(body, "crf", 20, 55); + const preset = optNumber(body, "preset", 4, 12); + const maxFps = optNumber(body, "maxFps", 0, 240); + const chunkMinutes = optNumber(body, "chunkMinutes", 1, 60); + const result = await compactSavedVideosAction({ + ...(select ? { select: true } : { items: reqVideoItems(body, "items") }), + ...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}), + dryRun: optBool(body, "dryRun") ?? false, + retryFailed: optBool(body, "retryFailed") ?? false, + overrides: { + ...(crf !== undefined ? { crf } : {}), + ...(preset !== undefined ? { preset } : {}), + ...(maxFps !== undefined ? { maxFps } : {}), + ...(chunkMinutes !== undefined ? { chunkMinutes } : {}), + }, + }); + if (!result.ok) return opsFail(result.error); + if (result.dryRun) return NextResponse.json(result); + return NextResponse.json({ + ...result, + ...(result.jobIds.length === 1 ? { jobId: result.jobIds[0] } : {}), + }); + }, + ); +} diff --git a/editor/app/api/ops/compaction-review/route.ts b/editor/app/api/ops/compaction-review/route.ts @@ -0,0 +1,33 @@ +import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import { COMPACTION_REVIEW_STATE_LABELS } from "yt-dlp-transcript-common/lib/savedVideoCompaction"; +import { compactionReviewList } from "../../../saved-videos/compactActions"; +import { readRoute } from "../_read"; +import { opsFail } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// GET [?slug=<channel>] +// -> { ok, count, awaiting, videos: [{ slug, id, state, label, line, +// availability, onPlatform, original?, compactedAt, bytes, sourceBytes, +// checksPassed, recheck? }], notAnswering: [slug] } +// +// Every compacted saved video (controller/compactSavedVideos.ts) and what its +// original waits for: "awaiting-review" (not known to be on its platform: a +// person reviews the compacted copy first — review-compacted-original), +// "reviewed" (drop-saved-alternate with "confirmOriginal": true may drop it), +// "kept" (dropOriginal "keep"), "drop-pending" (on its platform, the +// after-verify drop has not run) or "dropped". `awaiting` counts the first. +// Pointers and availability records only — no container is opened. +export async function GET(request: Request) { + return readRoute(request, ["slug"], async (q) => { + const slug = q.get("slug")?.trim() || undefined; + if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); + const { rows, notAnswering } = await compactionReviewList(slug ? { slug } : {}); + return { + count: rows.length, + awaiting: rows.filter((r) => r.state === "awaiting-review").length, + videos: rows.map((r) => ({ ...r, label: COMPACTION_REVIEW_STATE_LABELS[r.state] })), + notAnswering, + }; + }); +} diff --git a/editor/app/api/ops/drop-saved-alternate/route.ts b/editor/app/api/ops/drop-saved-alternate/route.ts @@ -4,7 +4,7 @@ import { ops, opsFail, optBool, reqSlug, reqString, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, file, dryRun? } +// POST { slug, id, file, dryRun?, confirmOriginal? } // -> { ok, dryRun, file, path, existed, bytes, remaining, alternate } // // Drop ONE saved alternate of one video — a copy kept beside a newer download @@ -17,13 +17,19 @@ export const dynamic = "force-dynamic"; // is left as it was. A file already gone but still listed is cleaned from the // pointer (`existed: false`). "dryRun": true answers the same and changes // nothing. No undo. +// +// AN ORIGINAL (`keptAs: "original"`, the source a compacted copy was made +// from) is refused unless "confirmOriginal": true; before the drop the +// compacted copy is read back from disk and must match its recorded sha256; +// and a video not known to be on its platform needs its review recorded first +// (review-compacted-original). `get compaction-review` lists each one's state. export async function POST(request: Request) { - return ops(request, ["slug", "id", "file", "dryRun"], async (body) => { + return ops(request, ["slug", "id", "file", "dryRun", "confirmOriginal"], async (body) => { const res = await dropSavedAlternateAction( reqSlug(body, "slug"), reqVideoId(body, "id"), reqString(body, "file"), - { dryRun: optBool(body, "dryRun") ?? false }, + { dryRun: optBool(body, "dryRun") ?? false, confirmOriginal: optBool(body, "confirmOriginal") ?? false }, ); if (!res.ok) return opsFail(res.error); const r = res.result; diff --git a/editor/app/api/ops/review-compacted-original/route.ts b/editor/app/api/ops/review-compacted-original/route.ts @@ -0,0 +1,25 @@ +import { NextResponse } from "next/server"; +import { reviewCompactedOriginalAction } from "../../../saved-videos/compactActions"; +import { ops, opsFail, optString, reqSlug, reqVideoId } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, id, note? } +// -> { ok, original } +// +// A person's review of a compacted copy: "the compacted copy is proven good". +// Recorded on the original's alternate entry (`review: {at, by: "ops", note}`) +// and nothing else changes — no file is touched. It is what a video not known +// to be on its platform needs before drop-saved-alternate, with +// "confirmOriginal": true, drops its original. Refused when the video keeps no +// original beside a compacted copy, or the copy's checks did not pass. +export async function POST(request: Request) { + return ops(request, ["slug", "id", "note"], async (body) => { + const res = await reviewCompactedOriginalAction(reqSlug(body, "slug"), reqVideoId(body, "id"), { + by: "ops", + ...(optString(body, "note") ? { note: optString(body, "note") } : {}), + }); + if (!res.ok) return opsFail(res.error); + return NextResponse.json({ ok: true, original: res.original }); + }); +} diff --git a/editor/app/api/ops/saved-alternates/route.ts b/editor/app/api/ops/saved-alternates/route.ts @@ -1,5 +1,5 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { savedAlternatesLine } from "yt-dlp-transcript-common/lib/savedVideo"; +import { compactedLine, savedAlternatesLine } from "yt-dlp-transcript-common/lib/savedVideo"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; import { listSavedAlternates } from "yt-dlp-transcript-common/controller/savedVideoInventory"; import { readRoute } from "../_read"; @@ -41,6 +41,8 @@ export async function GET(request: Request) { ...(e.pointer.keepReason ? { keepReason: e.pointer.keepReason } : {}), ...(e.pointer.origin ? { origin: e.pointer.origin } : {}), storedAt: e.pointer.storedAt, + // A re-encode says so (compact-saved-videos): of what, how. + ...(e.pointer.compacted ? { reencode: compactedLine(e.pointer) } : {}), }, alternates: e.pointer.alternates ?? [], })), diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx @@ -5,6 +5,7 @@ import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActio import type { ChannelHandling } from "yt-dlp-transcript-common/lib/channelConfig"; import { SAVED_ALTERNATE_KEPT_AS_LABELS, + compactedLine, type SavedVideoAlternate, type SavedVideoPointer, } from "yt-dlp-transcript-common/lib/savedVideo"; @@ -22,6 +23,7 @@ import { redownloadToArchiveAction, unpersistVideoAction, } from "../../videoActions"; +import { reviewCompactedOriginalAction } from "../../../../../../saved-videos/compactActions"; export function SourceVideoSection({ slug, @@ -156,6 +158,13 @@ function PersistedSourceVideo({ without losing the original. Transcription falls back to it when no audio is on disk. </p> + {/* A RE-ENCODE SAYS SO (compact-saved-videos): of what, how, and where + the original is. */} + {savedVideo.compacted && ( + <p className="text-sm" aria-label="compacted copy"> + {compactedLine(savedVideo)} + </p> + )} <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm"> <dt className="text-muted-foreground">File</dt> <dd className="font-mono break-all">{savedVideo.file}</dd> @@ -204,6 +213,20 @@ function PersistedSourceVideo({ </dd> </> )} + {savedVideo.compacted && ( + <> + <dt className="text-muted-foreground">Checks</dt> + <dd> + {savedVideo.compacted.checks.passed ? "passed" : "NOT passed"}:{" "} + {savedVideo.compacted.checks.frames[1]}/{savedVideo.compacted.checks.frames[2]} frames, + audio identical, {savedVideo.compacted.checks.quality.metric.toUpperCase()}{" "} + {savedVideo.compacted.checks.quality.mean} (worst {savedVideo.compacted.checks.quality.min}) + {savedVideo.compacted.recheck + ? `; re-checked from disk ${savedVideo.compacted.recheck.ok ? "ok" : `FAILED (${savedVideo.compacted.recheck.why ?? "?"})`}` + : ""} + </dd> + </> + )} {savedVideo.sha256 && ( <> <dt className="text-muted-foreground">sha256</dt> @@ -233,6 +256,7 @@ function PersistedSourceVideo({ slug={slug} videoId={videoId} alternate={a} + compacted={!!savedVideo.compacted} /> ))} </ul> @@ -276,14 +300,18 @@ function SavedAlternateRow({ slug, videoId, alternate, + compacted, }: { slug: string; videoId: string; alternate: SavedVideoAlternate; + compacted: boolean; }) { const [pending, startTransition] = useTransition(); const [armed, setArmed] = useState(false); + const [reviewArmed, setReviewArmed] = useState(false); const [error, setError] = useState<string | null>(null); + const original = alternate.keptAs === "original"; const facts = [ alternate.height ? `${alternate.height}p` : "height unknown", alternate.seconds !== undefined @@ -293,6 +321,11 @@ function SavedAlternateRow({ formatBytes(alternate.bytes), alternate.origin?.requestedBy ?? "download", alternate.keptAs ? SAVED_ALTERNATE_KEPT_AS_LABELS[alternate.keptAs] : undefined, + alternate.compactedFrom ? "a re-encode" : undefined, + original && alternate.sha256 ? `sha256 ${alternate.sha256.slice(0, 12)}…` : undefined, + original && alternate.review + ? `reviewed ${alternate.review.at.slice(0, 10)} by ${alternate.review.by}${alternate.review.note ? ` — “${alternate.review.note}”` : ""}` + : undefined, ] .filter(Boolean) .join(", "); @@ -309,9 +342,11 @@ function SavedAlternateRow({ {armed ? ( <> <span> - {alternate.keptAs === "proxy" - ? "This is the lower-quality copy kept on purpose as a proxy. Delete it from the store? No undo." - : "Delete this copy from the store? No undo."} + {original + ? "This is the ORIGINAL the active copy was re-encoded from. The compacted copy is read back from disk first; a video not known to be on its platform needs its review recorded. Delete the original? No undo." + : alternate.keptAs === "proxy" + ? "This is the lower-quality copy kept on purpose as a proxy. Delete it from the store? No undo." + : "Delete this copy from the store? No undo."} </span> <button type="button" @@ -324,6 +359,7 @@ function SavedAlternateRow({ slug, videoId, alternate.file, + original ? { confirmOriginal: true } : {}, ); if (!res.ok) setError(res.error); setArmed(false); @@ -331,7 +367,7 @@ function SavedAlternateRow({ }} className="px-3 py-1 rounded-md border border-destructive text-destructive text-sm font-medium hover:bg-muted disabled:opacity-50" > - {pending ? "Dropping…" : "Drop it"} + {pending ? "Dropping…" : original ? "Drop the original" : "Drop it"} </button> <button type="button" @@ -343,17 +379,64 @@ function SavedAlternateRow({ </button> </> ) : ( - <button - type="button" - aria-label={`drop saved alternate ${alternate.file}`} - onClick={() => { - setError(null); - setArmed(true); - }} - className="px-3 py-1 rounded-md border border-border text-sm hover:bg-muted" - > - Drop this alternate - </button> + <> + <button + type="button" + aria-label={`drop saved alternate ${alternate.file}`} + onClick={() => { + setError(null); + setArmed(true); + }} + className="px-3 py-1 rounded-md border border-border text-sm hover:bg-muted" + > + {original ? "Drop the original" : "Drop this alternate"} + </button> + {/* THE REVIEW a video gone from its platform needs before its + original may go: a person's word that the re-encode is good. */} + {original && compacted && !alternate.review && ( + reviewArmed ? ( + <> + <span>Record that the compacted copy is proven good? Nothing is deleted.</span> + <button + type="button" + disabled={pending} + aria-label={`confirm review of ${alternate.file}`} + onClick={() => { + setError(null); + startTransition(async () => { + const res = await reviewCompactedOriginalAction(slug, videoId); + if (!res.ok) setError(res.error); + setReviewArmed(false); + }); + }} + className="px-3 py-1 rounded-md border border-border text-sm font-medium hover:bg-muted disabled:opacity-50" + > + {pending ? "Recording…" : "It is good"} + </button> + <button + type="button" + disabled={pending} + onClick={() => setReviewArmed(false)} + className="px-3 py-1 rounded-md border border-border text-sm hover:bg-muted disabled:opacity-50" + > + Cancel + </button> + </> + ) : ( + <button + type="button" + aria-label={`review compacted copy ${videoId}`} + onClick={() => { + setError(null); + setReviewArmed(true); + }} + className="px-3 py-1 rounded-md border border-border text-sm hover:bg-muted" + > + Review the compacted copy + </button> + ) + )} + </> )} {error && ( <span className="text-destructive" aria-label="drop alternate error"> diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -76,6 +76,7 @@ import { import { findVideoSourceUrl } from "yt-dlp-transcript-common/controller/undownloadedVideos"; import { fullAudioFirst } from "yt-dlp-transcript-common/controller/fullAudioFirst"; import { fullAudioGate } from "yt-dlp-transcript-common/lib/fullAudioFirst-server"; +import { recheckCompactedCopy } from "yt-dlp-transcript-common/controller/compactSavedVideos"; import { dropSavedAlternate, loadSavedVideo, @@ -1439,7 +1440,14 @@ export async function unpersistVideoAction( videoId: string, ): Promise<{ ok: true } | { ok: false; error: string }> { const videoDir = videoDirOf(slug, videoId); - const reversed = await unpersistSavedVideo(videoDir); + let reversed: boolean; + try { + reversed = await unpersistSavedVideo(videoDir); + } catch (e) { + // A compacted copy whose original was dropped is refused (lib/savedVideo-server.ts). + if (e instanceof SavedAlternateRefusal) return { ok: false, error: e.message }; + throw e; + } if (!reversed) { return { ok: false, error: "This video has no persisted source to restore." }; } @@ -1455,11 +1463,17 @@ export async function unpersistVideoAction( // this; it is dropSavedAlternate, which refuses the active copy, a name the // pointer does not list and any path, and holds while the store is being moved. // `dryRun` answers the same and changes nothing. No undo. +// +// AN ORIGINAL (`keptAs: "original"`, the source a compacted copy was +// re-encoded from) needs `confirmOriginal`; before a real drop the compacted +// copy is read back from disk (recheckCompactedCopy: size, sha256, container, +// length) and the drop is refused unless that held. A video not known to be +// on its platform also needs its review recorded (reviewCompactedOriginalAction). export async function dropSavedAlternateAction( slug: string, videoId: string, file: string, - opts: { dryRun?: boolean } = {}, + opts: { dryRun?: boolean; confirmOriginal?: boolean } = {}, ): Promise<{ ok: true; result: DropSavedAlternateResult } | { ok: false; error: string }> { const paths = getPaths(); const config = await readChannelConfig(paths, slug); @@ -1467,11 +1481,26 @@ export async function dropSavedAlternateAction( if (channelTextStall(config)) { return { ok: false, error: `${file} not dropped: this channel's drive is not answering.` }; } + const videoDir = videoDirOf(slug, videoId); + let verifiedActive: { sha256: string } | undefined; + if (opts.confirmOriginal && !opts.dryRun) { + const pointer = await loadSavedVideo(videoDir); + const target = pointer?.alternates?.find((a) => a.file === file); + if (pointer?.compacted && target?.keptAs === "original" && pointer.file === pointer.compacted.result.file) { + const recheck = await recheckCompactedCopy({ paths, videoDir }); + if (!recheck.ok) { + return { ok: false, error: `${file} not dropped: the compacted copy did not re-check (${recheck.why}).` }; + } + verifiedActive = { sha256: recheck.sha256 }; + } + } let result: DropSavedAlternateResult; try { - result = await dropSavedAlternate(videoDirOf(slug, videoId), file, { + result = await dropSavedAlternate(videoDir, file, { dryRun: opts.dryRun, paths, + ...(opts.confirmOriginal ? { confirmOriginal: true } : {}), + ...(verifiedActive ? { verifiedActive } : {}), }); } catch (e) { if ( diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -18,6 +18,7 @@ import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCom import type { AudioFormat } from "yt-dlp-transcript-common/lib/channelConfig"; import { isSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { isPersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; +import { compactChannelVideosAction } from "../saved-videos/compactActions"; import { downloadAction, downloadMissingAction, @@ -619,4 +620,19 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { minFreeMemMb: num(p.minFreeMemMb), }); }, + // The same list, mode and overrides: a replay (or the boot pass) resumes at + // the first chunk not encoded and skips what is already compacted. + "compact-saved-videos": (spec) => { + const { p } = params(spec); + return compactChannelVideosAction(spec.slug, strings(p.ids) ?? [], { + mode: p.mode === "select" ? "select" : "explicit", + overrides: { + ...(num(p.crf) !== undefined ? { crf: num(p.crf) } : {}), + ...(num(p.preset) !== undefined ? { preset: num(p.preset) } : {}), + ...(num(p.maxFps) !== undefined ? { maxFps: num(p.maxFps) } : {}), + ...(num(p.chunkMinutes) !== undefined ? { chunkMinutes: num(p.chunkMinutes) } : {}), + }, + ...(p.retryFailed === true ? { retryFailed: true } : {}), + }); + }, }; diff --git a/editor/app/saved-videos/compactActions.ts b/editor/app/saved-videos/compactActions.ts @@ -0,0 +1,206 @@ +"use server"; + +import path from "node:path"; +import { safeRevalidate } from "../lib/safeRevalidate"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { + compactSavedVideos, + effectiveCompactionSettings, + listCompactionReview, + planCompaction, + type CompactItem, + type CompactPlan, + type CompactionReviewRow, +} from "yt-dlp-transcript-common/controller/compactSavedVideos"; +import { + SavedAlternateRefusal, + recordOriginalReview, +} from "yt-dlp-transcript-common/lib/savedVideo-server"; +import type { SavedVideoAlternate } from "yt-dlp-transcript-common/lib/savedVideo"; +import type { SavedVideoCompactionSettings } from "yt-dlp-transcript-common/lib/savedVideoCompaction"; +import { + runManagedFunction, + type StreamActionResult, +} from "yt-dlp-transcript-common/jobs/streamCommand"; +import { channelTextStall } from "yt-dlp-transcript-common/lib/channelMedia"; + +// COMPACT SAVED VIDEOS: the `compact-saved-videos` job, as `pnpm ops +// compact-saved-videos` posts it (`/api/ops/compact-saved-videos`). The work +// and its rules are common/controller/compactSavedVideos.ts. +// +// ONE QUEUE MACHINE-WIDE: an encode is hours of CPU and a write of gigabytes +// on the archive drive; one video at a time across every channel. +const COMPACT_QUEUE = "compact"; + +export type CompactOverrides = Partial<Pick<SavedVideoCompactionSettings, "crf" | "preset" | "maxFps" | "chunkMinutes">>; + +export type CompactSavedVideosActionResult = + | { ok: false; error: string } + | { ok: true; dryRun: true; plan: CompactPlan } + | { + ok: true; + dryRun: false; + plan: CompactPlan; + jobs: { slug: string; jobId: string }[]; + jobIds: string[]; + skipped: { slug: string; reason: string }[]; + }; + +function settingsFor(overrides: CompactOverrides): SavedVideoCompactionSettings { + return effectiveCompactionSettings(getSettings().savedVideoCompaction, overrides); +} + +// One channel's list as one job on the compact queue. The job carries its ids, +// its mode and its overrides in its spec, so a replay — or the boot pass after +// a restart — re-runs the same list, resuming the chunks already encoded. +export async function compactChannelVideosAction( + slug: string, + ids: string[], + opts: { mode: "explicit" | "select"; overrides?: CompactOverrides; retryFailed?: boolean }, +): Promise<StreamActionResult> { + const wanted = [...new Set(ids)]; + if (wanted.length === 0) return { ok: false, error: "No video ids to compact." }; + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `Channel "${slug}" not found` }; + const overrides = opts.overrides ?? {}; + return runManagedFunction({ + kind: "compact-saved-videos", + queueKey: COMPACT_QUEUE, + paths, + channelSlug: slug, + spec: { + kind: "compact-saved-videos", + slug, + params: { ids: wanted, mode: opts.mode, ...overrides, ...(opts.retryFailed ? { retryFailed: true } : {}) }, + }, + fn: async (onLog, signal, _progress, ctx) => { + // The settings as they are when the job STARTS (it may have queued). + const result = await compactSavedVideos({ + paths, + settings: settingsFor(overrides), + items: wanted.map((id) => ({ slug, id })), + mode: opts.mode, + ...(opts.retryFailed ? { retryFailed: true } : {}), + onLog, + signal, + drainSignal: ctx.drainSignal, + }); + if (result.compacted.length) safeRevalidate([`/channels/${slug}`, "/saved-videos"]); + if (result.stopped && result.stopped !== "drained" && result.stopped !== "cancelled") { + throw new Error(`Stopped: ${result.stopped}. A re-run resumes.`); + } + if (result.failed.length > 0) { + throw new Error(`${result.failed.length} video(s) not compacted: ${result.failed.map((f) => `${f.id} — ${f.reason}`).join("; ")}`); + } + }, + }); +} + +// An explicit list, or (`select`) what the settings' selector picks across the +// store (or `slugs`). A dry run answers with the plan — every item's line, the +// estimate, the disk, why one is skipped — and writes nothing. A real run +// starts one job per channel with something to compact. +export async function compactSavedVideosAction(input: { + items?: CompactItem[]; + select?: boolean; + slugs?: string[]; + dryRun?: boolean; + retryFailed?: boolean; + overrides?: CompactOverrides; +}): Promise<CompactSavedVideosActionResult> { + if (!input.select && !input.items?.length) { + return { ok: false, error: 'Name the videos ("items": [{slug, id}]) or ask the selector ("select": true).' }; + } + if (input.select && input.items?.length) { + return { ok: false, error: '"items" and "select" are two ways to ask: pass one.' }; + } + const paths = getPaths(); + const settings = settingsFor(input.overrides ?? {}); + const plan = await planCompaction({ + paths, + settings, + ...(input.items ? { items: input.items } : {}), + ...(input.select ? { select: true } : {}), + ...(input.slugs?.length ? { slugs: input.slugs } : {}), + ...(input.retryFailed ? { retryFailed: true } : {}), + }); + if (input.dryRun) return { ok: true, dryRun: true, plan }; + const bySlug = new Map<string, string[]>(); + for (const i of plan.items) { + if (!i.compact) continue; + bySlug.set(i.slug, [...(bySlug.get(i.slug) ?? []), i.id]); + } + const jobs: { slug: string; jobId: string }[] = []; + const skipped: { slug: string; reason: string }[] = []; + for (const [slug, ids] of bySlug) { + let result: StreamActionResult; + try { + result = await compactChannelVideosAction(slug, ids, { + mode: input.select ? "select" : "explicit", + ...(input.overrides ? { overrides: input.overrides } : {}), + ...(input.retryFailed ? { retryFailed: true } : {}), + }); + } catch (e) { + skipped.push({ slug, reason: (e as Error).message }); + continue; + } + if (!result.ok) { + skipped.push({ slug, reason: result.error }); + continue; + } + // Nobody reads the stream: the job's log is on disk (see the ops layer). + void result.stream.cancel(); + jobs.push({ slug, jobId: result.jobId }); + } + if (bySlug.size > 0 && jobs.length === 0) { + return { ok: false, error: skipped.map((s) => `${s.slug}: ${s.reason}`).join("; ") }; + } + return { ok: true, dryRun: false, plan, jobs, jobIds: jobs.map((j) => j.jobId), skipped }; +} + +// The review list: every compacted video and what its original waits for. +export async function compactionReviewList(opts: { slug?: string } = {}): Promise<{ + rows: CompactionReviewRow[]; + notAnswering: string[]; +}> { + const notAnswering: string[] = []; + const rows = await listCompactionReview({ + paths: getPaths(), + dropOriginal: getSettings().savedVideoCompaction.dropOriginal, + ...(opts.slug ? { channelSlug: opts.slug } : {}), + notAnswering, + }); + return { rows, notAnswering: notAnswering.sort() }; +} + +// A PERSON'S REVIEW of a compacted copy (the video page's "The compacted copy +// is good", `pnpm ops review-compacted-original`): recorded on the original's +// entry. It deletes nothing — it is what lets drop-saved-alternate, with +// `confirmOriginal`, drop the original of a video gone from its platform. +export async function reviewCompactedOriginalAction( + slug: string, + videoId: string, + opts: { note?: string; by?: string } = {}, +): Promise<{ ok: true; original: SavedVideoAlternate } | { ok: false; error: string }> { + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (channelTextStall(config)) { + return { ok: false, error: "Not recorded: this channel's drive is not answering." }; + } + try { + const original = await recordOriginalReview(path.join(paths.channelsDir, slug, "data", videoId), { + at: new Date().toISOString(), + by: opts.by ?? "editor", + ...(opts.note?.trim() ? { note: opts.note.trim() } : {}), + }); + safeRevalidate([`/channels/${slug}/videos/${videoId}`, "/saved-videos"]); + return { ok: true, original }; + } catch (e) { + if (e instanceof SavedAlternateRefusal) return { ok: false, error: e.message }; + throw e; + } +} diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx @@ -10,6 +10,8 @@ import { savedVideoBytes, } from "yt-dlp-transcript-common/lib/savedVideo"; import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState"; +import { listCompactionReview } from "yt-dlp-transcript-common/controller/compactSavedVideos"; +import { COMPACTION_REVIEW_STATE_LABELS } from "yt-dlp-transcript-common/lib/savedVideoCompaction"; import { SavedVideosControls } from "./components/SavedVideosControls"; import { PersistVideoListControl } from "./components/PersistVideoListControl"; @@ -54,6 +56,17 @@ export default async function SavedVideosPage() { // Two copies of one video, both kept (ytdlp/savedAlternates.ts): flagged // for a check. Off the same pointer walk, so free. const withAlternates = entries.filter((e) => (e.pointer.alternates?.length ?? 0) > 0); + // Compacted copies (compact-saved-videos) and what each original waits for; + // the ones awaiting a person's review first. + const compacted = await listCompactionReview({ + paths, + dropOriginal: settings.savedVideoCompaction.dropOriginal, + notAnswering: [], + }); + const reviewOrder = ["awaiting-review", "reviewed", "drop-pending", "kept", "dropped"]; + compacted.sort( + (a, b) => reviewOrder.indexOf(a.state) - reviewOrder.indexOf(b.state) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id), + ); const channels = [...byChannel.values()].sort((a, b) => a.slug.localeCompare(b.slug), ); @@ -190,6 +203,36 @@ export default async function SavedVideosPage() { </section> )} + {compacted.length > 0 && ( + <section aria-label="compacted saved videos" className="flex flex-col gap-2"> + <h2 className="text-base font-semibold"> + Compacted copies ({compacted.length} + {compacted.some((c) => c.state === "awaiting-review") + ? `, ${compacted.filter((c) => c.state === "awaiting-review").length} awaiting review` + : ""} + ) + </h2> + <ul className="flex flex-col gap-1 text-sm"> + {compacted.map((c) => ( + <li key={`${c.slug}/${c.id}`} aria-label={`compacted ${c.slug}/${c.id}`}> + <Link + href={`/channels/${c.slug}/videos/${encodeURIComponent(c.id)}`} + className="underline hover:no-underline" + > + {c.slug}/{c.id} + </Link> + <span className={c.state === "awaiting-review" ? "font-medium" : "text-muted-foreground"}> + {" "} + — {COMPACTION_REVIEW_STATE_LABELS[c.state]} + {c.onPlatform ? "" : ` (availability ${c.availability ?? "unknown"})`}. + </span> + <span className="text-muted-foreground"> {c.line}</span> + </li> + ))} + </ul> + </section> + )} + <section aria-label="backups" className="flex flex-col gap-2"> <h2 className="text-base font-semibold">Backups</h2> <SavedVideosControls diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -293,6 +293,10 @@ const GETTERS = { // the store keeps both): each one's active copy and its flagged alternates. "saved-alternates": (slug) => slug ? `/api/ops/saved-alternates?slug=${encodeURIComponent(slug)}` : "/api/ops/saved-alternates", + // Every compacted saved video and what its original waits for (a review, a + // drop, nothing): the compaction review list. + "compaction-review": (slug) => + slug ? `/api/ops/compaction-review?slug=${encodeURIComponent(slug)}` : "/api/ops/compaction-review", // Every site: id, title, siteUrl, Pages project, audience, policy, channels. sites: () => "/api/ops/sites", // The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's, @@ -377,6 +381,7 @@ const GET_ARG_OPTIONAL = new Set([ "settings", "storage", "saved-alternates", + "compaction-review", "sites", "archives", "workers", @@ -497,6 +502,13 @@ const ACTIONS = [ // A channel's saved containers remuxed losslessly into browser-playable // copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}). "prepare-playable", + // Saved videos re-encoded to AV1, verified, made the active copy, the + // original kept beside it ({items: [{slug, id}]} | {select: true, slugs?}, + // dryRun?, retryFailed?, crf?, preset?, maxFps?, chunkMinutes?); and a + // person's review of one, which lets a gone video's original be dropped + // ({slug, id, note?}). + "compact-saved-videos", + "review-compacted-original", // Write transcript.cues.json from each video's raw transcript ({slug, ids?, // force?}) — what a reader with no index build wants. "build-cues", @@ -1118,6 +1130,7 @@ export function usage() { " pnpm ops get settings [<key>]", " pnpm ops get storage | sites | workers | auto-queue | scheduler", " pnpm ops get saved-alternates [<slug>]", + " pnpm ops get compaction-review [<slug>]", " pnpm ops get services", " pnpm ops get x-session [<slug>]", " pnpm ops get x-run [<run id>]", @@ -1178,6 +1191,12 @@ export function usage() { " replaced). Each video: its line, the active copy, the alternates", " (height, seconds, origin, keptAs).", " Once one is checked, `drop-saved-alternate` deletes it.", + "get compaction-review [<slug>] lists every compacted saved video and what", + ' its original waits for: "awaiting-review" (not known to be on its', + " platform: a person reviews the compacted copy first, with", + ' review-compacted-original), "reviewed", "kept" (dropOriginal "keep"),', + ' "drop-pending" or "dropped". Each: its line (a re-encode, of what, how),', + " availability, the original's entry, sizes, checks and the re-check.", "get sites lists every site: id, title, siteUrl, Pages project, audience,", " listed, search, publish policy, channels, citedChannels. (`get publish`", " is the status.)", @@ -1435,6 +1454,10 @@ export function usage() { ' saved-video.json (the rest of the pointer is untouched); one already', ' gone is cleaned from the pointer ("existed": false). "dryRun": true', ' answers the same and changes nothing. No undo.', + ' An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs', + ' "confirmOriginal": true; the compacted copy is read back from disk', + " (size, sha256, container, length) before it goes, and a video not known", + " to be on its platform needs its review recorded first.", "", 'diarize runs a channel\'s "Diarize speakers" as a job: {"slug"}. Every video', ' still holding audio with no current diarization.json is diarized, and a', @@ -1847,6 +1870,29 @@ export function usage() { " is kept beside it, flagged for a check (`get saved-alternates`) or kept", " as the proxy; nothing is deleted.", "", + 'compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings', + ' savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the', + " source's height, Kick and Twitch above 30 fps to 30, the audio copied),", + ' verifies the copy and makes it the active one; the original stays beside', + ' it ("keptAs": "original"): {"items": [{"slug", "id"}, ...]} names videos', + ' (deliberately stored only: pinned, an explicit persist, a requested or', + ' landed container -- never a keep-latest one); {"select": true, "slugs"?}', + " asks the selector (and platform, height and video bitrate). \"dryRun\":", + " true answers each video's line -- size, bitrate, height, fps, the", + " estimate (size, hours), the disk it needs against what is free, or why", + ' it is skipped -- and starts nothing. "crf", "preset", "maxFps",', + ' "chunkMinutes" override the settings for the run; "retryFailed": true', + " runs one whose last checks failed. One job per channel on the compact", + " queue, one video at a time, each chunk through the heavy slot; a re-run", + " resumes. Under dropOriginal \"after-verify\" the original is dropped in", + " a later step once the copy re-checks from disk -- never for a video not", + " known to be on its platform (get compaction-review).", + "", + 'review-compacted-original records a person\'s review of one compacted copy:', + ' {"slug", "id", "note"?}. It changes nothing on disk; it is what lets', + ' drop-saved-alternate ("confirmOriginal": true) drop the original of a', + " video not known to be on its platform.", + "", 'import-archive-org imports archive.org media into a channel, as one job on', ' archive.org\'s queue: {"slug", "item", "files": [...] | "match": "<regex>"}', ' for one item; {"slug", "items": ["<id>" | {"item", "files"? | "match"?},', diff --git a/settings.json.example b/settings.json.example @@ -146,6 +146,29 @@ "dest": "", "intervalMinutes": 1440 }, + "savedVideoCompaction": { + "platforms": [ + "kick", + "twitch", + "rumble" + ], + "minVideoMbps": 3, + "minHeight": 720, + "crf": 36, + "preset": 8, + "maxFps": 30, + "maxFpsPlatforms": [ + "kick", + "twitch" + ], + "chunkMinutes": 10, + "qualitySamples": 12, + "vmafMinMean": 90, + "vmafMinSample": 85, + "ssimMinMean": 0.95, + "ssimMinSample": 0.9, + "dropOriginal": "after-verify" + }, "storage": { "locations": [], "defaultLocationId": ""