commit b2934794506772ee58e766947258152729a27458
parent aebd1ed4fb772cd856c83e99cc7472e0f920f19c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 14 Nov 2026 00:58:26 -0500
Merge main into lane/clip-kit-2: the full-frame rule (lane/teaser-chrome) and compact-store
editor/CHANGELOG.md: both sides' entries kept. The clip kit adds no deck region or Play
layer: its promo card, desktop plate and captions, short QR, hidden regions, zooms and
cold open are drawn into the per-clip segments (or, for hidden regions in Play, into the
footage canvas), which the full-frame blackouts do not touch. Tests pin that a short or a
desktop clip of a take with a cold-open teaser and an analysis ending plans and builds
the clip alone, as before.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
83 files changed, 7731 insertions(+), 158 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,9 @@ 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, <id>-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/<id>/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"? (<id>-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, every other stream and the chapters 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: a pin, an explicit persist, a requested or landed container -- never keep-latest, never persist-kept's override); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate) and is a DRY RUN unless "dryRun": false. A named video the selector would not pick is refused unless "belowThreshold": true (the refusal says how little it saves). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs, or why it is skipped. "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 Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | |
+| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "<file>" reviews the active copy that replaced a former original instead. | |
+| `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | |
| `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 +202,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:<slug>:<id>), 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; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. A FORMER original ("former-original") needs its own "confirmFormerOriginal": true, and the same gone/review rule. | |
| `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)} -> {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 +254,8 @@ 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 kept-originals [<slug>]
pnpm ops get services
pnpm ops get x-session [<slug>]
pnpm ops get x-run [<run id>]
@@ -309,6 +314,20 @@ 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 freshly checked 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 and why, the original's entry, sizes, checks, the re-check,
+ "watch" (both files and an smplayer command that plays them) and any
+ "leftover" of an interrupted drop.
+get kept-originals [<slug>] lists every saved video that keeps an original
+ ("keptAs": "original") or a former original ("former-original") beside
+ its active copy, or has a drop in flight (pendingDrops: a file the pointer
+ no longer lists, still on disk -- drop it again by name to finish). An
+ editor from before compaction would treat those as ordinary droppable
+ alternates: while this is not empty, do not roll the editor back past it.
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,124 @@ 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}' # a dry run: what the selector picks, each with its estimate
+pnpm ops compact-saved-videos --json '{"select":true,"dryRun":false}' --wait # the selector, for real (said by name)
+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, and what to watch
+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}'
+pnpm ops get kept-originals # every pointer keeping an original: read before any rollback
+pnpm ops compaction-markers --json '{}' # the "being compacted" markers, live or stale
+pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}}'
+```
+
+- **ROLLBACK: do not roll the editor back past this release while any pointer keeps an original.** An editor built
+ from before compaction does not know `"keptAs": "original"` or `"former-original"`, and treats such a copy as an
+ ordinary alternate. Its prune and its drop would delete the only original. `pnpm ops get kept-originals` lists
+ every pointer that keeps one, and every drop in flight; when it is empty, a rollback is safe for these files.
+
+- **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. Kick and Twitch above 30 fps go to 30. Every other stream of the source is copied bit for bit:
+ every audio track, subtitles, data, attachments, and the chapters. The re-encode becomes the active copy under its
+ own name, `source-media.compact-av1-<stamp>.mp4` (`.mkv` when the source holds streams an mp4 cannot carry), never
+ the original's. The original stays beside it as the alternate `"keptAs": "original"`, known by its sha256. 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`, a playable copy
+ (`playable.json` `"note": "re-encoded copy"`), a clip window's provenance (`fromReencode`) and a whole-recording
+ `fetch_clip` answer all say it is a re-encode.
+- **Deliberately stored videos only, always.** That is a pointer with `keepReason: "pin"` (a pin, and every landed
+ container: an import, a live recording, attach-media), one marked `explicit` (persist-videos, the video page's
+ Persist source video, the whole-recording fetch), or any `origin` (a container somebody requested). A pointer
+ with `keepReason: "override"` and neither mark is not selected. persist-kept, the keep-latest catch-up, writes
+ "override" too, and a pointer from before the mark cannot say which wrote it. A keep-latest container is never
+ compacted, and neither is the audio beside the record. No flag overrides this.
+- **The selector** (`"select": true`, `"slugs"` narrows it) is a dry run unless the body says `"dryRun": false`. 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 explicitly
+ named video the selector would not pick is refused unless the run says `"belowThreshold": true`. The refusal and
+ the dry run say how little it would save. Always skipped: already compacted, already keeping an original, 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 is hashed fresh first;
+ one whose bytes disagree with the sha256 on its pointer is not compacted. While it runs,
+ `<store dir>/.compacting.json` makes every persist, attach, import, unpersist and drop of that video refuse with a
+ clear line (the container stays where it was; run it again after). The source's packets are scanned once. Chunks
+ of `chunkMinutes` (10) start on source keyframes on the copy's frame grid, in `<store dir>/.compact-scratch/`. Each
+ chunk is one heavy-slot admission (1.5 GB, niced), so it waits while render mode holds the machine. What the
+ encoder wrote is counted against what the chunk must hold; a short or long chunk is encoded once more. A cancel
+ stops the chunk running, a drain waits for it. A re-run (the job's Retry, or the same body again) resumes at the
+ first chunk not done; a restart leaves the job for a person to retry, because the run may drop originals. 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, no gap between frames
+ the source does not have, and the picture's start against the sound's as in the source;
+ - the audio packets identical (bytes, and times to the millisecond);
+ - every other stream and the chapters present (`checks.streams`);
+ - THE WHOLE FILE compared, EVERY FRAME. Both copies are decoded end to end, the source taken to the copy's rate
+ as the encode took it, at 256 px wide, grey, paired frame for frame. The comparison must cover every frame of
+ the copy. Each frame is scored whole:
+ - no frame below `wholeFileSsimMin` (0.9);
+ - a mean of at least `wholeFileSsimMean` (0.97);
+ - no frame below the file's own mean − max(`wholeFileSigmaK` (8) × its spread, `wholeFileSigmaMargin` (0.03)).
+
+ Each frame is also split into an 8×8 grid of tiles, each scored alone: a tile below `wholeFileTileMin` (0.7)
+ for more than `wholeFileTileRunFrames` (2) frames in a row fails, so a small region changed for 3 frames at 30
+ fps does not average away. The pointer records the mean, the spread, the lowest frame and when, and the worst
+ tile and when. It costs about 1.3–1.6× a plain decode of both files;
+ - VMAF on 2-second excerpts across every chunk join, inside every chunk, and at `qualitySamples` (12) more spread
+ through the file: mean at least `vmafMinMean` (90), none below `vmafMinSample` (85). SSIM where this ffmpeg has
+ no libvmaf. Frames are paired by number on one clock;
+ - three windows cut through the evidence cutter from both copies, compared frame by frame: a cut that matches the
+ original's better a frame off fails;
+ - the recording clock (`clock.json`) re-measured against the re-encode and within its tolerance of the old map.
+ The map is then retargeted (its id kept, so windows cut through it stay current) in the swap's own lock.
+- **The swap.** The re-encode is fsynced, then swapped in one locked pointer write. The write happens only while the
+ pointer still names the encoded file, with the same bytes, dir, storedAt and sha256. After the swap nothing is
+ undone: a failure after it is reported as one, with the original kept.
+- **The original.** `dropOriginal` is `"keep"` by default: every original stays until a person drops it. Under
+ `"after-verify"` a separate step, after the swap, reads the re-encode back from disk (fsynced, dropped from the
+ page cache, size, sha256, container, length). It then drops the original only when all of these hold:
+ - the verification included the whole-file comparison;
+ - no download or persist of the video is queued or running;
+ - the video is still on its platform, freshly and first-hand.
+
+ "Freshly and first-hand" means an availability record written by a real check (not a backfill), public or
+ unlisted, at most `availabilityMaxAgeDays` (7) old. Anything else counts as gone, members-only and login walls
+ included, and the original waits in `get compaction-review` (and on /saved-videos) as "compacted, original
+ awaiting review". The log says what refreshes it: Check availability on the channel page's Diagnostics. **There is
+ no backup of the store: after a drop the compacted copy is the only copy.**
+- **A former original** (`"keptAs": "former-original"`: an original whose compacted copy a later persist, attach or
+ import replaced) is dropped only with its own `"confirmFormerOriginal": true`. It follows the same gone/review rule
+ as an original: `review-compacted-original` with `"formerOriginal": "<file>"` reviews the active copy that replaced
+ it. No automatic step ever passes that flag, and the after-verify drop names exactly the original it means (kind,
+ sha256, file), so a copy re-labelled in between is not dropped.
+- **The marker.** `<store dir>/.compacting.json` is held from the start of a compaction through the swap, the
+ re-check and the drop. It is live only on this machine's current boot and host, with the same pid and pid start
+ time, its job still running, and under 72 h old. Anything else is stale and ignored. Stale markers are removed at
+ editor boot, at the start of every compaction run, when the video is skipped as already compacted, and by
+ `compaction-markers {"clear": …}`. A refusal by one video never stops a batch: the prune logs it and goes on.
+- **A review.** `get compaction-review` gives each video's two files and an `smplayer` command that plays both. The
+ editor has no player for the store. Watch them, then record the review (the video page's **Review the compacted
+ copy**, or `review-compacted-original`). A review names the copy it watched (`forSha256`) and counts for that copy
+ only. Then drop the original with `"confirmOriginal": true`. That drop reads the copy back again itself and
+ refuses if it does not match.
+- **Nothing else deletes an original.** The prune keeps a video that holds one. Unpersist brings the original back
+ as the source and refuses a re-encode whose original was dropped. A persist, attach or import over a compacted
+ copy moves the original aside: it becomes `"keptAs": "former-original"`, which no automatic step drops and which
+ is never compacted over. A download planned before a compaction refuses to write over it. A drop writes the
+ pointer before it removes the file; an interrupted one is listed (`leftover`) and finished by asking again.
+- **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,71 @@ 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. |
+| `wholeFileSsimMin` | `0.9` | THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0). |
+| `wholeFileSsimMean` | `0.97` | The whole-file comparison's mean must reach this. Default 0.97. |
+| `wholeFileSigmaK` | `8` | The floor relative to the file itself: no frame below its mean − max(k × the frames' standard deviation, wholeFileSigmaMargin). Default k = 8 (measured: a good crf-36 copy has a spread of 0.0006, its worst frame 3 spreads under its mean). |
+| `wholeFileSigmaMargin` | `0.03` | The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03. |
+| `wholeFileTileMin` | `0.7` | Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46). |
+| `wholeFileTileRunFrames` | `2` | How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails. |
+| `availabilityMaxAgeDays` | `7` | How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7. |
+| `dropOriginal` | `"keep"` | "keep" (the default in this slice): every original stays until a person drops it. "after-verify": 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`); only when the verification included the whole-file comparison. There is no backup of the store: after such a drop the compacted copy is the only copy. |
+
+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,
+ "wholeFileSsimMin": 0.9,
+ "wholeFileSsimMean": 0.97,
+ "wholeFileSigmaK": 8,
+ "wholeFileSigmaMargin": 0.03,
+ "wholeFileTileMin": 0.7,
+ "wholeFileTileRunFrames": 2,
+ "availabilityMaxAgeDays": 7,
+ "dropOriginal": "keep"
+}
+```
+
## `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/backupSavedVideos.ts b/common/controller/backupSavedVideos.ts
@@ -95,7 +95,7 @@ export async function backupSavedVideos({
}
const sha256 = await sha256File(entry.storedPath);
// Cache the checksum back onto the pointer for the store/UI.
- await updateSavedVideoChecksum(entry.videoDir, sha256).catch(() => {});
+ await updateSavedVideoChecksum(entry.videoDir, sha256, entry.pointer.file).catch(() => {});
manifestEntries.push({
slug: entry.slug,
videoId: entry.videoId,
diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts
@@ -0,0 +1,942 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readFile, readdir, rename, 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,
+ listKeptOriginals,
+ sweepCompactingMarkers,
+ planCompaction,
+ type CompactDeps,
+ type Presence,
+} from "./compactSavedVideos";
+import {
+ compareCuts,
+ cutIsOffset,
+ encodeChunkArgs,
+ ffmpegHas,
+ type ChunkPlan,
+ type EncodeSettings,
+} from "../lib/compactMedia-server";
+import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, type SavedVideoCompactionSettings } from "../lib/savedVideoCompaction";
+import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, restoreSavedVideoProvenance, savedVideoPointerPath } from "../lib/savedVideo-server";
+import { compactedOriginalOf, savedVideoPath } from "../lib/savedVideo";
+import { keepDownloadAsAlternate, planSavedContainer } from "../ytdlp/savedAlternates";
+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 most flow
+// tests (x264 ultrafast, the same seek, end and frame-rate handling), so they
+// run without libsvtav1 and in seconds; two run the real SVT-AV1 encode, one
+// of them on the DEFAULT thresholds, skipped where this ffmpeg has no
+// libsvtav1. Every check but the stubbed ones is real (the whole-file
+// comparison, the gap and start checks, the stream inventory). The review's
+// probes (probe1…probe5) are tests here. Skipped 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 NO_SVT = NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1");
+
+const ORIGINAL = "source-media.mp4";
+
+type Gen = { gen?: string; seconds?: number; fps?: number; gop?: number; offset?: number; ext?: string; bf?: number; size?: string };
+
+async function makeSource(file: string, g: Gen = {}): Promise<void> {
+ const seconds = g.seconds ?? 6;
+ const fps = g.fps ?? 60;
+ await execa("ffmpeg", [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", `${g.gen ?? "testsrc"}=size=${g.size ?? "320x180"}:rate=${fps}:duration=${seconds}`,
+ "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`,
+ "-c:v", "libx264", "-preset", g.bf ? "veryfast" : "ultrafast", ...(g.bf ? ["-bf", String(g.bf)] : []),
+ "-g", String(g.gop ?? fps * 2), "-keyint_min", String(g.gop ?? fps * 2), "-sc_threshold", "0", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-b:a", "64k", "-shortest",
+ ...(g.offset ? ["-output_ts_offset", String(g.offset)] : []),
+ 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>;
+};
+
+const sources = new Map<string, string>();
+
+async function withVideo(
+ opts: { platform?: string; keepReason?: string; slug?: string; id?: string; gen?: Gen } = {},
+ 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 }),
+ );
+ const ext = opts.gen?.ext ?? "mp4";
+ const key = JSON.stringify(opts.gen ?? {});
+ if (!sources.has(key)) {
+ const f = path.join(await mkdtemp(path.join(tmpdir(), "compact-src-")), `source-media.${ext}`);
+ await makeSource(f, opts.gen);
+ sources.set(key, f);
+ }
+ const file = `source-media.${ext}`;
+ const source = path.join(storeDir, file);
+ await writeFile(source, await readFile(sources.get(key)!));
+ const bytes = (await stat(source)).size;
+ await writeFile(
+ savedVideoPointerPath(videoDir),
+ JSON.stringify({
+ storedAt: "2026-11-01T00:00:00.000Z",
+ dir: storeDir,
+ file,
+ 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 records 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 spread samples, the original dropped after verify.
+const SETTINGS: SavedVideoCompactionSettings = {
+ ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS,
+ chunkMinutes: 2 / 60,
+ qualitySamples: 3,
+ dropOriginal: "after-verify",
+};
+
+// x264 in SVT-AV1's place: the same seek, end, frame-rate handling and clock.
+async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }, crf = 18, defect?: 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", String(crf));
+ if (defect) {
+ const v = args.indexOf("-vf");
+ if (v >= 0) args[v + 1] = `${args[v + 1]},${defect}`;
+ else args.splice(args.indexOf("-c:v"), 0, "-vf", defect);
+ }
+ await execa("ffmpeg", args);
+}
+
+const ON: Presence = { onPlatform: true, availability: "public", why: "checked public today" };
+const GONE = (availability: Presence["availability"]): Presence => ({ onPlatform: false, availability, why: `availability ${availability ?? "unknown"}` });
+
+function flowDeps(extra: CompactDeps = {}): CompactDeps {
+ return {
+ presence: async () => ON,
+ busy: () => null,
+ freeBytes: async () => 1e15,
+ encodeChunk: (o) => x264Chunk(o),
+ score: async () => 95,
+ cutCompare: async () => ({ ssim: 0.99, earlier: 0.95, later: 0.95 }),
+ 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();
+}
+
+const run = (fx: Fx, deps: CompactDeps, settings: SavedVideoCompactionSettings = SETTINGS, onLog: (l: string) => void = () => {}, extra = {}) =>
+ // The fixtures are 180p: below the selector's height, so named with belowThreshold.
+ compactOne({ paths: fx.paths, settings, item: { slug: "kick", id: "v1" }, mode: "explicit", onLog, deps, belowThreshold: true, ...extra });
+
+test("the real encode on the DEFAULT thresholds: every check, swapped, re-checked, the original dropped after", { skip: NO_SVT }, async () => {
+ await withVideo({}, async (fx) => {
+ const log = logger();
+ const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, dropOriginal: "after-verify" as const };
+ const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog);
+ assert.equal(r.status, "compacted", log.lines.join("\n"));
+ const p = (await loadSavedVideo(fx.videoDir))!;
+ assert.match(p.file, /^source-media\.compact-av1-\d{14}\.mp4$/);
+ assert.equal(p.sha256, await sha(path.join(fx.storeDir, p.file)));
+ const c = p.compacted!;
+ assert.equal(c.checks.passed, true);
+ // 60 -> 30 fps on Kick: 360 source frames give 180.
+ assert.deepEqual(c.checks.frames, [360, 180, 180]);
+ assert.equal(c.checks.audio, "identical");
+ assert.equal(c.checks.quality.metric, vmaf ? "vmaf" : "ssim");
+ // Every join and every chunk scored, the spread samples besides.
+ assert.ok(c.checks.quality.samples >= 3 + 3 + 2, String(c.checks.quality.samples));
+ assert.ok(c.checks.quality.mean >= settings.vmafMinMean && c.checks.quality.min >= settings.vmafMinSample, JSON.stringify(c.checks.quality));
+ assert.ok(c.checks.wholeFile && c.checks.wholeFile.min >= 0.9 && c.checks.wholeFile.frames >= 11, JSON.stringify(c.checks.wholeFile));
+ assert.equal(c.checks.cuts.length, 3);
+ assert.deepEqual(c.checks.streams?.source, c.checks.streams?.result);
+ assert.equal(c.result.vcodec, "av1");
+ assert.equal(c.result.fps, 30);
+ assert.equal(c.source.sha256, fx.sourceSha);
+ assert.equal(c.chunks, 3);
+ assert.equal(c.recheck?.ok, true);
+ assert.equal(c.originalDropped?.sha256, fx.sourceSha);
+ assert.equal(c.originalDropped?.fileRemoved, true);
+ assert.equal(compactedOriginalOf(p), null);
+ await assert.rejects(stat(path.join(fx.storeDir, ORIGINAL)));
+ await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch")));
+ await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json")));
+ 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"));
+ });
+});
+
+// PROBE 1: a chunk with the right frame count and the wrong picture.
+test("probe 1: a black chunk, or a chunk of the wrong seconds, fails the whole-file comparison", { skip: NO_TOOLS }, async () => {
+ for (const variant of ["black", "wrong-seconds"]) {
+ await withVideo({ gen: { gen: "testsrc2", seconds: 12, fps: 30, gop: 30 }, platform: "rumble" }, async (fx) => {
+ const before = await fx.pointerText();
+ const r = await run(
+ fx,
+ flowDeps({
+ encodeChunk: async (o) => {
+ if (o.chunk.index !== 3) return x264Chunk(o);
+ if (variant === "black") {
+ await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=black:size=320x180:rate=30",
+ "-frames:v", String(o.chunk.expectedFrames), "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
+ "-video_track_timescale", "90000", "-f", "mp4", o.out]);
+ } else {
+ const shifted = { ...o.chunk, from: o.chunk.from - 4, to: o.chunk.to - 4 };
+ await x264Chunk({ ...o, chunk: shifted });
+ }
+ },
+ }),
+ );
+ assert.equal(r.status, "failed", variant);
+ assert.match((r as { reason: string }).reason, /the whole-file comparison: /, variant);
+ assert.equal(await fx.pointerText(), before);
+ await stat(fx.source);
+ });
+ }
+});
+
+test("probe 1: a short chunk is caught by counting what the encoder wrote", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const r = await run(
+ fx,
+ flowDeps({
+ encodeChunk: async (o) => {
+ if (o.chunk.index !== 1) return x264Chunk(o);
+ // An encoder that stops ten frames early.
+ 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", "-frames:v", String(o.chunk.expectedFrames - 10));
+ await execa("ffmpeg", args);
+ },
+ }),
+ );
+ assert.equal(r.status, "failed");
+ assert.match((r as { reason: string }).reason, /chunk 1 holds 50 frames, not the 60 expected \(encoded twice\)/);
+ });
+});
+
+// PROBE 1b: the scorer pairs frames by number on the copy's grid, so a chunked
+// copy scores like the source (a timestamp pairing paired neighbours).
+test("probe 1b: a chunked 60 -> 30 copy scores as high as it is at every excerpt (frame pairing)", { skip: NO_TOOLS || (!vmaf && "no libvmaf") }, async () => {
+ await withVideo({ gen: { gen: "testsrc2", seconds: 12, fps: 60, gop: 60 } }, async (fx) => {
+ const log = logger();
+ const r = await run(
+ fx,
+ flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }),
+ { ...SETTINGS, dropOriginal: "keep", vmafMinMean: 90, vmafMinSample: 85 },
+ log.onLog,
+ );
+ assert.equal(r.status, "compacted", log.lines.join("\n"));
+ const q = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.quality;
+ assert.ok(q.min >= 85, JSON.stringify(q));
+ });
+});
+
+// PROBE 2: compact, attach over it, compact again under after-verify.
+test("probe 2: an original of an earlier compacted copy is never the one dropped, and is not compacted over", { skip: NO_TOOLS }, async () => {
+ await withVideo({ platform: "rumble" }, async (fx) => {
+ const r1 = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" });
+ assert.equal(r1.status, "compacted");
+ const previous = (await loadSavedVideo(fx.videoDir))!;
+ // Attach another recording over it, as attachMedia does.
+ const staging = path.join(path.dirname(fx.storeDir), ".v1.attach-1.part");
+ await makeSource(`${staging}.mp4`, { gen: "smptebars" });
+ await rename(`${staging}.mp4`, staging);
+ const landed = await persistSourceVideo({ videoDir: fx.videoDir, sourceFilename: ORIGINAL, sourcePath: staging, storeDir: fx.storeDir, keepReason: "pin", origin: { requestedBy: "attach-media" }, paths: fx.paths });
+ if (savedVideoPath(previous) !== savedVideoPath(landed)) await rm(savedVideoPath(previous), { force: true });
+ const p = (await loadSavedVideo(fx.videoDir))!;
+ const former = p.alternates!.find((a) => a.sha256 === fx.sourceSha)!;
+ assert.equal(former.keptAs, "former-original");
+ const r2 = await run(fx, flowDeps(), SETTINGS);
+ assert.equal(r2.status, "skipped");
+ assert.match((r2 as { reason: string }).reason, /already keeps an original/);
+ assert.equal(await sha(path.join(fx.storeDir, former.file)), fx.sourceSha);
+ });
+});
+
+// PROBE 3: a source whose first timestamp is not 0, with B-frames.
+test("probe 3: an offset mp4, an offset mkv and an mpegts are cut from the right seconds", { skip: NO_TOOLS }, async () => {
+ for (const ext of ["mp4", "mkv", "ts"]) {
+ await withVideo({ platform: "rumble", gen: { gen: "testsrc2", seconds: 12, fps: 30, gop: 60, offset: 1.5, ext, bf: 2 } }, async (fx) => {
+ const log = logger();
+ // The REAL scorer and cutter on the default thresholds: a seek that
+ // lands late in any of the three shows as a bad excerpt or a cut a frame off.
+ const r = await run(
+ fx,
+ flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }),
+ { ...SETTINGS, chunkMinutes: 4 / 60, dropOriginal: "keep" },
+ log.onLog,
+ );
+ assert.equal(r.status, "compacted", `${ext}: ${log.lines.join("\n")}`);
+ const c = (await loadSavedVideo(fx.videoDir))!.compacted!;
+ assert.equal(c.checks.frames[1], c.checks.frames[2], ext);
+ assert.ok(c.checks.wholeFile!.min >= 0.9, `${ext}: ${JSON.stringify(c.checks.wholeFile)}`);
+ assert.ok(Math.abs(c.checks.avOffset![0] - c.checks.avOffset![1]) < 0.02, `${ext}: ${JSON.stringify(c.checks.avOffset)}`);
+ if (vmaf) assert.ok(c.checks.quality.min >= 85, `${ext}: ${JSON.stringify(c.checks.quality)}`);
+ });
+ }
+});
+
+// PROBE 4: a download that planned before the compaction writes after it.
+test("probe 4: a download's plan made on the pointer before a compaction is refused after it", { skip: NO_TOOLS }, async () => {
+ await withVideo({ platform: "rumble" }, async (fx) => {
+ const dl = path.join(fx.videoDir, ORIGINAL);
+ await makeSource(dl, { seconds: 5 });
+ const deps = { measure: async (f: string) => (f.startsWith(fx.videoDir) ? 5 : 6), height: async () => 180 };
+ const plan = (await planSavedContainer({ videoDir: fx.videoDir, newContainer: dl, explicit: false, deps }))!;
+ assert.equal(plan.active, "existing");
+ const r = await run(fx, flowDeps());
+ assert.equal(r.status, "compacted");
+ const after = await readFile(savedVideoPointerPath(fx.videoDir), "utf8");
+ await assert.rejects(
+ keepDownloadAsAlternate(plan, { sourceFilename: ORIGINAL, paths: fx.paths, deps, onLog: () => {} }),
+ (e: Error) => e instanceof SavedPointerChangedError && /changed since this download was planned/.test(e.message),
+ );
+ assert.equal(await readFile(savedVideoPointerPath(fx.videoDir), "utf8"), after);
+ const p = (await loadSavedVideo(fx.videoDir))!;
+ await stat(savedVideoPath(p));
+ await stat(dl);
+ });
+});
+
+// PROBE 5: a copy whose picture is a frame off the source's.
+test("probe 5: the cut check catches a copy one frame off, and passes a copy on the frame", { skip: NO_TOOLS }, async () => {
+ const d = await mkdtemp(path.join(tmpdir(), "compact-off-"));
+ try {
+ const src = path.join(d, "src.mp4");
+ await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=12", "-c:v", "libx264", "-preset", "ultrafast", "-g", "30", "-pix_fmt", "yuv420p", src]);
+ const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" };
+ for (const frames of [0, 1, 5]) {
+ const out = path.join(d, `off${frames}.mp4`);
+ await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", src, "-vf", `trim=start_frame=${frames},setpts=PTS-STARTPTS`, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "16", out]);
+ const c = await compareCuts(paths, { compacted: out, source: src, at: 4.9917, seconds: 3, fps: null, sourceFps: 30, scratchDir: d });
+ assert.equal(cutIsOffset(c) || c.ssim < 0.9, frames !== 0, `${frames} frame(s): ${JSON.stringify(c)}`);
+ }
+ } finally {
+ await rm(d, { recursive: true, force: true });
+ }
+});
+
+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 (fx) => {
+ const before = await fx.pointerText();
+ const ac = new AbortController();
+ const first: number[] = [];
+ const r1 = await run(
+ fx,
+ 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);
+ },
+ }),
+ SETTINGS,
+ () => {},
+ { signal: ac.signal },
+ );
+ assert.deepEqual(r1, { status: "stopped", reason: "cancelled" });
+ assert.deepEqual(first, [0, 1]);
+ assert.equal(await fx.pointerText(), before, "the pointer is untouched");
+ const scratch = path.join(fx.storeDir, ".compact-scratch");
+ const files = await readdir(scratch);
+ assert.ok(files.includes("chunk-0000.mp4"));
+ assert.ok(!files.some((f) => f.endsWith(".part")), files.join(","));
+ await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json")), "the marker goes with the run");
+ 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 run(fx, flowDeps({ encodeChunk: async (o) => { second.push(o.chunk.index); await x264Chunk(o); } }), SETTINGS, log.onLog);
+ 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)));
+ });
+});
+
+test("an encoder that dies (not a cancel) keeps the chunks done for the re-run", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const before = await fx.pointerText();
+ const r = await run(fx, 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 fx.pointerText(), before);
+ const state = JSON.parse(await readFile(path.join(fx.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 (fx) => {
+ const before = await fx.pointerText();
+ let encoded = 0;
+ const r = await run(fx, 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 fx.pointerText(), before);
+ // Room for the plan, the start and the first chunk only.
+ let calls = 0;
+ const r2 = await run(fx, flowDeps({ freeBytes: async () => (++calls <= 3 ? 1e15 : 1000) }));
+ assert.equal(r2.status, "stopped");
+ const state = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "state.json"), "utf8"));
+ assert.deepEqual(state.chunks.map((c: { done: boolean }) => c.done), [true, false, false]);
+ assert.equal(await fx.pointerText(), before);
+ });
+});
+
+test("the source is hashed fresh: one that disagrees with its recorded sha256 is not compacted", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const raw = JSON.parse(await readFile(savedVideoPointerPath(fx.videoDir), "utf8"));
+ raw.sha256 = "9".repeat(64);
+ await writeFile(savedVideoPointerPath(fx.videoDir), JSON.stringify(raw));
+ const r = await run(fx, flowDeps());
+ assert.equal(r.status, "failed");
+ assert.match((r as { reason: string }).reason, /do not match the sha256 recorded on its pointer/);
+ });
+});
+
+test("a failed verification leaves the original active and untouched, the re-encode removed, the reason recorded", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const before = await fx.pointerText();
+ const log = logger();
+ const r = await run(fx, flowDeps({ score: async () => 42 }), SETTINGS, log.onLog);
+ assert.equal(r.status, "failed");
+ assert.match((r as { reason: string }).reason, /verification failed: VMAF 42\.00 mean/);
+ assert.equal(await fx.pointerText(), before);
+ assert.equal(await sha(fx.source), fx.sourceSha);
+ assert.deepEqual(await readdir(path.join(fx.storeDir, ".compact-scratch")), ["failed.json"]);
+ assert.deepEqual((await readdir(fx.storeDir)).sort(), [".compact-scratch", ORIGINAL]);
+ assert.ok(log.lines.some((l) => /NOT compacted .*The original stays the active copy, untouched/.test(l)));
+ const plan = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, 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: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], retryFailed: true, belowThreshold: true, deps: flowDeps() });
+ assert.equal(again.items[0].compact, true);
+ });
+});
+
+test("an audio stream that is not the source's fails the check, and the record says so", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const before = await fx.pointerText();
+ let n = 0;
+ const r = await run(fx, 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 fx.pointerText(), before);
+ const failed = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "failed.json"), "utf8"));
+ assert.equal(failed.checks.audio, "different");
+ });
+});
+
+test("a stream the copy loses fails the check", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ let n = 0;
+ const r = await run(fx, flowDeps({ inventory: async () => (n++ === 0 ? ["audio:aac:1ch", "subtitle:mov_text"] : ["audio:aac:1ch"]) }));
+ assert.equal(r.status, "failed");
+ assert.match((r as { reason: string }).reason, /does not carry every stream of the source/);
+ });
+});
+
+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", "needs_auth"] as const) {
+ await withVideo({}, async (fx) => {
+ const log = logger();
+ const r = await run(fx, flowDeps({ presence: async () => GONE(availability) }), SETTINGS, log.onLog);
+ 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(fx.videoDir))!;
+ assert.equal(compactedOriginalOf(p)?.file, ORIGINAL);
+ await stat(path.join(fx.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: fx.paths, settings: SETTINGS, deps: { presence: async () => GONE(availability) } });
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0].state, "awaiting-review");
+ assert.match(rows[0].watch.command, /^smplayer ".*compact-av1.*" ".*source-media\.mp4"$/);
+ const again = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, 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 (fx) => {
+ const log = logger();
+ let swapHashed = false;
+ const r = await run(
+ fx,
+ flowDeps({
+ sha256: async (file) => {
+ if (/compact-av1/.test(path.basename(file))) return "0".repeat(64);
+ if (/compacted\.mp4$/.test(file)) swapHashed = true;
+ return sha(file);
+ },
+ }),
+ SETTINGS,
+ log.onLog,
+ );
+ assert.ok(swapHashed);
+ assert.equal(r.status, "compacted");
+ assert.equal((r as { dropped: boolean }).dropped, false);
+ const p = (await loadSavedVideo(fx.videoDir))!;
+ assert.equal(p.compacted?.recheck?.ok, false);
+ assert.match(p.compacted?.recheck?.why ?? "", /sha256/);
+ await stat(path.join(fx.storeDir, ORIGINAL));
+ assert.ok(log.lines.some((l) => /re-check after the swap FAILED/.test(l)));
+ });
+ // The re-check holds: when the drop step asks, the pointer already names the
+ // re-encode and the original is still on disk.
+ await withVideo({}, async (fx) => {
+ const seen: { file: string; original: boolean }[] = [];
+ let calls = 0;
+ const r = await run(
+ fx,
+ flowDeps({
+ presence: async () => {
+ if (++calls > 1) {
+ seen.push({
+ file: (await loadSavedVideo(fx.videoDir))!.file,
+ original: await stat(path.join(fx.storeDir, ORIGINAL)).then(() => true, () => false),
+ });
+ }
+ return ON;
+ },
+ }),
+ );
+ 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(fx.videoDir))!;
+ assert.ok(p.compacted?.recheck?.ok);
+ assert.ok(p.compacted!.originalDropped!.at >= p.compacted!.recheck!.at);
+ });
+});
+
+test("no automatic drop while a download of the video is queued or running", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const log = logger();
+ const r = await run(fx, flowDeps({ busy: () => "a persist-videos job (queued, j9) may write this video's saved copy — wait for it to end" }), SETTINGS, log.onLog);
+ assert.equal(r.status, "compacted");
+ assert.equal((r as { dropped: boolean }).dropped, false);
+ await stat(path.join(fx.storeDir, ORIGINAL));
+ assert.ok(log.lines.some((l) => /is kept: a persist-videos job/.test(l)));
+ });
+});
+
+test("an error after the swap reports the swap as done and drops nothing", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const log = logger();
+ const r = await run(
+ fx,
+ flowDeps({
+ sha256: async (file) => {
+ if (/compact-av1/.test(path.basename(file))) throw new Error("EIO reading the new copy");
+ return sha(file);
+ },
+ }),
+ SETTINGS,
+ log.onLog,
+ );
+ assert.equal(r.status, "compacted");
+ assert.match((r as { afterSwapError?: string }).afterSwapError ?? "", /EIO/);
+ assert.equal((r as { dropped: boolean }).dropped, false);
+ await stat(path.join(fx.storeDir, ORIGINAL));
+ assert.ok(log.lines.some((l) => /the swap is written .*After it, a step failed: EIO/.test(l)), log.lines.join("\n"));
+ assert.ok(!log.lines.some((l) => /The original stays the active copy/.test(l)));
+ });
+});
+
+test('dropOriginal "keep" (the default): the original stays', { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const r = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS.dropOriginal });
+ assert.deepEqual([r.status, (r as { review: string }).review], ["compacted", "kept"]);
+ await stat(path.join(fx.storeDir, ORIGINAL));
+ });
+});
+
+test("the selector picks only deliberately stored + platform + bitrate; an explicit item below it needs belowThreshold", 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, Record<string, unknown>, number][] = [
+ // slug, platform, id, pointer facts, video kbps
+ ["kick", "kick", "pinned-hi", { keepReason: "pin" }, 5200],
+ ["kick", "kick", "latest-hi", { keepReason: "keep-latest" }, 5200],
+ ["kick", "kick", "kept-catchup", { keepReason: "override" }, 5200],
+ ["kick", "kick", "pinned-lo", { keepReason: "pin" }, 640],
+ ["tube", "youtube", "pinned-hi", { keepReason: "pin" }, 5200],
+ ["rumble", "rumble", "persisted-hi", { keepReason: "override", explicit: true }, 3400],
+ ];
+ const kbps = new Map<string, number>();
+ for (const [slug, platform, id, facts, 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, ...facts }));
+ }
+ const deps: CompactDeps = {
+ presence: async () => ON,
+ 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, audioStart: 0, formatStart: 0, audioStreams: 1,
+ bytes: 5_000_000_000, mainVideoIndex: 0, container: "mp4",
+ }),
+ };
+ 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/kept-catchup": 'kept as "override" with no record that a person asked for it (persist-kept, the keep-latest catch-up, writes it too): not known to be kept on purpose',
+ "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$/);
+ assert.doesNotMatch(plan.items.find((i) => i.slug === "rumble")!.line, /at 30 fps/);
+ assert.match(plan.lines.at(-1)!, /^total: 2 container\(s\)/);
+ // Explicitly named, below the selector: refused, saying how little it saves.
+ const items = [{ slug: "tube", id: "pinned-hi" }, { slug: "kick", id: "pinned-lo" }, { slug: "kick", id: "latest-hi" }, { slug: "kick", id: "kept-catchup" }];
+ const explicit = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, items, deps });
+ assert.deepEqual(explicit.items.map((i) => i.compact), [false, false, false, false]);
+ assert.match(explicit.items[1].reason!, /below minVideoMbps 3; named explicitly, it is compacted only with "belowThreshold": true \(it would save about .* of 4\.66 GB\)/);
+ const allowed = await planCompaction({ paths, settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, items, belowThreshold: true, deps });
+ assert.deepEqual(allowed.items.map((i) => i.compact), [true, true, false, false]);
+ assert.match(allowed.items[1].line, /below the selector's thresholds \(0\.64 Mbit\/s video is below minVideoMbps 3\): it would save about/);
+ 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 (fx) => {
+ const before = await listTree(fx.root);
+ const plan = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, deps: { presence: async () => GONE(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(fx.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 (fx) => {
+ const audio = path.join(fx.videoDir, "audio.mp3");
+ await writeFile(audio, "cue audio");
+ const p = (await loadSavedVideo(fx.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(fx.videoDir, CLOCK_FILE), JSON.stringify(clock));
+ const before = await fx.pointerText();
+ const r = await run(
+ fx,
+ 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,
+ }),
+ { ...SETTINGS, dropOriginal: "keep" },
+ );
+ const written = JSON.parse(await readFile(path.join(fx.videoDir, CLOCK_FILE), "utf8"));
+ if (shift === 0) {
+ assert.equal(r.status, "compacted");
+ const after = (await loadSavedVideo(fx.videoDir))!;
+ assert.equal(after.compacted?.checks.clock, "kept");
+ assert.equal(written.target.file, after.file);
+ assert.equal(written.target.bytes, after.bytes);
+ assert.equal(written.id, "c1");
+ assert.equal(written.retargeted.from.file, ORIGINAL);
+ assert.equal(written.retargeted.measured, "c2");
+ } else {
+ assert.equal(r.status, "failed");
+ assert.match((r as { reason: string }).reason, /the recording clock moved/);
+ assert.equal(await fx.pointerText(), before);
+ assert.equal(written.id, "c1");
+ assert.equal(written.target.file, ORIGINAL);
+ }
+ });
+ }
+});
+
+test("compactSavedVideos runs a list one at a time and a drain stops between videos", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const drain = new AbortController();
+ drain.abort();
+ const r = await compactSavedVideos({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], mode: "explicit", belowThreshold: true, 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_SVT }, async () => {
+ await withVideo({}, async (fx) => {
+ // A stand-in for scripts/queue-lock.mjs: records each argv, runs the rest.
+ const repo = path.join(fx.root, "repo");
+ await mkdir(path.join(repo, "scripts"), { recursive: true });
+ const marker = path.join(fx.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: { ...fx.paths, monorepoRoot: repo } as Paths,
+ settings: { ...SETTINGS, dropOriginal: "keep" },
+ item: { slug: "kick", id: "v1" },
+ mode: "explicit",
+ belowThreshold: true,
+ onLog: () => {},
+ deps: { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15, score: async () => 95, cutCompare: async () => ({ ssim: 0.99, earlier: 0.9, later: 0.9 }) },
+ });
+ 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"]);
+ assert.ok(runs.some((a) => a.includes("-xerror")), "the full decode");
+ assert.ok(runs.some((a) => a.some((x) => /wf-graph/.test(x))), "the whole-file comparison");
+ });
+});
+
+// --- review round 2 ------------------------------------------------------------
+
+// F2: the defects the first whole-file comparison passed, on the DEFAULT
+// thresholds, every check real (the reviewer's set: 0.47 s of black between
+// two ticks, 3 black frames at a chunk join, 2.5 s of heavy noise, a ~3%
+// region changed for 3 s), and the smaller ones the tiles now catch.
+test("F2: every listed defect fails the whole-file comparison on the default thresholds", { skip: NO_TOOLS }, async () => {
+ const defects: [string, (c: ChunkPlan) => string | undefined][] = [
+ ["0.47 s of black", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='between(t,1.1,1.57)'" : undefined)],
+ ["3 black frames at a join", (c) => (c.index === 0 ? `drawbox=c=black:t=fill:enable='gte(n,${c.expectedFrames - 3})'` : undefined)],
+ ["2.5 s of heavy noise", (c) => (c.index === 1 ? "noise=alls=60:allf=t:enable='between(t,0.5,3)'" : undefined)],
+ ["a 3% region for 3 s", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=110:h=63:c=red:t=fill:enable='between(t,0.5,3.5)'" : undefined)],
+ ["a 1% region for 3 frames", (c) => (c.index === 1 ? "drawbox=x=300:y=150:w=64:h=36:c=red:t=fill:enable='between(n,30,32)'" : undefined)],
+ ["one black frame", (c) => (c.index === 1 ? "drawbox=c=black:t=fill:enable='eq(n,40)'" : undefined)],
+ ];
+ for (const [label, defect] of defects) {
+ await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 12, fps: 30, gop: 30 } }, async (fx) => {
+ const before = await fx.pointerText();
+ const r = await run(fx, flowDeps({ encodeChunk: (o) => x264Chunk(o, 18, defect(o.chunk)) }), { ...SETTINGS, chunkMinutes: 4 / 60 });
+ assert.equal(r.status, "failed", label);
+ assert.match((r as { reason: string }).reason, /verification failed: the whole-file comparison: /, label);
+ assert.equal(await fx.pointerText(), before, label);
+ await stat(fx.source);
+ });
+ }
+});
+
+test("F2: a GOOD SVT-AV1 crf-36 encode of a detailed 640x360 fixture passes every default threshold, with margin", { skip: NO_SVT }, async () => {
+ await withVideo({ platform: "rumble", gen: { gen: "testsrc2", size: "640x360", seconds: 6, fps: 30, gop: 60 } }, async (fx) => {
+ const log = logger();
+ const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3 };
+ const r = await run(fx, { presence: async () => ON, busy: () => null, freeBytes: async () => 1e15 }, settings, log.onLog);
+ assert.equal(r.status, "compacted", log.lines.join("\n"));
+ const w = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.wholeFile!;
+ assert.equal(w.frames, 180);
+ assert.equal(w.grid, 8);
+ // The margins the defaults keep over a good copy (measured 0.996 / 0.949).
+ assert.ok(w.min >= settings.wholeFileSsimMin + 0.05, JSON.stringify(w));
+ assert.ok(w.min >= w.relativeFloor! + 0.01, JSON.stringify(w));
+ assert.ok(w.worstTile && w.worstTile.min >= settings.wholeFileTileMin + 0.1 && w.worstTile.longestBelow === 0, JSON.stringify(w));
+ });
+});
+
+test("F3: a stale marker beside an already compacted video is cleared, and every run sweeps the store", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const r1 = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" });
+ assert.equal(r1.status, "compacted");
+ // The state a crash between the swap and the marker's removal leaves.
+ const marker = path.join(fx.storeDir, ".compacting.json");
+ await writeFile(marker, JSON.stringify({ pid: 2 ** 22 + 7, host: "x", startedAt: "2026-11-01T00:00:00Z", token: "t" }));
+ const log = logger();
+ const r2 = await run(fx, flowDeps(), SETTINGS, log.onLog);
+ assert.equal(r2.status, "skipped");
+ await assert.rejects(stat(marker));
+ assert.ok(log.lines.some((l) => /a stale compaction marker removed/.test(l)), log.lines.join("\n"));
+ await writeFile(marker, JSON.stringify({ pid: 2 ** 22 + 7, host: "x", startedAt: "2026-11-01T00:00:00Z", token: "t" }));
+ const swept = await sweepCompactingMarkers(fx.paths);
+ assert.deepEqual(swept.map((x) => [x.id, x.cleared]), [["v1", true]]);
+ await assert.rejects(stat(marker));
+ });
+});
+
+test("F4: the marker is held through the swap, the re-check and the drop; a persist in that window is refused", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ let calls = 0;
+ let during = "";
+ const r = await run(
+ fx,
+ flowDeps({
+ presence: async () => {
+ // The second call is afterSwap's, just before the drop.
+ if (++calls === 2) {
+ const dl = path.join(fx.videoDir, "source-media.webm");
+ await writeFile(dl, "a download");
+ during = await persistSourceVideo({ videoDir: fx.videoDir, sourceFilename: "source-media.webm", storeDir: fx.storeDir, paths: fx.paths }).then(
+ () => "went through",
+ (e) => (e as Error).name,
+ );
+ }
+ return ON;
+ },
+ }),
+ );
+ assert.equal(during, "CompactionInProgressError");
+ assert.equal(r.status, "compacted");
+ assert.equal((r as { dropped: boolean }).dropped, true, "the compaction's own drop passes its marker");
+ await assert.rejects(stat(path.join(fx.storeDir, ".compacting.json")), "released at the very end");
+ });
+});
+
+test("the swap's compare-and-swap covers keepReason, origin and explicit", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ const r = await run(
+ fx,
+ flowDeps({
+ encodeChunk: async (o) => {
+ await x264Chunk(o);
+ if (o.chunk.index === 1) await restoreSavedVideoProvenance(fx.videoDir, { keepReason: "keep-latest" });
+ },
+ }),
+ );
+ assert.equal(r.status, "failed");
+ assert.match((r as { reason: string }).reason, /the saved copy changed while it was being compacted/);
+ assert.equal((await loadSavedVideo(fx.videoDir))!.file, ORIGINAL);
+ });
+});
+
+test("kept-originals lists every pointer that keeps an original (what a rollback would mistreat)", { skip: NO_TOOLS }, async () => {
+ await withVideo({}, async (fx) => {
+ assert.deepEqual(await listKeptOriginals({ paths: fx.paths }), []);
+ await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" });
+ const rows = await listKeptOriginals({ paths: fx.paths });
+ assert.equal(rows.length, 1);
+ assert.deepEqual(rows[0].kept.map((k) => [k.file, k.keptAs, k.sha256]), [[ORIGINAL, "original", fx.sourceSha]]);
+ });
+});
diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts
@@ -0,0 +1,1489 @@
+// 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 (deliberately stored always; an explicit item the
+// selector would not pick only with `belowThreshold`). A dry run stops
+// here and prints the estimate and the disk it needs.
+// 2. HASH THE SOURCE, fresh, every run (never the pointer's word): a stored
+// sha256 that disagrees stops the run.
+// 3. ENCODE IN CHUNKS, in `<store dir>/.compact-scratch/` (the store's own
+// drive), with `<store dir>/.compacting.json` saying so to every persist
+// of the video. Chunks start on source keyframes (on the copy's frame
+// grid); each is one heavy-slot admission; what the encoder WROTE is
+// counted against what the chunk must hold; the state is recorded so a
+// Retry resumes. Cancel and drain between chunks; the disk floor before
+// the first and before each one.
+// 4. MUX: the chunks joined; every other stream of the source (audio,
+// subtitles, data, attachments) and its chapters copied.
+// 5. 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 length within a frame; the frame
+// count; no gap between frames the source does not have; the picture's
+// start against the sound's; the audio packets identical; every other
+// stream and the chapters there; THE WHOLE FILE compared at 2 frames a
+// second; VMAF (or SSIM) on excerpts across every chunk join, inside
+// every chunk and spread through the file; windows cut from both copies
+// through the evidence cutter, frame-exact; the recording clock.
+// 6. SWAP, fsynced first, in one locked pointer write that compares the
+// pointer's file, bytes, dir, storedAt and sha256 with what was encoded:
+// the re-encode (its OWN name) becomes `file`; the original joins
+// `alternates` as `keptAs: "original"`, identified by its sha256;
+// `compacted` records every number; the clock map is retargeted in the
+// same lock.
+// 7. RECHECK, a separate step: the re-encode read back from disk.
+// 8. DROP THE ORIGINAL, another separate step, only under `dropOriginal:
+// "after-verify"`, only after a whole-file comparison, only while nothing
+// is downloading the video, and NEVER for a video not freshly checked on
+// its platform (that one waits for a person's review). The drop runs
+// dropSavedAlternate, which reads the copy back again itself.
+
+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,
+ parseSavedVideoPointer,
+ reviewIsCurrent,
+ savedVideoPath,
+ type SavedVideoAlternate,
+ type SavedVideoCompacted,
+ type SavedVideoCompactedChecks,
+ type SavedVideoPointer,
+} from "../lib/savedVideo";
+import {
+ SavedAlternateRefusal,
+ dropSavedAlternate,
+ fsyncFileAndDir,
+ loadSavedVideo,
+ readBackCompactedCopy,
+ savedVideoPointerPath,
+ updateSavedVideoChecksum,
+ withPointerLock,
+} from "../lib/savedVideo-server";
+import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore";
+import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
+import { platformPresence } from "../lib/availability-server";
+import { getFreeBytes } from "../lib/diskSpace";
+import { formatBytes } from "../lib/format";
+import {
+ COMPACTION_DISK_MARGIN_BYTES,
+ COMPACTION_SCRATCH_DIRNAME,
+ COMPACTION_STATE_FILENAME,
+ COMPACTION_TOOL,
+ compactedFileName,
+ compactionFreeNeeded,
+ decideCompaction,
+ estimateCompaction,
+ sanitizeSavedVideoCompaction,
+ targetFps,
+ type CompactionEstimate,
+ type CompactionReviewState,
+ type SavedVideoCompactionSettings,
+} from "../lib/savedVideoCompaction";
+import {
+ CHUNK_ESTIMATE_MB,
+ CHUNK_EXT,
+ WHOLE_FILE_GRID,
+ WHOLE_FILE_WIDTH,
+ audioPacketsHash,
+ compareCuts,
+ compareWholeFile,
+ concatList,
+ countVideoFrames,
+ cutIsOffset,
+ encodeChunkArgs,
+ ffmpegHas,
+ ffmpegVersionLine,
+ fullDecode,
+ muxArgs,
+ planChunks,
+ probeCompactionSource,
+ sameAudioTiming,
+ runHeavyFfmpeg,
+ sampleTimes,
+ scanVideoPackets,
+ scoreExcerpt,
+ streamInventory,
+ type AudioHash,
+ type ChunkPlan,
+ type CutComparison,
+ type EncodeSettings,
+ type PacketScan,
+ type SourceProbe,
+ type WholeFileComparison,
+ judgeWholeFile,
+} from "../lib/compactMedia-server";
+import { clearCompactingMarker, readCompactingMarker, writeCompactingMarker } from "../lib/compactingMarker-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 frame by frame: below this the copy's
+// cut is another picture; better a frame off than as cut, it lands elsewhere.
+export const CUT_SSIM_MIN = 0.9;
+export const FAILED_FILENAME = "failed.json";
+const STATE_VERSION = 2;
+
+export type Presence = { onPlatform: boolean; availability: Availability | null; why: string };
+
+// --- deps (a test replaces what it judges) ----------------------------------
+
+export type CompactDeps = {
+ now?: () => Date;
+ freeBytes?: (dir: string) => Promise<number>;
+ // Still on its platform, freshly and first-hand (availability-server's
+ // platformPresence with settings.availabilityMaxAgeDays).
+ presence?: (videoDir: string) => Promise<Presence>;
+ // A download or persist of the video queued or running (controller/videoBusy.ts).
+ busy?: (slug: string, id: string) => string | null | Promise<string | 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; probe: SourceProbe; out: string; signal?: AbortSignal }) => Promise<void>;
+ fullDecode?: (file: string, signal?: AbortSignal) => Promise<{ ok: boolean; why?: string }>;
+ audioHash?: (file: string, signal?: AbortSignal) => Promise<AudioHash>;
+ inventory?: (file: string, skipIndex: number) => Promise<string[]>;
+ wholeFile?: (o: Parameters<typeof compareWholeFile>[1]) => Promise<WholeFileComparison>;
+ hasVmaf?: () => Promise<boolean>;
+ score?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; sourceFps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>;
+ cutCompare?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<CutComparison>;
+ 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, settings: SavedVideoCompactionSettings, deps: CompactDeps = {}): Required<CompactDeps> {
+ return {
+ now: deps.now ?? (() => new Date()),
+ freeBytes: deps.freeBytes ?? getFreeBytes,
+ presence:
+ deps.presence ??
+ ((d) =>
+ platformPresence(d, { maxAgeDays: settings.availabilityMaxAgeDays }).catch(() => ({
+ onPlatform: false,
+ availability: null,
+ why: "its availability could not be read",
+ }))),
+ busy: deps.busy ?? (async (slug, id) => (await import("./videoBusy")).videoPersistBusyReason(slug, id)),
+ 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,
+ // The video's start RELATIVE to the file's (ffmpeg moves every input
+ // to start at 0, the copied streams of the source with it).
+ muxArgs(o.list, o.src, Math.max(0, o.probe.videoStart - o.probe.formatStart), o.out, {
+ mainVideoIndex: o.probe.mainVideoIndex,
+ container: o.probe.container,
+ }),
+ { 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, paths.ffprobeBin)),
+ inventory: deps.inventory ?? ((f, skip) => streamInventory(paths.ffprobeBin, f, skip)),
+ wholeFile: deps.wholeFile ?? ((o) => compareWholeFile(paths, o)),
+ 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;
+ // Still on its platform, freshly and first-hand; else counted as gone.
+ onPlatform: boolean;
+ availability: Availability | null;
+ presence?: string;
+ // An explicit item the selector would not pick: why (ruling 9).
+ belowThreshold?: string;
+ 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, v: STATE_VERSION });
+}
+
+export async function planOne(opts: {
+ paths: Paths;
+ item: CompactItem;
+ mode: "explicit" | "select";
+ settings: SavedVideoCompactionSettings;
+ retryFailed?: boolean;
+ belowThreshold?: 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 presence = await deps.presence(videoDir);
+ 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: presence.onPlatform, availability: presence.availability, presence: presence.why };
+ const decision = decideCompaction({
+ pointer,
+ platform,
+ channelExcluded: config.excludeFromCompaction === true,
+ mode: opts.mode,
+ containerPresent: present,
+ probe,
+ settings,
+ ...(opts.belowThreshold ? { belowThreshold: true } : {}),
+ });
+ 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)}`
+ : "";
+ const fps = probe ? targetFps(probe.fps, platform, settings) : null;
+ const estimate = probe?.hasVideo && probe.seconds ? estimateCompaction({ probe, crf: settings.crf, fps }) : null;
+ // HOW LITTLE IT WOULD SAVE (ruling 9), said wherever a below-threshold item is.
+ const saves = estimate
+ ? `it would save about ${formatBytes(Math.max(0, pointer.bytes - estimate.bytes[1]))}–${formatBytes(Math.max(0, pointer.bytes - estimate.bytes[0]))} of ${formatBytes(pointer.bytes)}`
+ : "";
+ if (!decision.ok) {
+ const reason = decision.belowThreshold && saves ? `${decision.reason} (${saves})` : decision.reason;
+ return { ...skip(reason, { ...facts, line: brief ? `${brief} —` : "", ...(decision.belowThreshold ? { belowThreshold: decision.belowThreshold } : {}) }), pointer, probe };
+ }
+ const failed = await lastFailure(pointer.dir);
+ 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 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 = presence.onPlatform ? "" : `; not known to be on its platform (${presence.why}): 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") +
+ (decision.belowThreshold ? `; below the selector's thresholds (${decision.belowThreshold}): ${saves}` : "") +
+ gone;
+ return {
+ ...base,
+ ...facts,
+ compact: true,
+ ...(decision.belowThreshold ? { belowThreshold: decision.belowThreshold } : {}),
+ source: {
+ file: pointer.file,
+ bytes: pointer.bytes,
+ vcodec: probe!.vcodec,
+ height: probe!.height,
+ fps: probe!.fps,
+ seconds: probe!.seconds,
+ videoMbps: mbps,
+ },
+ fps,
+ estimate: 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;
+ belowThreshold?: boolean;
+ deps?: CompactDeps;
+}): Promise<CompactPlan> {
+ const deps = resolveDeps(opts.paths, opts.settings, 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,
+ belowThreshold: opts.belowThreshold,
+ 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 = ChunkPlan & { file: string; bytes?: number; done: boolean };
+
+type CompactState = {
+ version: typeof STATE_VERSION;
+ sourceFile: string;
+ sourceBytes: number;
+ sourceSha256: string;
+ settingsKey: string;
+ startedAt: string;
+ sourceFrames: number;
+ sourceFirstPts: number;
+ sourceLastPts: number;
+ sourceFrameStep: number;
+ sourceMaxGap: number;
+ chunks: ChunkState[];
+};
+
+export type CompactOneResult =
+ | {
+ status: "compacted";
+ line: string;
+ pointer: SavedVideoPointer;
+ dropped: boolean;
+ review: CompactionReviewState;
+ // Something after the swap failed: the swap stands; this says what.
+ afterSwapError?: string;
+ }
+ | { 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 === STATE_VERSION && Array.isArray(s.chunks) ? s : null;
+}
+
+function maxGap(pts: Float64Array): number {
+ let g = 0;
+ for (let i = 1; i < pts.length; i += 1) g = Math.max(g, pts[i] - pts[i - 1]);
+ return g;
+}
+
+export type CompactRunOptions = {
+ paths: Paths;
+ // The job this run is (its marker names it; the registry is asked).
+ jobId?: string;
+ 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; belowThreshold?: boolean },
+): Promise<CompactOneResult> {
+ const log = (s: string) => opts.onLog(s.endsWith("\n") ? s : `${s}\n`);
+ const deps = resolveDeps(opts.paths, opts.settings, opts.deps);
+ const planned = await planOne({
+ paths: opts.paths,
+ item: opts.item,
+ mode: opts.mode,
+ settings: opts.settings,
+ retryFailed: opts.retryFailed,
+ belowThreshold: opts.belowThreshold,
+ deps,
+ });
+ if (!planned.compact || !planned.pointer || !planned.probe) {
+ // A stale marker beside a video that is not compacted now (an already
+ // compacted one after a crash between the swap and the marker's
+ // removal) is cleared here, so it never blocks the video.
+ if (planned.pointer) {
+ const c = await clearCompactingMarker(planned.pointer.dir).catch(() => null);
+ if (c?.cleared) log(`${opts.item.slug}/${opts.item.id}: a stale compaction marker removed (${c.why}).`);
+ }
+ log(planned.line);
+ return { status: "skipped", reason: planned.reason ?? "not a candidate" };
+ }
+ await assertSavedVideosStoreWritable(opts.paths, planned.pointer.dir);
+ const existing = await readCompactingMarker(planned.pointer.dir);
+ if (existing) {
+ const c = await clearCompactingMarker(planned.pointer.dir);
+ if (!c.cleared) return { status: "skipped", reason: `another compaction of this video is running (${c.why})` };
+ log(`${opts.item.slug}/${opts.item.id}: a stale compaction marker removed (${c.why}).`);
+ }
+ // THE MARKER every persist, attach, import, unpersist and drop of this
+ // video reads (lib/compactingMarker-server.ts): written before anything
+ // else, HELD through the swap, the re-check and the drop (review F4), and
+ // removed only at the very end. The compaction's own steps pass its token.
+ const marker = await writeCompactingMarker(planned.pointer.dir, {
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ video: `${opts.item.slug}/${opts.item.id}`,
+ now: deps.now(),
+ });
+ try {
+ return await compactPlanned(opts, deps, planned, log, marker.token);
+ } finally {
+ await clearCompactingMarker(planned.pointer.dir, { token: marker.token }).catch(() => {});
+ }
+}
+
+// EVERY STALE MARKER IN THE STORE removed (lib/compactingMarker-server.ts
+// says what stale is): at editor boot and at the start of every compaction
+// run. Answers what it found.
+export async function sweepCompactingMarkers(paths: Paths, onLog?: (l: string) => void): Promise<{ slug: string; id: string; cleared: boolean; why: string }[]> {
+ const out: { slug: string; id: string; cleared: boolean; why: string }[] = [];
+ for (const e of await listSavedVideos({ paths }).catch(() => [])) {
+ const m = await readCompactingMarker(e.pointer.dir).catch(() => null);
+ if (!m) continue;
+ const c = await clearCompactingMarker(e.pointer.dir).catch((err) => ({ cleared: false, why: (err as Error).message }));
+ out.push({ slug: e.slug, id: e.videoId, ...c });
+ if (c.cleared) onLog?.(`${e.slug}/${e.videoId}: a stale compaction marker removed (${c.why}).\n`);
+ }
+ return out;
+}
+
+async function compactPlanned(
+ opts: CompactRunOptions & { item: CompactItem },
+ deps: Required<CompactDeps>,
+ planned: Awaited<ReturnType<typeof planOne>>,
+ log: (s: string) => void,
+ // The marker's token: the drop step passes it (the marker is still held).
+ markerToken: string,
+): Promise<CompactOneResult> {
+ const { settings: s, signal } = opts;
+ const tag = `${opts.item.slug}/${opts.item.id}`;
+ 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 mkdir(scratch, { recursive: true });
+ let swapped = false;
+ let state: CompactState | null = null;
+ try {
+ // ---- 2. the source, hashed fresh ----
+ const low0 = await floor(0);
+ if (low0) return { status: "stopped", reason: low0 };
+ log(`${tag}: hashing ${pointer.file} (${formatBytes(pointer.bytes)}) — the original's sha256 is read fresh, never taken from the pointer.`);
+ const sourceSha = await deps.sha256(src, signal);
+ if (pointer.sha256 && pointer.sha256 !== sourceSha) {
+ return {
+ status: "failed",
+ reason:
+ `${pointer.file}'s bytes do not match the sha256 recorded on its pointer (${pointer.sha256.slice(0, 12)}… recorded, ` +
+ `${sourceSha.slice(0, 12)}… now): the stored original is not what was saved — nothing is compacted`,
+ };
+ }
+ if (!pointer.sha256) await updateSavedVideoChecksum(videoDir, sourceSha, pointer.file);
+
+ state = await loadState(stateFile);
+ if (
+ state &&
+ (state.sourceFile !== pointer.file || state.sourceBytes !== pointer.bytes || state.settingsKey !== settingsKey || state.sourceSha256 !== sourceSha)
+ ) {
+ 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);
+ if (!state) {
+ 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, probe.fps);
+ if (!plan.length) return { status: "failed", reason: "the source has no video packets" };
+ const n = scan.pts.length;
+ state = {
+ version: STATE_VERSION,
+ sourceFile: pointer.file,
+ sourceBytes: pointer.bytes,
+ sourceSha256: sourceSha,
+ 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),
+ sourceMaxGap: maxGap(scan.pts),
+ chunks: plan.map((c) => ({ ...c, file: `chunk-${String(c.index).padStart(4, "0")}${CHUNK_EXT}`, 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.`);
+ }
+
+ // ---- 3. the chunks ----
+ const enc: EncodeSettings = {
+ preset: s.preset,
+ crf: s.crf,
+ gopSeconds: COMPACT_GOP_SECONDS,
+ pixFmt: COMPACT_PIX_FMT,
+ fps,
+ sourceFps: probe.fps ?? 30,
+ formatStart: probe.formatStart,
+ };
+ 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)…`);
+ // WHAT THE ENCODER WROTE, counted: a short or long chunk 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();
+ }
+
+ // ---- 4. 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 ext = probe.container === "mp4" ? ".mp4" : ".mkv";
+ const muxed = path.join(scratch, `compacted${ext}`);
+ await rm(muxed, { force: true });
+ log(`${tag}: joining ${state.chunks.length} chunk(s), every other stream and the chapters of the source copied…`);
+ await deps.mux({ list: listFile, src, probe, out: muxed, signal });
+
+ // ---- 5. verify ----
+ const { checks, clock: keptClock } = await verify({ ...opts, deps, tag, state, src, muxed, probe, fps, videoDir, pointer, scratch, log });
+
+ // ---- 6. the swap ----
+ const at = deps.now();
+ await fsyncFileAndDir(muxed);
+ 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(() => []), ext);
+ 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: sourceSha,
+ };
+ 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: sourceSha,
+ ...(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 swappedNow = await withPointerLock(videoDir, async () => {
+ const read = await readJsonFile(pointerFile);
+ const raw = read.ok && read.value && typeof read.value === "object" ? { ...(read.value as Record<string, unknown>) } : null;
+ // COMPARE-AND-SWAP: the pointer still names exactly the bytes encoded.
+ if (
+ !raw ||
+ raw.file !== pointer.file ||
+ raw.bytes !== pointer.bytes ||
+ raw.dir !== pointer.dir ||
+ raw.storedAt !== pointer.storedAt ||
+ // …and is still kept for the same reason, by the same request.
+ !sameProvenance(raw, pointer) ||
+ (raw.sha256 !== undefined && raw.sha256 !== sourceSha) ||
+ raw.compacted !== undefined
+ ) {
+ return false;
+ }
+ // The clock first (its old map kept to put back), then the file, then
+ // the pointer: a failure puts both back as they were.
+ const oldClock = keptClock ? await recordingClockSidecar.load(videoDir) : null;
+ if (keptClock) await recordingClockSidecar.write(videoDir, { ...keptClock, target: { file: name, bytes: resultBytes } });
+ try {
+ await rename(muxed, final);
+ await fsyncFileAndDir(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);
+ } catch (err) {
+ // The pointer still names the original: the re-encode goes back to
+ // its scratch name and the clock map to the original's.
+ await rename(final, muxed).catch(() => {});
+ if (keptClock && oldClock) await recordingClockSidecar.write(videoDir, oldClock).catch(() => {});
+ throw err;
+ }
+ return true;
+ });
+ if (!swappedNow) {
+ 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" };
+ }
+ swapped = true;
+ 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), whole file SSIM ${checks.wholeFile?.mean.toFixed(3)} ` +
+ `(lowest ${checks.wholeFile?.min.toFixed(3)} at ${checks.wholeFile?.worstAt.toFixed(1)} s), ${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.`,
+ );
+ await rm(scratch, { recursive: true, force: true });
+
+ // ---- 7 and 8: the recheck, then the drop — each its own step ----
+ const after = await afterSwap({ paths: opts.paths, videoDir, item: opts.item, settings: s, deps, log, tag, signal, markerToken });
+ return { status: "compacted", line: `compacted ${tag}`, pointer: (await loadSavedVideo(videoDir))!, ...after };
+ } catch (err) {
+ if (swapped) {
+ // AFTER THE SWAP NOTHING IS UNDONE, and nothing pretends it was: the
+ // re-encode is the active copy, the original is kept beside it.
+ const why = (err as Error).message;
+ log(
+ `compacted ${tag}: the swap is written (the active copy is the re-encode; the original ${pointer.file} is kept beside it). ` +
+ `After it, a step failed: ${why}. Nothing is dropped.`,
+ );
+ const p = await loadSavedVideo(videoDir);
+ return {
+ status: "compacted",
+ line: `compacted ${tag}`,
+ pointer: p ?? pointer,
+ dropped: false,
+ review: "drop-pending",
+ afterSwapError: why,
+ };
+ }
+ 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.
+ for (const f of ["compacted.mp4", "compacted.mkv"]) await rm(path.join(scratch, f), { 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 };
+ }
+}
+
+function sameProvenance(raw: Record<string, unknown>, pointer: SavedVideoPointer): boolean {
+ const now = parseSavedVideoPointer(raw);
+ return (
+ !!now &&
+ now.keepReason === pointer.keepReason &&
+ now.explicit === pointer.explicit &&
+ JSON.stringify(now.origin ?? null) === JSON.stringify(pointer.origin ?? null)
+ );
+}
+
+// The excerpt seconds (relative to the file's start) on the copy's frame grid,
+// a quarter frame early: a seek lands on the same picture in both files.
+function onGrid(t: number, fps: number): number {
+ const g = Math.round(t * fps) / fps;
+ return Number(Math.max(0, g - 0.25 / fps).toFixed(4));
+}
+
+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; clock: RecordingClock | null }> {
+ const { deps, tag, state, settings: s, log, signal } = o;
+ const checks: Partial<SavedVideoCompactedChecks> = { passed: false, audio: "unknown" };
+ const fail = (why: string): never => {
+ throw new VerifyFailure(why, checks);
+ };
+ let keep: RecordingClock | null = null;
+ const outFps = o.fps ?? o.probe.fps ?? 30;
+ 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, frames and gaps, from both files' packets.
+ const outProbe = await deps.probe(o.muxed);
+ if (!outProbe?.hasVideo) fail("the re-encode does not open as a video");
+ const op = outProbe!;
+ 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 / outFps;
+ const srcSeconds = state.sourceLastPts + state.sourceFrameStep - state.sourceFirstPts;
+ const outSeconds = n ? outScan.pts[n - 1] + outStep - outScan.pts[0] : 0;
+ const frameTol = 1 / outFps + 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)`);
+ }
+ // NO GAP THE SOURCE DOES NOT HAVE (a lost stretch at a chunk join).
+ const gap = maxGap(outScan.pts);
+ if (gap > Math.max(1.5 / outFps, state.sourceMaxGap + 1 / outFps)) {
+ fail(`the re-encode has a ${gap.toFixed(3)} s gap between frames (the source's largest is ${state.sourceMaxGap.toFixed(3)} s)`);
+ }
+ // THE PICTURE'S START AGAINST THE SOUND'S, in each file (a source whose
+ // first timestamp is not 0 — an offset mp4 or mkv, an mpegts — keeps it).
+ if (o.probe.audioStart !== null && op.audioStart !== null) {
+ const srcOff = o.probe.videoStart - o.probe.audioStart;
+ const outOff = op.videoStart - op.audioStart;
+ checks.avOffset = [round(srcOff, 4), round(outOff, 4)];
+ if (Math.abs(srcOff - outOff) > 0.5 / outFps + 1e-3) {
+ fail(`the re-encode's picture starts ${outOff.toFixed(3)} s from its sound, the source's ${srcOff.toFixed(3)} s`);
+ }
+ }
+ const relFirst = (pts0: number, p: SourceProbe) => pts0 - p.formatStart;
+ if (n && Math.abs(relFirst(outScan.pts[0], op) - relFirst(state.sourceFirstPts, o.probe)) > 0.5 / outFps + 1e-3) {
+ fail(`the re-encode's first frame is ${relFirst(outScan.pts[0], op).toFixed(3)} s into it, the source's ${relFirst(state.sourceFirstPts, o.probe).toFixed(3)} s`);
+ }
+ log(`${tag}: ${n}/${expected} frames, ${outSeconds.toFixed(3)} s against ${srcSeconds.toFixed(3)} s, largest gap ${gap.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.audioHash = b.data;
+ const sameTiming = sameAudioTiming(a, b);
+ if (a.packets !== b.packets || a.data !== b.data || !sameTiming) {
+ checks.audio = "different";
+ fail(
+ `the audio is not the source's packet for packet (${a.packets} → ${b.packets} packets` +
+ `${a.data !== b.data ? ", different bytes" : ""}${!sameTiming ? ", different timing" : ""})`,
+ );
+ }
+ checks.audio = "identical";
+ log(`${tag}: audio identical (${b.packets} packets).`);
+
+ // Every other stream and the chapters.
+ const srcInv = await deps.inventory(o.src, o.probe.mainVideoIndex);
+ const outInv = await deps.inventory(o.muxed, op.mainVideoIndex);
+ checks.streams = { source: srcInv, result: outInv };
+ if (JSON.stringify(srcInv) !== JSON.stringify(outInv)) {
+ fail(`the re-encode does not carry every stream of the source (source: ${srcInv.join(", ") || "none"}; copy: ${outInv.join(", ") || "none"})`);
+ }
+
+ // THE WHOLE FILE, compared EVERY FRAME, whole and tile by tile.
+ log(`${tag}: comparing the whole file, every frame, at ${WHOLE_FILE_WIDTH} px in a ${WHOLE_FILE_GRID}×${WHOLE_FILE_GRID} grid…`);
+ const cmp = await deps.wholeFile({
+ compacted: o.muxed,
+ source: o.src,
+ scratchDir: o.scratch,
+ fps: o.fps,
+ sourceFps: o.probe.fps,
+ sourceWidth: o.probe.width,
+ sourceHeight: o.probe.height,
+ tileFloor: s.wholeFileTileMin,
+ signal,
+ });
+ const v = judgeWholeFile(cmp, {
+ minFrame: s.wholeFileSsimMin,
+ meanFloor: s.wholeFileSsimMean,
+ sigmaK: s.wholeFileSigmaK,
+ sigmaMinMargin: s.wholeFileSigmaMargin,
+ tileRunFrames: s.wholeFileTileRunFrames,
+ expectedFrames: n,
+ fps: outFps,
+ });
+ checks.wholeFile = {
+ fps: outFps,
+ width: WHOLE_FILE_WIDTH,
+ frames: cmp.frames.length,
+ mean: round(v.mean, 4),
+ min: round(v.min, 4),
+ worstAt: round(v.minAt / outFps, 3),
+ minFloor: s.wholeFileSsimMin,
+ meanFloor: s.wholeFileSsimMean,
+ maxGapSeconds: round(gap, 4),
+ sd: round(v.sd, 5),
+ relativeFloor: round(v.relativeFloor, 4),
+ grid: WHOLE_FILE_GRID,
+ tileFloor: s.wholeFileTileMin,
+ tileRunFrames: s.wholeFileTileRunFrames,
+ ...(v.worstTile
+ ? {
+ worstTile: {
+ col: v.worstTile.col,
+ row: v.worstTile.row,
+ min: round(v.worstTile.min, 4),
+ at: round(v.worstTile.minAt / outFps, 3),
+ longestBelow: v.worstTile.longestBelow,
+ },
+ }
+ : {}),
+ };
+ if (!v.ok) fail(`the whole-file comparison: ${v.why}`);
+ log(
+ `${tag}: whole file SSIM ${v.mean.toFixed(4)} mean over ${cmp.frames.length} frames, lowest ${v.min.toFixed(4)} at ${(v.minAt / outFps).toFixed(2)} s; ` +
+ `worst tile ${v.worstTile ? `${v.worstTile.col},${v.worstTile.row} at ${v.worstTile.min.toFixed(3)} (${v.worstTile.longestBelow} frame(s) below ${s.wholeFileTileMin})` : "none"}.`,
+ );
+
+ // Quality on excerpts: spread through the file, ACROSS EVERY CHUNK JOIN and
+ // inside every chunk (the count grows with the chunks).
+ const metric: "vmaf" | "ssim" = (await deps.hasVmaf().catch(() => false)) ? "vmaf" : "ssim";
+ const relStart = state.sourceFirstPts - o.probe.formatStart;
+ const lastAt = Math.max(0, srcSeconds - EXCERPT_SECONDS - 0.25);
+ const times = new Set<number>(sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps).map((t) => onGrid(t + relStart, outFps)));
+ for (const c of state.chunks) {
+ const from = c.from - state.sourceFirstPts;
+ const to = c.last ? srcSeconds : c.to - state.sourceFirstPts;
+ if (c.index > 0) times.add(onGrid(Math.min(lastAt, Math.max(0, from - EXCERPT_SECONDS / 2)) + relStart, outFps));
+ times.add(onGrid(Math.min(lastAt, Math.max(0, (from + to) / 2 - EXCERPT_SECONDS / 2)) + relStart, outFps));
+ }
+ const scores: number[] = [];
+ for (const at of [...times].sort((x, y) => x - y)) {
+ 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, sourceFps: o.probe.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 (every join and every chunk), worst ${min.toFixed(2)}.`);
+
+ // Real windows cut from each, compared frame by frame.
+ const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps).map((t) => onGrid(t + relStart, outFps));
+ checks.cuts = [];
+ checks.cutSsimMin = CUT_SSIM_MIN;
+ for (const at of cutTimes) {
+ const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, seconds: CUT_SECONDS, fps: o.fps, sourceFps: o.probe.fps, scratchDir: o.scratch, signal });
+ checks.cuts.push({ at, ssim: round(c.ssim, 4) });
+ if (c.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 ${c.ssim.toFixed(3)} < ${CUT_SSIM_MIN})`);
+ if (cutIsOffset(c)) {
+ fail(
+ `a window cut at ${at.toFixed(1)} s from the re-encode lands on other frames than the original's ` +
+ `(SSIM ${c.ssim.toFixed(4)} as cut, ${Math.max(c.earlier, c.later).toFixed(4)} a frame ${c.later > c.earlier ? "later" : "earlier"})`,
+ );
+ }
+ }
+ log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter land on the original's frames.`);
+
+ // 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);
+ const 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 moved = okAnchors.find((t: number) => Math.abs(clockOffsetAt(old, t).offset - clockOffsetAt(fresh, t).offset) > tol);
+ if (fresh.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(fresh, moved).offset.toFixed(3)} s, against the original ${clockOffsetAt(old, moved).offset.toFixed(3)} s`
+ : `the recording clock's map is ${fresh.ok ? "ok" : "NOT ok"} against the re-encode and ${old.ok ? "ok" : "NOT ok"} against the original`,
+ );
+ }
+ checks.clock = "kept";
+ // THE SAME MAP, retargeted (written in the swap's lock): its id kept, so
+ // every window cut through it stays on this clock.
+ keep = {
+ ...old,
+ retargeted: { at: deps.now().toISOString(), from: old.target, measured: fresh.id, by: COMPACTION_TOOL },
+ } as RecordingClock;
+ 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, clock: keep };
+}
+
+// --- after the swap ------------------------------------------------------------
+
+// THE SECOND CHECK (a step of its own): the pointer read back from disk, and
+// the file it names read back too (lib readBackCompactedCopy: fsynced, out of
+// the page cache, size, sha256, container, length). Recorded as
+// `compacted.recheck`.
+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 pointer = await loadSavedVideo(opts.videoDir);
+ const res = pointer
+ ? await readBackCompactedCopy(pointer, {
+ ...(opts.deps?.sha256 ? { hasher: (f: string) => opts.deps!.sha256!(f, opts.signal) } : {}),
+ })
+ : ({ ok: false, why: "no pointer" } as const);
+ if (opts.record !== false && pointer?.compacted) {
+ const pointerFile = savedVideoPointerPath(opts.videoDir);
+ await withPointerLock(opts.videoDir, 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: (opts.deps?.now?.() ?? new Date()).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 (reviewIsCurrent(pointer, original)) return "reviewed";
+ if (!onPlatform) return "awaiting-review";
+ return dropOriginal === "keep" ? "kept" : "drop-pending";
+}
+
+async function afterSwap(o: {
+ paths: Paths;
+ videoDir: string;
+ item: CompactItem;
+ settings: SavedVideoCompactionSettings;
+ deps: Required<CompactDeps>;
+ log: (s: string) => void;
+ tag: string;
+ signal?: AbortSignal;
+ markerToken: string;
+}): 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 presence = await o.deps.presence(o.videoDir);
+ const state = () => reviewStateOf(pointer, presence.onPlatform, o.settings.dropOriginal) ?? "drop-pending";
+ if (!recheck.ok) {
+ log(`${tag}: the re-check after the swap FAILED (${recheck.why}): the original ${original?.file ?? "?"} is kept.`);
+ return { dropped: false, review: state() };
+ }
+ 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: state() };
+ }
+ if (!pointer.compacted?.checks.wholeFile) {
+ log(`${tag}: the verification has no whole-file comparison: "after-verify" does not drop the original ${original.file}.`);
+ return { dropped: false, review: state() };
+ }
+ if (!presence.onPlatform) {
+ log(
+ `${tag}: not known to be on its platform (${presence.why}): the original ${original.file} ` +
+ "is NOT dropped — it waits for a person's review (get compaction-review).",
+ );
+ return { dropped: false, review: state() };
+ }
+ try {
+ // EXACTLY THE ORIGINAL OF THIS COMPACTED COPY, checked again under the
+ // pointer's lock (kind, sha256, file): a persist landing between this
+ // read and that lock re-labels it, and then nothing is dropped. This step
+ // never passes the former-original confirm (a test scans the callers).
+ const r = await dropSavedAlternate(o.videoDir, original.file, {
+ confirmOriginal: true,
+ expect: { keptAs: "original", sha256: pointer.compacted!.source.sha256, file: original.file },
+ markerToken: o.markerToken,
+ by: "compact-saved-videos (after-verify)",
+ presence,
+ busy: () => o.deps.busy(o.item.slug, o.item.id),
+ readBack: { hasher: (f) => o.deps.sha256(f, o.signal) },
+ 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: state() };
+ }
+}
+
+// --- the job's body ------------------------------------------------------------
+
+export type CompactSavedVideosResult = {
+ compacted: { slug: string; id: string; dropped: boolean; review: CompactionReviewState; afterSwapError?: string }[];
+ 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; belowThreshold?: boolean },
+): Promise<CompactSavedVideosResult> {
+ const result: CompactSavedVideosResult = { compacted: [], skipped: [], failed: [] };
+ // Stale markers first: none of them may block this run (or any other).
+ await sweepCompactingMarkers(opts.paths, opts.onLog).catch(() => {});
+ 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, ...(r.afterSwapError ? { afterSwapError: r.afterSwapError } : {}) });
+ } 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;
+ presence: string;
+ original?: SavedVideoAlternate;
+ compactedAt: string;
+ bytes: number;
+ sourceBytes: number;
+ checksPassed: boolean;
+ recheck?: SavedVideoCompacted["recheck"];
+ // What a reviewer watches: the two files, and a command that plays both.
+ watch: { compacted: string; original?: string; command: string };
+ // An interrupted drop: the original's file still on disk.
+ leftover?: string;
+};
+
+// Every compacted video, with what its original is waiting for.
+export async function listCompactionReview(opts: {
+ paths: Paths;
+ settings: Pick<SavedVideoCompactionSettings, "dropOriginal" | "availabilityMaxAgeDays">;
+ channelSlug?: string;
+ notAnswering?: string[];
+ deps?: Pick<CompactDeps, "presence">;
+}): Promise<CompactionReviewRow[]> {
+ const presenceOf =
+ opts.deps?.presence ??
+ ((d: string) =>
+ platformPresence(d, { maxAgeDays: opts.settings.availabilityMaxAgeDays }).catch(() => ({
+ onPlatform: false,
+ availability: null,
+ why: "its availability could not be read",
+ })));
+ 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 presence = await presenceOf(e.videoDir);
+ const original = compactedOriginalOf(e.pointer) ?? undefined;
+ const compactedPath = savedVideoPath(e.pointer);
+ const originalPath = original ? path.join(e.pointer.dir, original.file) : undefined;
+ const d = c.originalDropped;
+ const leftover =
+ d && d.fileRemoved === false && (await stat(path.join(e.pointer.dir, d.file)).then(() => true, () => false))
+ ? path.join(e.pointer.dir, d.file)
+ : undefined;
+ rows.push({
+ slug: e.slug,
+ id: e.videoId,
+ state: reviewStateOf(e.pointer, presence.onPlatform, opts.settings.dropOriginal)!,
+ line: compactedLine(e.pointer) ?? "",
+ availability: presence.availability,
+ onPlatform: presence.onPlatform,
+ presence: presence.why,
+ ...(original ? { original } : {}),
+ compactedAt: c.at,
+ bytes: e.pointer.bytes,
+ sourceBytes: c.source.bytes,
+ checksPassed: c.checks.passed,
+ ...(c.recheck ? { recheck: c.recheck } : {}),
+ watch: {
+ compacted: compactedPath,
+ ...(originalPath ? { original: originalPath } : {}),
+ command: `smplayer ${JSON.stringify(compactedPath)}${originalPath ? ` ${JSON.stringify(originalPath)}` : ""}`,
+ },
+ ...(leftover ? { leftover } : {}),
+ });
+ }
+ return rows;
+}
+
+// --- what a rollback must know, and the markers ------------------------------------
+
+// EVERY POINTER THAT KEEPS AN ORIGINAL (`keptAs: "original"`) OR A FORMER ONE
+// (`"former-original"`), or has a drop in flight (`pendingDrops`). An editor
+// built from before this release does not know those labels and would treat
+// such a copy as an ordinary droppable alternate: while this list is not
+// empty, do not roll the editor back past this release (OPERATING.md).
+export type KeptOriginalRow = {
+ slug: string;
+ id: string;
+ active: string;
+ compacted: boolean;
+ kept: { file: string; keptAs: "original" | "former-original"; sha256?: string; bytes: number }[];
+ pendingDrops: { file: string; keptAs?: string; at: string }[];
+};
+
+export async function listKeptOriginals(opts: { paths: Paths; channelSlug?: string; notAnswering?: string[] }): Promise<KeptOriginalRow[]> {
+ const entries = await listSavedVideos({
+ paths: opts.paths,
+ ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}),
+ ...(opts.notAnswering ? { notAnswering: opts.notAnswering } : {}),
+ });
+ const rows: KeptOriginalRow[] = [];
+ for (const e of entries) {
+ const kept = (e.pointer.alternates ?? [])
+ .filter((a) => a.keptAs === "original" || a.keptAs === "former-original")
+ .map((a) => ({ file: a.file, keptAs: a.keptAs as "original" | "former-original", ...(a.sha256 ? { sha256: a.sha256 } : {}), bytes: a.bytes }));
+ const pending = (e.pointer.pendingDrops ?? []).map((d) => ({ file: d.file, ...(d.keptAs ? { keptAs: d.keptAs } : {}), at: d.at }));
+ if (!kept.length && !pending.length) continue;
+ rows.push({ slug: e.slug, id: e.videoId, active: e.pointer.file, compacted: !!e.pointer.compacted, kept, pendingDrops: pending });
+ }
+ return rows;
+}
+
+export type CompactionMarkerRow = { slug: string; id: string; dir: string; live: boolean; why: string; marker: unknown };
+
+// Every `.compacting.json` in the store, live or stale, and why.
+export async function listCompactionMarkers(paths: Paths): Promise<CompactionMarkerRow[]> {
+ const { markerLiveness } = await import("../lib/compactingMarker-server");
+ const rows: CompactionMarkerRow[] = [];
+ for (const e of await listSavedVideos({ paths })) {
+ const m = await readCompactingMarker(e.pointer.dir).catch(() => null);
+ if (!m) continue;
+ const l = await markerLiveness(m);
+ rows.push({ slug: e.slug, id: e.videoId, dir: e.pointer.dir, live: l.live, why: l.why, marker: m });
+ }
+ return rows;
+}
+
+// Clear one video's marker — refused while it is live (cancel the job instead).
+export async function clearCompactionMarker(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string }> {
+ const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id));
+ if (!p) return { cleared: false, why: "no saved video" };
+ return clearCompactingMarker(p.dir);
+}
diff --git a/common/controller/preparePlayable.ts b/common/controller/preparePlayable.ts
@@ -264,7 +264,7 @@ export async function preparePlayable(opts: PreparePlayableOptions): Promise<Pre
if (!sourceSha256) {
onLog(`${id}: hashing ${pointer.file} (${formatBytes(srcBytes)})`);
sourceSha256 = await sha256File(src, opts.signal);
- if (!opts.dryRun) await updateSavedVideoChecksum(videoDir, sourceSha256);
+ if (!opts.dryRun) await updateSavedVideoChecksum(videoDir, sourceSha256, pointer.file);
}
const prior = manifest.entries[id];
if (prior && prior.sourceSha256 === sourceSha256) {
@@ -335,11 +335,18 @@ export async function preparePlayable(opts: PreparePlayableOptions): Promise<Pre
vcodec: probed?.vcodec ?? "",
acodec: probed?.acodec ?? null,
preparedAt: now().toISOString(),
+ // A copy of a re-encode says so, and of which original.
+ ...(pointer.compacted?.source.sha256
+ ? { compactedFrom: pointer.compacted.source.sha256, note: "re-encoded copy" as const }
+ : {}),
};
manifest.entries[id] = entry;
await writeJsonAtomic(playableManifestPath(root, opts.slug), manifest);
result.prepared.push(id);
- onLog(`${id}: ${name} ${formatBytes(bytes)}, infohash ${made.infoHash}, ${made.pieceLength / 1024} KiB pieces`);
+ onLog(
+ `${id}: ${name} ${formatBytes(bytes)}, infohash ${made.infoHash}, ${made.pieceLength / 1024} KiB pieces` +
+ (entry.compactedFrom ? `; a re-encoded copy (of the original sha256 ${entry.compactedFrom.slice(0, 12)}…)` : ""),
+ );
} catch (err) {
if (opts.signal?.aborted) {
result.stopped = "cancelled";
diff --git a/common/controller/pruneSavedVideos.test.ts b/common/controller/pruneSavedVideos.test.ts
@@ -105,3 +105,22 @@ test("never evicts override or pinned containers, even out of window", async ()
}
});
});
+
+// Review F5: a refusal for one video (being compacted) never stops the prune.
+test("a video the prune may not drop is logged and kept; the prune goes on", async () => {
+ await withPaths(async (paths) => {
+ await writeConfig(paths, "ch", 1);
+ await seedSaved(paths, "ch", "newest", "20240301", "keep-latest");
+ await seedSaved(paths, "ch", "a", "20240101", "keep-latest");
+ await seedSaved(paths, "ch", "b", "20240102", "keep-latest");
+ // a is being compacted: a live marker beside its stored copy.
+ const { writeCompactingMarker } = await import("../lib/compactingMarker-server");
+ await writeCompactingMarker(path.join(paths.savedVideosDir, "ch", "a"));
+ const lines: string[] = [];
+ const res = await pruneSavedVideos({ channelSlug: "ch", paths, onLog: (l) => lines.push(l) });
+ assert.equal(res.pruned, 1);
+ assert.notEqual(await loadSavedVideo(path.join(paths.channelsDir, "ch", "data", "a")), null);
+ assert.equal(await loadSavedVideo(path.join(paths.channelsDir, "ch", "data", "b")), null);
+ assert.ok(lines.some((l) => /Kept saved video a: .*being compacted/.test(l)), lines.join("\n"));
+ });
+});
diff --git a/common/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts
@@ -69,10 +69,12 @@ export async function pruneSavedVideos({
if (pointer.alternates?.length) {
const n = pointer.alternates.length;
const proxies = pointer.alternates.filter((a) => a.keptAs === "proxy").length;
- const flagged = n - proxies;
- const what = proxies
+ const originals = pointer.alternates.filter((a) => a.keptAs === "original").length;
+ const flagged = n - proxies - originals;
+ const what = proxies || originals
? ` (${[
- `${proxies} kept on purpose as the lower-quality proxy`,
+ ...(originals ? ["the original a compacted copy was re-encoded from"] : []),
+ ...(proxies ? [`${proxies} kept on purpose as the lower-quality proxy`] : []),
...(flagged ? [`${flagged} flagged for a check`] : []),
].join(" and ")})`
: " flagged for a check";
@@ -82,7 +84,15 @@ export async function pruneSavedVideos({
);
continue;
}
- const bytes = await dropSavedVideo(videoDir);
+ // A REFUSAL FOR ONE VIDEO NEVER STOPS THE PRUNE (review F5): a video
+ // being compacted, or one that keeps an original, is logged and kept.
+ let bytes: number;
+ try {
+ bytes = await dropSavedVideo(videoDir);
+ } catch (err) {
+ log(`Kept saved video ${id}: ${(err as Error).message}`);
+ continue;
+ }
bytesFreed += bytes;
pruned++;
log(
diff --git a/common/controller/videoBusy.ts b/common/controller/videoBusy.ts
@@ -0,0 +1,58 @@
+// IS ANYTHING ABOUT TO WRITE THIS VIDEO'S SAVED COPY? (compaction's drop
+// guard, review H4.) A download, a persist, an attach or an import of the
+// same video that is queued or running may land a container on the pointer
+// while an original is being dropped — the drop then refuses, naming it.
+//
+// A job counts when it is of a kind that can persist a container, for this
+// channel, and either names this video (`videoId`, or `spec.params.ids`) or
+// names no video at all (a channel-wide run: it may reach this one). The
+// download lane's in-flight units (they make no job record) count by their
+// video id. The compaction job itself never counts.
+
+import { getRegistry } from "../jobs/registry";
+import { getAutoRunnerStatus } from "./autoRunner";
+
+export const VIDEO_WRITING_KINDS: ReadonlySet<string> = new Set([
+ "auto-download-unit",
+ "download-from-playlist",
+ "download-missing",
+ "download-missing-subs",
+ "download-one-pipeline",
+ "import-one",
+ "import-archive-org",
+ "redownload-archive",
+ "redownload-incomplete-bucket",
+ "retry-bucket",
+ "sync",
+ "persist-kept",
+ "persist-videos",
+ "fetch-windows",
+ "attach-media",
+ "import-media",
+ "record-live",
+ "import-local-media",
+]);
+
+export function videoPersistBusyReason(slug: string, id: string): string | null {
+ const jobs = getRegistry()
+ .list()
+ .filter((j) => {
+ if (!VIDEO_WRITING_KINDS.has(j.kind)) return false;
+ if (j.status !== "queued" && j.status !== "running") return false;
+ if (j.channelSlug && j.channelSlug !== slug) return false;
+ if (j.videoId) return j.videoId === id;
+ const ids = (j.spec?.params as { ids?: unknown } | undefined)?.ids;
+ if (Array.isArray(ids)) return ids.includes(id);
+ return j.channelSlug === slug;
+ });
+ if (jobs.length) {
+ return `a ${jobs[0].kind} job (${jobs[0].status}, ${jobs[0].id}) may write this video's saved copy — wait for it to end`;
+ }
+ try {
+ const unit = getAutoRunnerStatus("download").inFlight.find((u) => u.channelSlug === slug && u.videoId === id);
+ if (unit) return "the download lane is downloading this video now — wait for it to end";
+ } catch {
+ // No runner in this process (a CLI): nothing in flight here.
+ }
+ return null;
+}
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -412,7 +412,7 @@ test("resumeOnBoot: exactly the kinds that continue on a re-run, every one repla
]);
for (const k of resumeOnBootKindIds()) assert.equal(getJobKind(k)?.replayable, true, `${k} is replayable`);
// Never a move, a delete or a one-shot.
- for (const k of ["relocate-channel-media", "repoint-storage-location", "purge-superseded-auto-subs", "evict-clips", "sync", "fetch-chat", "record-live"]) {
+ for (const k of ["relocate-channel-media", "repoint-storage-location", "purge-superseded-auto-subs", "evict-clips", "sync", "fetch-chat", "record-live", "compact-saved-videos"]) {
assert.equal(getJobKind(k)?.resumeOnBoot, undefined, `${k} does not resume`);
}
});
@@ -433,3 +433,18 @@ test("x-run: a network, drainable, replayable ingest kind on X's queue that a re
// A restart never re-queues one left queued (jobs/bootQueuedJobs.ts).
assert.equal(meta.startedByPerson, true);
});
+
+// COMPACT SAVED VIDEOS (controller/compactSavedVideos.ts): reads and writes
+// the store, stops between chunks, rewrites the pointer a playable build reads
+// — and may delete an original, so a restart never re-runs it by itself.
+test("compact-saved-videos is a drainable, replayable media ingest kind the boot pass leaves alone", () => {
+ const meta = getJobKind("compact-saved-videos");
+ assert.ok(meta, "registered");
+ assert.equal(jobKindLabel("compact-saved-videos"), "Compact saved videos");
+ assert.equal(isDrainableKind("compact-saved-videos"), true);
+ assert.equal(meta.replayable, true);
+ assert.equal(meta.resumeOnBoot, undefined);
+ assert.equal(kindNeedsMedia("compact-saved-videos"), true);
+ assert.equal(isIngestKind("compact-saved-videos"), true);
+ assert.equal(kindIsNetwork("compact-saved-videos"), false);
+});
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1571,6 +1571,26 @@ 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 (Retry)
+ // — resumes at the first chunk not encoded (`.compact-scratch/state.json`);
+ // a video already compacted is skipped. NOT resumed by the boot pass: under
+ // `dropOriginal: "after-verify"` it deletes originals, and whether a
+ // destructive kind runs again is a person's call, not a boot's. 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,
+ },
};
export function getJobKind(kind: string): JobKindMeta | undefined {
@@ -1645,6 +1665,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/availability-server.ts b/common/lib/availability-server.ts
@@ -74,6 +74,7 @@ export async function recordAvailability(
if (updateTopLevel) {
record = {
checkedAt: obs.observedAt,
+ checkedBy: obs.source,
availability: obs.availability,
history,
};
@@ -184,3 +185,43 @@ async function loadDownloadOutcomeAvailability(
finishedAt: typeof outcome.finishedAt === "string" ? outcome.finishedAt : null,
};
}
+
+// STILL ON ITS PLATFORM, FRESH AND FIRST-HAND (compaction's gone rule,
+// controller/compactSavedVideos.ts): an availability record written by a REAL
+// PROBE (`checkedBy: "check"`) saying public or unlisted, no older than
+// `maxAgeDays`, and no download attempt since that found it gone. Anything
+// else — a backfilled or legacy record, an older one, an error, members-only,
+// a login wall, no record — is NOT on its platform: `why` says which, and what
+// would refresh it.
+export async function platformPresence(
+ videoDir: string,
+ opts: { maxAgeDays: number; now?: Date },
+): Promise<{ onPlatform: boolean; availability: Availability | null; why: string }> {
+ const now = opts.now ?? new Date();
+ const record = await loadAvailability(videoDir);
+ const effective = await resolveEffectiveAvailability(videoDir).catch(() => null);
+ const refresh = "check its availability again (the channel page's Diagnostics → Check availability)";
+ if (!record) return { onPlatform: false, availability: effective, why: `no availability record — ${refresh}` };
+ if (record.checkedBy !== "check") {
+ return {
+ onPlatform: false,
+ availability: record.availability,
+ why: `its availability (${record.availability}) was not read by a check of the platform${record.checkedBy ? ` (${record.checkedBy})` : ""} — ${refresh}`,
+ };
+ }
+ const age = (now.getTime() - Date.parse(record.checkedAt)) / 86_400_000;
+ if (!Number.isFinite(age) || age > opts.maxAgeDays) {
+ return {
+ onPlatform: false,
+ availability: record.availability,
+ why: `its last check (${record.checkedAt.slice(0, 10)}) is older than ${opts.maxAgeDays} day(s) — ${refresh}`,
+ };
+ }
+ if (effective !== record.availability) {
+ return { onPlatform: false, availability: effective, why: `a download since the check found it ${effective ?? "unknown"}` };
+ }
+ if (record.availability !== "public" && record.availability !== "unlisted") {
+ return { onPlatform: false, availability: record.availability, why: `its check says ${record.availability}` };
+ }
+ return { onPlatform: true, availability: record.availability, why: `checked ${record.availability} on ${record.checkedAt.slice(0, 10)}` };
+}
diff --git a/common/lib/availability.ts b/common/lib/availability.ts
@@ -146,6 +146,10 @@ export type AvailabilityHistoryEntry = {
export type AvailabilityRecord = {
checkedAt: string;
+ // WHO WROTE `checkedAt`/`availability`: "check" (a real probe of the
+ // platform) or "backfill" (an assumption from a listing). Absent on every
+ // record written before it — which says nothing about which it was.
+ checkedBy?: AvailabilityHistorySource;
availability: Availability;
error?: string;
webpageUrl?: string;
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.test.ts b/common/lib/channelConfigSchema.test.ts
@@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it",
assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]);
- assert.equal(CHANNEL_CONFIG_KEYS.length, 47); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 48); // 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
assert.equal(sameKeys, true);
assert.equal(fits, true);
for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k);
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/clipWindow.ts b/common/lib/clipWindow.ts
@@ -286,6 +286,11 @@ export type ClipProvenance = {
sourceHost?: string;
// "clip-window": the tiered window's file name this one was cut from.
derivedFrom?: string;
+ // "saved-video": the saved copy it was cut from was a RE-ENCODE (a compacted
+ // copy, controller/compactSavedVideos.ts) — its file and the original's
+ // sha256 — so the window says it is a later generation. Absent on a cut from
+ // an original.
+ fromReencode?: { file: string; originalSha256: string };
// How many times the player's page was opened for this window's cut (release
// 32 R9, ytdlp/storedUrlPageOpen.ts): a stored-URL cut opens it before the
// first cut of each video in a run. Absent when none was.
@@ -389,6 +394,10 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if (sourceHost) out.sourceHost = sourceHost;
const derivedFrom = str(r.derivedFrom);
if (derivedFrom) out.derivedFrom = derivedFrom;
+ const re = r.fromReencode as Record<string, unknown> | undefined;
+ if (re && typeof re === "object" && typeof re.file === "string" && typeof re.originalSha256 === "string") {
+ out.fromReencode = { file: re.file, originalSha256: re.originalSha256 };
+ }
const pageOpens = num(r.pageOpens);
if (pageOpens !== undefined && pageOpens > 0) out.pageOpens = pageOpens;
const copy = coerceClipCopy(r.copy);
diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts
@@ -0,0 +1,921 @@
+// 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, writeFile } 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;
+ // The first audio stream's start (seconds), or null with no audio.
+ audioStart: number | null;
+ // The container's own start (seconds): what a plain -ss counts from.
+ formatStart: number;
+ audioStreams: number;
+ bytes: number;
+ // The stream index of the video stream compaction replaces.
+ mainVideoIndex: number;
+ // What the container must keep besides that stream: "mp4" when every other
+ // stream is one an mp4 holds when copied (audio, mov_text, an attached
+ // picture), else "matroska".
+ container: "mp4" | "matroska";
+};
+
+// 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));
+ }
+ const others = streams.filter((x) => x !== v);
+ const mp4Ok = others.every(
+ (x) =>
+ x.codec_type === "audio" ||
+ (x.codec_type === "subtitle" && x.codec_name === "mov_text") ||
+ (x.codec_type === "video" && (x.disposition as { attached_pic?: number } | undefined)?.attached_pic === 1),
+ );
+ const firstAudio = audios[0];
+ return {
+ mainVideoIndex: typeof v?.index === "number" ? v.index : 0,
+ container: mp4Ok ? "mp4" : "matroska",
+ audioStart: firstAudio ? (numOr(firstAudio.start_time) ?? 0) : null,
+ formatStart: numOr(doc.format?.start_time) ?? 0,
+ 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;
+ // The last chunk runs to the end of the source.
+ last?: boolean;
+};
+
+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, sourceFps?: 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];
+ // With a frame-rate change, a chunk starts only on a keyframe that is ON THE
+ // COPY'S FRAME GRID (its time from the first frame a whole number of output
+ // frames): elsewhere each chunk's rounded frame count would move the copy's
+ // picture against its sound by part of a frame, chunk after chunk.
+ const onGrid = (k: number) => {
+ if (!outFps) return true;
+ const x = (k - starts[0]) * outFps;
+ return Math.abs(x - Math.round(x)) < 0.02;
+ };
+ for (const k of keyframes) {
+ if (k - starts[starts.length - 1] >= chunkSeconds - EDGE && onGrid(k)) 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
+ ? sourceFrames
+ : wholeRatio(sourceFps, outFps)
+ ? Math.ceil(sourceFrames / wholeRatio(sourceFps, outFps)!)
+ : framesAtFps(pts, from, to, outFps, i + 1 === starts.length),
+ ...(i + 1 === starts.length ? { last: true } : {}),
+ });
+ }
+ 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;
+ // The source container's start (seconds): a plain -ss counts from it.
+ formatStart?: number;
+};
+
+// One chunk: an input seek to the chunk's keyframe — RELATIVE TO THE FILE'S
+// START (the scan's pts are the file's own; a plain -ss counts from the
+// container's start time, so an offset mp4 or mkv, or an mpegts starting at
+// 1.4 s, would be cut that much late; `-seek_timestamp 1` would mend that for
+// mp4 and mkv but not for mpegts, measured) — the video only, ended by TIME, not
+// by a frame count: what the encoder actually wrote is counted afterwards, so
+// a short or long chunk shows. Into an mp4 with a 90 kHz track clock (exact for
+// 24, 25, 30, 50, 60 and the NTSC rates), which the concat demuxer joins
+// without rounding a frame's time to the millisecond.
+export const CHUNK_EXT = ".mp4";
+
+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));
+ // The input read up to a quarter source frame short of the next chunk's
+ // keyframe (an input -to: the decoder, and the fps filter's last frame, are
+ // flushed at it); the last chunk reads to the end.
+ const start = s.formatStart ?? 0;
+ const to = chunk.last ? null : chunk.to - start - 0.25 / s.sourceFps;
+ return [
+ "-nostdin", "-hide_banner", "-loglevel", "error", "-y",
+ "-ss", Math.max(0, chunk.from - start - 0.001).toFixed(6),
+ ...(to !== null ? ["-to", to.toFixed(6)] : []),
+ "-i", src,
+ "-map", "0:v:0", "-an", "-sn", "-dn",
+ // A whole ratio: every m-th frame, RE-TIMED on the copy's own grid from
+ // the chunk's first frame (n / fps) and written at that rate, so each
+ // chunk lasts exactly its frames — passed through, the last frame kept the
+ // source's 1/60 s and every later chunk landed a source frame early.
+ ...(s.fps
+ ? wholeRatio(s.sourceFps, s.fps)
+ ? ["-vf", `${decimateTo(s.sourceFps, s.fps)}setpts=N/${s.fps}/TB`, "-r", String(s.fps)]
+ : ["-vf", decimateTo(s.sourceFps, s.fps).replace(/,$/, "")]
+ : []),
+ "-c:v", "libsvtav1", "-preset", String(s.preset), "-crf", String(s.crf),
+ "-g", String(gop), "-pix_fmt", s.pixFmt,
+ "-video_track_timescale", "90000",
+ "-f", "mp4", out,
+ ];
+}
+
+// The chunks joined (concat demuxer, `-c copy`), the source's video start kept,
+// and EVERY OTHER STREAM OF THE SOURCE COPIED bit for bit — every audio track
+// (a later transcription hears the same samples, at the same seconds),
+// subtitles, data, attachments — and its chapters and metadata. An mp4 when
+// the source's other streams fit one, else Matroska (SourceProbe.container).
+export function muxArgs(
+ listFile: string,
+ src: string,
+ videoStart: number,
+ out: string,
+ opts: { mainVideoIndex?: number; container?: "mp4" | "matroska" } = {},
+): string[] {
+ const container = opts.container ?? "mp4";
+ 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", "-map", `-1:${opts.mainVideoIndex ?? 0}`,
+ "-c", "copy",
+ "-map_metadata", "1",
+ "-map_chapters", "1",
+ ...(container === "mp4" ? ["-movflags", "+faststart", "-f", "mp4"] : ["-f", "matroska"]),
+ out,
+ ];
+}
+
+// EVERY STREAM BUT ONE VIDEO, AND THE CHAPTERS, as words to compare: what a
+// copy must hold of its source besides the picture it replaces.
+export async function streamInventory(ffprobeBin: string, file: string, skipIndex: number): Promise<string[]> {
+ const r = await execa(ffprobeBin, ["-v", "error", "-show_streams", "-show_chapters", "-of", "json", file], { reject: false });
+ if (r.exitCode !== 0) throw new Error(`ffprobe could not read the streams of ${path.basename(file)}`);
+ const doc = JSON.parse(String(r.stdout)) as {
+ streams?: { index?: number; codec_type?: string; codec_name?: string; channels?: number; disposition?: { attached_pic?: number } }[];
+ chapters?: unknown[];
+ };
+ const out = (doc.streams ?? [])
+ .filter((x) => x.index !== skipIndex)
+ .map((x) =>
+ [x.codec_type ?? "?", x.codec_name ?? "?", ...(x.channels ? [`${x.channels}ch`] : []), ...(x.disposition?.attached_pic ? ["attached"] : [])].join(":"),
+ );
+ if (doc.chapters?.length) out.push(`chapters:${doc.chapters.length}`);
+ return out.sort();
+}
+
+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;
+ // Every packet's time from the first, in seconds — compared with a tolerance
+ // of a container's rounding (Matroska keeps milliseconds).
+ times?: Float64Array;
+};
+
+export const AUDIO_TIMING_TOLERANCE_S = 0.002;
+
+// Same audio timing: the per-packet times within the tolerance (or, without
+// them, the timing hashes equal).
+export function sameAudioTiming(a: AudioHash, b: AudioHash): boolean {
+ if (!a.times || !b.times) return a.timing === b.timing;
+ if (a.times.length !== b.times.length) return false;
+ for (let i = 0; i < a.times.length; i += 1) if (Math.abs(a.times[i] - b.times[i]) > AUDIO_TIMING_TOLERANCE_S) return false;
+ return true;
+}
+
+// The audio packets of every audio stream, demuxed and copied (`-c copy`) into
+// framemd5: what a copied track must reproduce exactly.
+// AAC carried in ADTS (an mpegts, a raw .aac) loses its ADTS headers when
+// copied into an mp4 (aac_adtstoasc, which ffmpeg inserts): the same samples
+// in other packet bytes. Both sides are hashed through that filter, which
+// passes a packet with no ADTS header through as it is.
+async function aacAudioIndexes(ffprobeBin: string, file: string): Promise<number[]> {
+ const r = await execa(ffprobeBin, ["-v", "error", "-select_streams", "a", "-show_entries", "stream=codec_name", "-of", "csv=p=0", file], {
+ reject: false,
+ });
+ return String(r.stdout ?? "")
+ .split("\n")
+ .map((l, i) => (l.trim() === "aac" ? i : -1))
+ .filter((i) => i >= 0);
+}
+
+export async function audioPacketsHash(ffmpegBin: string, file: string, signal?: AbortSignal, ffprobeBin = "ffprobe"): Promise<AudioHash> {
+ const bsf = (await aacAudioIndexes(ffprobeBin, file)).flatMap((i) => [`-bsf:a:${i}`, "aac_adtstoasc"]);
+ const data = createHash("sha256");
+ const timing = createHash("sha256");
+ let first: number | null = null;
+ let packets = 0;
+ const times: number[] = [];
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(
+ ffmpegBin,
+ ["-nostdin", "-hide_banner", "-v", "error", "-i", file, "-map", "0:a?", "-c", "copy", ...bsf, "-f", "framemd5", "-"],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let carry = "";
+ let err = "";
+ const onAbort = () => child.kill("SIGKILL");
+ signal?.addEventListener("abort", onAbort, { once: true });
+ // Each stream's timebase, from framemd5's header ("#tb 0: 1/44100"): the
+ // timing is compared in SECONDS, to the millisecond — the same packets
+ // carried by a Matroska source (1 ms ticks) and an mp4 copy (1/44100 s)
+ // are the same times in other numbers.
+ const tbs = new Map<string, number>();
+ const take = (line: string) => {
+ if (!line) return;
+ if (line.startsWith("#")) {
+ const m = /^#tb (\d+): (\d+)\/(\d+)/.exec(line);
+ if (m) tbs.set(m[1], Number(m[2]) / Number(m[3]));
+ return;
+ }
+ const f = line.split(",").map((x) => x.trim());
+ if (f.length < 6) return;
+ const [streamIdx, , pts, , size, md5] = f;
+ const p = Number(pts) * (tbs.get(streamIdx) ?? 1);
+ if (first === null) first = p;
+ packets += 1;
+ data.update(`${streamIdx},${size},${md5}\n`);
+ timing.update(`${streamIdx},${Math.round((p - (first ?? 0)) * 100)}\n`);
+ times.push(p - (first ?? 0));
+ };
+ 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, times: Float64Array.from(times) };
+}
+
+export type QualitySample = { at: number; score: number };
+
+// THE SOURCE TAKEN TO THE COPY'S RATE, the same way in the encode and in every
+// check: for a whole ratio (60 -> 30) every m-th frame from the first — the
+// copy's frame k IS the source's frame m·k, chunks starting on the copy's grid
+// — else the fps filter. (The fps filter's rounding took the ODD frames of a
+// 60 fps chunk seeked a millisecond early: a copy one source frame late.)
+export function wholeRatio(sourceFps: number | null | undefined, fps: number | null): number | null {
+ if (!fps || !sourceFps) return null;
+ const m = sourceFps / fps;
+ return m > 1 && Math.abs(m - Math.round(m)) < 0.01 ? Math.round(m) : null;
+}
+
+export function decimateTo(sourceFps: number | null | undefined, fps: number | null): string {
+ if (!fps) return "";
+ const m = wholeRatio(sourceFps, fps);
+ return m ? `select='not(mod(n,${m}))',` : `fps=${fps},`;
+}
+
+// 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;
+ sourceFps?: number | null;
+ metric: "vmaf" | "ssim";
+ scratchDir: string;
+ signal?: AbortSignal;
+ },
+): Promise<number> {
+ // FRAMES PAIRED BY THEIR NUMBER, not their timestamps: both inputs start on
+ // the same picture (sampleTimes puts `at` on the copy's frame grid), and the
+ // source is taken to the copy's rate first, so frame n of one is frame n of
+ // the other. A timestamp pairing paired neighbours wherever a container
+ // rounded a frame's time.
+ const n = renumber(opts.fps ?? opts.sourceFps ?? null);
+ const pre = Math.max(0, opts.at - 10);
+ const ref = `[1:v]trim=start=${(opts.at - pre).toFixed(4)},${decimateTo(opts.sourceFps, opts.fps)}${n}[r]`;
+ const dist = `[0:v]${n}[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,
+ // The source decoded from up to 10 s earlier and trimmed to the second:
+ // exact in any container (see referenceCutArgs).
+ "-ss", pre.toFixed(4), "-t", (opts.at - pre + 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 FRAME BY FRAME at the cut's
+// own size (at most 1280×720), the original's cut taken to the copy's rate:
+// frames paired by number, SSIM at the pairing as cut and at one frame either
+// way. The copy's cut must score best as cut: one that scores better a frame
+// off lands on other frames than the original's (on moving picture; on a
+// still one all three tie, and a tie passes — an offset there shows nothing).
+export type CutComparison = { ssim: number; earlier: number; later: number };
+
+// Frame n's time is n / rate on both sides — the rate written out, because a
+// `select` keeps its input's FRAME_RATE, and a pairing by time then pairs the
+// copy's frame n with the original's n / 2.
+//
+//
+// The SAME timebase and integer timestamps on both sides (`settb=1/rate`,
+// then `setpts=N`): the filters pair frames by time, and n / 30 s carried in a
+// 90 kHz copy and a 15360 Hz source rounds to different numbers — measured: a
+// lossless copy, frame for frame identical by framemd5, paired every fifth
+// frame with its neighbour.
+function renumber(rate: number | null): string {
+ return rate ? `settb=1/${rate},setpts=N` : "setpts=N/FRAME_RATE/TB,settb=AVTB";
+}
+
+async function ssimOf(paths: GatedPaths, b: string, a: string, rate: string, outRate: number | null, shift: number, signal?: AbortSignal): Promise<number> {
+ const n = renumber(outRate);
+ // shift > 0: the copy's frame n against the original's n + shift.
+ const trimA = shift > 0 ? `trim=start_frame=${shift},` : "";
+ const trimB = shift < 0 ? `trim=start_frame=${-shift},` : "";
+ const r = await execa(
+ paths.ffmpegBin,
+ [
+ "-nostdin", "-hide_banner", "-loglevel", "info",
+ "-i", b, "-i", a,
+ "-lavfi",
+ `[0:v]${trimB}${n}[d];[1:v]${rate}${trimA}${n}[r];[d][r]ssim=eof_action=endall`,
+ "-f", "null", "-",
+ ],
+ { reject: false, ...(signal ? { cancelSignal: 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");
+ return Number(m[1]);
+}
+
+// THE ORIGINAL'S CUT, as the reference: the evidence cutter's own encode, but
+// decoded from up to 10 s earlier and seeked on the output — exact whatever
+// the container (an input seek into an mpegts lands mid-GOP, and its first
+// pictures are the decoder's guesses). The COPY is cut by the cutter itself,
+// input seek and all: that is what is being proved.
+export function referenceCutArgs(file: string, a: number, b: number, out: string): string[] {
+ const args = evidenceCutArgs(file, a, b, "video", out);
+ const i = args.indexOf("-ss");
+ const pre = Math.max(0, a - 10);
+ args.splice(i, 6, "-ss", pre.toFixed(3), "-i", file, "-ss", (a - pre).toFixed(3), "-t", (b - a).toFixed(3));
+ return args;
+}
+
+export async function compareCuts(
+ paths: GatedPaths,
+ opts: {
+ compacted: string;
+ source: string;
+ at: number;
+ seconds: number;
+ fps: number | null;
+ sourceFps?: number | null;
+ scratchDir: string;
+ signal?: AbortSignal;
+ },
+): Promise<CutComparison> {
+ 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, args] of [
+ [opts.source, a, referenceCutArgs(opts.source, opts.at, opts.at + opts.seconds, a)],
+ [opts.compacted, b, evidenceCutArgs(opts.compacted, opts.at, opts.at + opts.seconds, "video", b)],
+ ] as const) {
+ const r = await execa(paths.ffmpegBin, args, {
+ 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 rate = decimateTo(opts.sourceFps, opts.fps);
+ const outRate = opts.fps ?? opts.sourceFps ?? null;
+ const ssim = await ssimOf(paths, b, a, rate, outRate, 0, opts.signal);
+ const later = await ssimOf(paths, b, a, rate, outRate, 1, opts.signal);
+ const earlier = await ssimOf(paths, b, a, rate, outRate, -1, opts.signal);
+ return { ssim, earlier, later };
+ } finally {
+ await rm(a, { force: true }).catch(() => {});
+ await rm(b, { force: true }).catch(() => {});
+ }
+}
+
+// A cut a frame off scores better shifted than as cut (beyond noise).
+export const CUT_OFFSET_MARGIN = 0.001;
+export function cutIsOffset(c: CutComparison): boolean {
+ return Math.max(c.earlier, c.later) > c.ssim + CUT_OFFSET_MARGIN;
+}
+
+// THE WHOLE FILE, COMPARED, EVERY FRAME (reviews H1 and F2). Both copies
+// decoded end to end; the source taken to the copy's rate exactly as the
+// encode took it (decimateTo), both on one clock and paired frame for frame
+// (renumber); scaled to WHOLE_FILE_WIDTH px wide, its aspect kept, grey. Each
+// frame scored by SSIM whole, AND split into a WHOLE_FILE_GRID × WHOLE_FILE_GRID
+// grid of tiles, each tile scored on its own — so a change to a small region
+// is not averaged away by the rest of the picture. One ffmpeg run (the tiles
+// are crops of the same decoded frames: one decode, 1 + grid² SSIM filters).
+//
+// Answers every frame's whole score, and per tile its lowest score (and
+// frame) and its longest run of frames below `tileFloor` (and where it
+// starts). The caller judges the floors.
+export const WHOLE_FILE_WIDTH = 256;
+export const WHOLE_FILE_GRID = 8;
+export const WHOLE_FILE_ESTIMATE_MB = 1500;
+
+export type TileSummary = {
+ index: number;
+ col: number;
+ row: number;
+ min: number;
+ minAt: number; // frame index
+ longestBelow: number; // frames
+ longestBelowAt: number; // frame index of the run's start
+};
+
+export type WholeFileComparison = {
+ frames: Float32Array;
+ tiles: TileSummary[];
+ width: number;
+ height: number;
+ grid: number;
+};
+
+function ssimScores(text: string): number[] {
+ const out: number[] = [];
+ for (const l of text.split("\n")) {
+ const m = /All:([0-9.]+|inf)/.exec(l);
+ if (m) out.push(m[1] === "inf" ? 1 : Number(m[1]));
+ }
+ return out;
+}
+
+export async function compareWholeFile(
+ paths: GatedPaths,
+ opts: {
+ compacted: string;
+ source: string;
+ scratchDir: string;
+ // The copy's frame rate when it was capped, the source's rate, its size.
+ fps: number | null;
+ sourceFps: number | null;
+ sourceWidth: number | null;
+ sourceHeight: number | null;
+ tileFloor: number;
+ signal?: AbortSignal;
+ },
+): Promise<WholeFileComparison> {
+ const W = WHOLE_FILE_WIDTH;
+ const aspect = opts.sourceWidth && opts.sourceHeight ? opts.sourceHeight / opts.sourceWidth : 9 / 16;
+ const H = Math.max(2 * WHOLE_FILE_GRID, 2 * Math.round((W * aspect) / 2));
+ const G = WHOLE_FILE_GRID;
+ const tw = Math.floor(W / G);
+ const th = Math.floor(H / G);
+ const T = G * G;
+ const rate = opts.fps ?? opts.sourceFps ?? null;
+ const n = renumber(rate);
+ const esc = (f: string) => f.replace(/[:\\']/g, "\\$&");
+ const whole = path.join(opts.scratchDir, "wf-whole.log");
+ const tileLog = (k: number) => path.join(opts.scratchDir, `wf-tile-${k}.log`);
+ const labels = (p: string) => Array.from({ length: T + 1 }, (_, k) => `[${p}${k}]`).join("");
+ const chains = [
+ `[0:v]${n},scale=${W}:${H}:flags=area,format=gray,split=${T + 1}${labels("d")}`,
+ `[1:v]${decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=gray,split=${T + 1}${labels("r")}`,
+ `[d0][r0]ssim=stats_file=${esc(whole)}:eof_action=endall[out]`,
+ ];
+ for (let k = 0; k < T; k += 1) {
+ const x = (k % G) * tw;
+ const y = Math.floor(k / G) * th;
+ const crop = `crop=${tw}:${th}:${x}:${y}`;
+ chains.push(`[d${k + 1}]${crop}[dc${k}]`, `[r${k + 1}]${crop}[rc${k}]`, `[dc${k}][rc${k}]ssim=stats_file=${esc(tileLog(k))}:eof_action=endall,nullsink`);
+ }
+ const graphFile = path.join(opts.scratchDir, "wf-graph.txt");
+ await writeFile(graphFile, chains.join(";\n"));
+ try {
+ await runHeavyFfmpeg(
+ paths,
+ [
+ "-nostdin", "-hide_banner", "-loglevel", "error",
+ "-i", opts.compacted, "-i", opts.source,
+ // ffmpeg 7+: a "-/" option reads its value from the file.
+ "-/filter_complex", graphFile, "-map", "[out]",
+ "-f", "null", "-",
+ ],
+ { estimateMB: WHOLE_FILE_ESTIMATE_MB, ...(opts.signal ? { signal: opts.signal } : {}) },
+ );
+ const frames = Float32Array.from(ssimScores(await readFile(whole, "utf8")));
+ const tiles: TileSummary[] = [];
+ for (let k = 0; k < T; k += 1) {
+ const sc = ssimScores(await readFile(tileLog(k), "utf8"));
+ let min = 1;
+ let minAt = 0;
+ let run = 0;
+ let runAt = 0;
+ let longest = 0;
+ let longestAt = 0;
+ for (let i = 0; i < sc.length; i += 1) {
+ if (sc[i] < min) {
+ min = sc[i];
+ minAt = i;
+ }
+ if (sc[i] < opts.tileFloor) {
+ if (run === 0) runAt = i;
+ run += 1;
+ if (run > longest) {
+ longest = run;
+ longestAt = runAt;
+ }
+ } else run = 0;
+ }
+ tiles.push({ index: k, col: k % G, row: Math.floor(k / G), min, minAt, longestBelow: longest, longestBelowAt: longestAt });
+ }
+ return { frames, tiles, width: W, height: H, grid: G };
+ } finally {
+ await rm(whole, { force: true }).catch(() => {});
+ await rm(graphFile, { force: true }).catch(() => {});
+ for (let k = 0; k < T; k += 1) await rm(tileLog(k), { force: true }).catch(() => {});
+ }
+}
+
+// The whole-file verdict (pure, so the thresholds are tested on their own).
+export type WholeFileVerdict = {
+ ok: boolean;
+ why?: string;
+ mean: number;
+ sd: number;
+ min: number;
+ minAt: number; // frame index
+ relativeFloor: number;
+ worstTile: TileSummary | null;
+};
+
+export function judgeWholeFile(
+ c: Pick<WholeFileComparison, "frames" | "tiles">,
+ t: { minFrame: number; meanFloor: number; sigmaK: number; sigmaMinMargin: number; tileRunFrames: number; expectedFrames: number; fps: number },
+): WholeFileVerdict {
+ const f = c.frames;
+ let sum = 0;
+ let min = 1;
+ let minAt = 0;
+ for (let i = 0; i < f.length; i += 1) {
+ sum += f[i];
+ if (f[i] < min) {
+ min = f[i];
+ minAt = i;
+ }
+ }
+ const mean = f.length ? sum / f.length : 0;
+ let v = 0;
+ for (let i = 0; i < f.length; i += 1) v += (f[i] - mean) ** 2;
+ const sd = f.length ? Math.sqrt(v / f.length) : 0;
+ const relativeFloor = mean - Math.max(t.sigmaK * sd, t.sigmaMinMargin);
+ let worstTile: TileSummary | null = null;
+ for (const tile of c.tiles) {
+ if (!worstTile || tile.longestBelow > worstTile.longestBelow || (tile.longestBelow === worstTile.longestBelow && tile.min < worstTile.min)) worstTile = tile;
+ }
+ const at = (i: number) => `${(i / t.fps).toFixed(2)} s`;
+ const base = { mean, sd, min, minAt, relativeFloor, worstTile };
+ if (f.length !== t.expectedFrames) {
+ return { ...base, ok: false, why: `the comparison saw ${f.length} of the copy's ${t.expectedFrames} frames: it ends early or skips` };
+ }
+ if (min < t.minFrame) return { ...base, ok: false, why: `a frame at ${at(minAt)} scores ${min.toFixed(3)} (no frame may fall below ${t.minFrame})` };
+ if (mean < t.meanFloor) return { ...base, ok: false, why: `the mean is ${mean.toFixed(3)} (needs ${t.meanFloor})` };
+ if (min < relativeFloor) {
+ return {
+ ...base,
+ ok: false,
+ why: `a frame at ${at(minAt)} scores ${min.toFixed(4)}, below the file's own ${mean.toFixed(4)} − max(${t.sigmaK}·${sd.toFixed(4)}, ${t.sigmaMinMargin}) = ${relativeFloor.toFixed(4)}`,
+ };
+ }
+ if (worstTile && worstTile.longestBelow > t.tileRunFrames) {
+ return {
+ ...base,
+ ok: false,
+ why:
+ `tile ${worstTile.col},${worstTile.row} of the ${Math.sqrt(c.tiles.length)}×${Math.sqrt(c.tiles.length)} grid is below its floor for ` +
+ `${worstTile.longestBelow} frames from ${at(worstTile.longestBelowAt)} (lowest ${worstTile.min.toFixed(3)}; more than ${t.tileRunFrames} fails)`,
+ };
+ }
+ return { ...base, ok: true };
+}
diff --git a/common/lib/compactingMarker-server.ts b/common/lib/compactingMarker-server.ts
@@ -0,0 +1,165 @@
+// THE "BEING COMPACTED" MARKER, `<store dir>/.compacting.json`
+// (controller/compactSavedVideos.ts writes it; every persist, attach, import,
+// unpersist and drop of the video reads it).
+//
+// A marker is LIVE only when everything it names still holds:
+// - this machine's kernel (`/proc/sys/kernel/random/boot_id`) — a reboot
+// ends every compaction;
+// - this host (a marker written in another container or on the host by a
+// CLI cannot be checked from here, and counts as stale);
+// - a running process with that pid AND that process's start time (field 22
+// of /proc/<pid>/stat), so a pid reused by another process is not it;
+// - when the marker is this process's own and names a job: that job is one
+// the job registry knows as queued or running (a probe the controller
+// registers; lib does not import the registry);
+// - younger than MARKER_MAX_AGE_HOURS.
+// Anything else is stale: it is ignored by every guard and removed by the
+// sweep (at editor boot and at the start of every compaction run) and by
+// `pnpm ops compaction-markers {"clear": …}`.
+//
+// The compaction's own steps carry the marker's token, and pass where another
+// writer is refused (the drop of the original under after-verify, F4).
+
+import { readFile, rm } from "node:fs/promises";
+import { hostname } from "node:os";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { readJsonFile, writeJsonAtomic } from "./jsonFile-server";
+
+export const COMPACTING_MARKER_FILENAME = ".compacting.json";
+export const MARKER_MAX_AGE_HOURS = 72;
+
+export type CompactingMarker = {
+ pid: number;
+ pidStart: string | null;
+ bootId: string | null;
+ host: string;
+ jobId?: string;
+ token: string;
+ startedAt: string;
+ video?: string;
+};
+
+export class CompactionInProgressError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "CompactionInProgressError";
+ }
+}
+
+async function bootId(): Promise<string | null> {
+ return readFile("/proc/sys/kernel/random/boot_id", "utf8").then((s) => s.trim(), () => null);
+}
+
+// The process's start time in clock ticks since boot, or null (no /proc, gone).
+export async function processStartTime(pid: number): Promise<string | null> {
+ try {
+ const s = await readFile(`/proc/${pid}/stat`, "utf8");
+ const rest = s.slice(s.lastIndexOf(")") + 2).split(" ");
+ // Fields after the comm start at field 3: start time is field 22.
+ return rest[22 - 3] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function alive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ // EPERM: it exists, under another user.
+ return (e as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+// The registry's word on a job of this process (registered by the controller).
+type JobProbe = (jobId: string) => boolean;
+let jobProbe: JobProbe | null = null;
+export function registerCompactionJobProbe(probe: JobProbe | null): void {
+ jobProbe = probe;
+}
+
+export function markerPath(storeDir: string): string {
+ return path.join(storeDir, COMPACTING_MARKER_FILENAME);
+}
+
+export async function writeCompactingMarker(storeDir: string, opts: { jobId?: string; video?: string; now?: Date } = {}): Promise<CompactingMarker> {
+ const m: CompactingMarker = {
+ pid: process.pid,
+ pidStart: await processStartTime(process.pid),
+ bootId: await bootId(),
+ host: hostname(),
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ token: randomUUID(),
+ startedAt: (opts.now ?? new Date()).toISOString(),
+ ...(opts.video ? { video: opts.video } : {}),
+ };
+ await writeJsonAtomic(markerPath(storeDir), m);
+ return m;
+}
+
+export async function readCompactingMarker(storeDir: string): Promise<CompactingMarker | null> {
+ const read = await readJsonFile(markerPath(storeDir));
+ if (!read.ok || !read.value || typeof read.value !== "object") return null;
+ const r = read.value as Record<string, unknown>;
+ if (typeof r.pid !== "number") return null;
+ return {
+ pid: r.pid,
+ pidStart: typeof r.pidStart === "string" ? r.pidStart : null,
+ bootId: typeof r.bootId === "string" ? r.bootId : null,
+ host: typeof r.host === "string" ? r.host : "",
+ ...(typeof r.jobId === "string" ? { jobId: r.jobId } : {}),
+ token: typeof r.token === "string" ? r.token : "",
+ startedAt: typeof r.startedAt === "string" ? r.startedAt : "",
+ ...(typeof r.video === "string" ? { video: r.video } : {}),
+ };
+}
+
+// Live, or why not.
+export async function markerLiveness(m: CompactingMarker, now = new Date()): Promise<{ live: boolean; why: string }> {
+ if (m.host !== hostname()) return { live: false, why: `written on another host (${m.host || "unknown"})` };
+ const boot = await bootId();
+ if (!m.bootId || (boot && m.bootId !== boot)) return { live: false, why: "written before this machine last started" };
+ if (!alive(m.pid)) return { live: false, why: `its process ${m.pid} is gone` };
+ const start = await processStartTime(m.pid);
+ if (!m.pidStart || (start !== null && start !== m.pidStart)) return { live: false, why: `pid ${m.pid} is another process now` };
+ if (m.pid === process.pid && m.jobId && jobProbe && !jobProbe(m.jobId)) {
+ return { live: false, why: `its job ${m.jobId} is not running` };
+ }
+ const age = (now.getTime() - Date.parse(m.startedAt)) / 3_600_000;
+ if (!Number.isFinite(age) || age > MARKER_MAX_AGE_HOURS) return { live: false, why: `older than ${MARKER_MAX_AGE_HOURS} h` };
+ return { live: true, why: `pid ${m.pid} since ${m.startedAt.slice(0, 16)}${m.jobId ? `, job ${m.jobId}` : ""}` };
+}
+
+export async function liveCompactingMarker(storeDir: string): Promise<CompactingMarker | null> {
+ const m = await readCompactingMarker(storeDir);
+ if (!m) return null;
+ return (await markerLiveness(m)).live ? m : null;
+}
+
+// Refused while a live marker is there — unless the caller holds its token
+// (the compaction's own steps).
+export async function assertNotCompacting(storeDir: string, what: string, ownToken?: string): Promise<void> {
+ const m = await liveCompactingMarker(storeDir);
+ if (m && !(ownToken && m.token === ownToken)) {
+ throw new CompactionInProgressError(
+ `${what} refused: this video's saved copy is being compacted (since ${m.startedAt.slice(0, 16)}, pid ${m.pid}` +
+ `${m.jobId ? `, job ${m.jobId}` : ""}). Run it again once the compaction is done.`,
+ );
+ }
+}
+
+// Remove a marker that is not live (or, with `token`, the caller's own).
+export async function clearCompactingMarker(storeDir: string, opts: { token?: string } = {}): Promise<{ cleared: boolean; why: string }> {
+ const m = await readCompactingMarker(storeDir);
+ if (!m) return { cleared: false, why: "no marker" };
+ if (opts.token && m.token === opts.token) {
+ await rm(markerPath(storeDir), { force: true });
+ return { cleared: true, why: "the compaction's own" };
+ }
+ const l = await markerLiveness(m);
+ if (l.live) return { cleared: false, why: `live: ${l.why} — cancel that job instead` };
+ await rm(markerPath(storeDir), { force: true });
+ return { cleared: true, why: `stale: ${l.why}` };
+}
diff --git a/common/lib/compactingMarker.test.ts b/common/lib/compactingMarker.test.ts
@@ -0,0 +1,96 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { hostname, tmpdir } from "node:os";
+import path from "node:path";
+import {
+ COMPACTING_MARKER_FILENAME,
+ CompactionInProgressError,
+ MARKER_MAX_AGE_HOURS,
+ assertNotCompacting,
+ clearCompactingMarker,
+ liveCompactingMarker,
+ markerLiveness,
+ processStartTime,
+ readCompactingMarker,
+ registerCompactionJobProbe,
+ writeCompactingMarker,
+} from "./compactingMarker-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/compactingMarker.test.ts
+//
+// The "being compacted" marker (review F3): live only when boot, host, pid,
+// the pid's start time, the job and the age all hold; every stale case is
+// ignored by the guards and cleared on request.
+
+async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
+ const dir = await mkdtemp(path.join(tmpdir(), "marker-"));
+ try {
+ await fn(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ registerCompactionJobProbe(null);
+ }
+}
+
+const bootId = async () => (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
+
+async function write(dir: string, m: Record<string, unknown>): Promise<void> {
+ const base = {
+ pid: process.pid,
+ pidStart: await processStartTime(process.pid),
+ bootId: await bootId(),
+ host: hostname(),
+ token: "t",
+ startedAt: new Date().toISOString(),
+ };
+ await writeFile(path.join(dir, COMPACTING_MARKER_FILENAME), JSON.stringify({ ...base, ...m }));
+}
+
+test("a marker this process wrote is live, refuses others, and passes its own token", async () => {
+ await withDir(async (dir) => {
+ const m = await writeCompactingMarker(dir, { video: "kick/v1" });
+ assert.ok(await liveCompactingMarker(dir));
+ await assert.rejects(assertNotCompacting(dir, "Persisting"), (e: Error) => e instanceof CompactionInProgressError);
+ await assertNotCompacting(dir, "the compaction's own drop", m.token);
+ assert.deepEqual(await clearCompactingMarker(dir), { cleared: false, why: `live: pid ${process.pid} since ${m.startedAt.slice(0, 16)} — cancel that job instead` });
+ assert.equal((await clearCompactingMarker(dir, { token: m.token })).cleared, true);
+ await assert.rejects(stat(path.join(dir, COMPACTING_MARKER_FILENAME)));
+ });
+});
+
+test("every stale case is ignored by the guards and cleared", async () => {
+ const cases: [string, Record<string, unknown>, RegExp][] = [
+ ["a dead pid", { pid: 2 ** 22 + 7 }, /process .* is gone/],
+ ["a pid reused by another live process", { pid: process.ppid }, /is another process now/],
+ ["pid 1, as a container's editor would be", { pid: 1 }, /is another process now/],
+ ["another host or container", { host: "another-host" }, /another host/],
+ ["before this machine last started", { bootId: "00000000-0000-0000-0000-000000000000" }, /before this machine last started/],
+ ["older than the cap", { startedAt: new Date(Date.now() - (MARKER_MAX_AGE_HOURS + 1) * 3_600_000).toISOString() }, /older than/],
+ ["a marker with no start time or boot (an older writer)", { pidStart: null, bootId: null }, /before this machine last started|another process/],
+ ];
+ for (const [label, m, why] of cases) {
+ await withDir(async (dir) => {
+ await write(dir, m);
+ const read = (await readCompactingMarker(dir))!;
+ const l = await markerLiveness(read);
+ assert.equal(l.live, false, label);
+ assert.match(l.why, why, label);
+ await assertNotCompacting(dir, "Persisting");
+ const c = await clearCompactingMarker(dir);
+ assert.equal(c.cleared, true, label);
+ });
+ }
+});
+
+test("this process's marker for a job the registry does not run is stale", async () => {
+ await withDir(async (dir) => {
+ await writeCompactingMarker(dir, { jobId: "j-gone" });
+ registerCompactionJobProbe((id) => id === "j-running");
+ assert.match((await markerLiveness((await readCompactingMarker(dir))!)).why, /job j-gone is not running/);
+ await assertNotCompacting(dir, "Persisting");
+ await writeCompactingMarker(dir, { jobId: "j-running" });
+ await assert.rejects(assertNotCompacting(dir, "Persisting"), (e: Error) => e instanceof CompactionInProgressError);
+ });
+});
diff --git a/common/lib/playableMedia.ts b/common/lib/playableMedia.ts
@@ -160,6 +160,11 @@ export type PlayableEntry = {
vcodec: string;
acodec: string | null;
preparedAt: string;
+ // MADE FROM A RE-ENCODE (the saved copy was compacted:
+ // controller/compactSavedVideos.ts): the ORIGINAL's sha256, and the words a
+ // reader shows. Absent on a copy of an original.
+ compactedFrom?: string;
+ note?: "re-encoded copy";
};
export type PlayableManifest = {
@@ -212,6 +217,9 @@ export function parsePlayableManifest(raw: unknown, slug: string): PlayableManif
vcodec: r.vcodec,
acodec: r.acodec as string | null,
preparedAt: r.preparedAt,
+ ...(typeof r.compactedFrom === "string" && HEX64.test(r.compactedFrom)
+ ? { compactedFrom: r.compactedFrom, note: "re-encoded copy" as const }
+ : {}),
};
}
return out;
diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts
@@ -5,8 +5,13 @@ import {
writeJsonAtomic,
} from "./jsonFile-server";
import path from "node:path";
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { execa } from "execa";
import {
mkdir,
+ open,
+ readdir,
readFile,
rename,
rm,
@@ -14,9 +19,13 @@ import {
} from "node:fs/promises";
import {
SAVED_VIDEO_POINTER_FILENAME,
+ compactedOriginalOf,
+ keepsAnyOriginal,
parseSavedVideoPointer,
+ reviewIsCurrent,
savedVideoBytes,
savedVideoPath,
+ type SavedAlternateReview,
type SavedVideoFormat,
type SavedVideoKeepReason,
type SavedVideoAlternate,
@@ -24,10 +33,28 @@ import {
type SavedVideoPointer,
} from "./savedVideo";
import { assertSavedVideosStoreWritable } from "./savedVideoStore";
+import { platformPresence } from "./availability-server";
+import { assertNotCompacting } from "./compactingMarker-server";
+import { probeMedia } from "./evidenceClip-server";
import type { Paths } from "./paths";
// Filesystem side of the saved-video store. See savedVideo.ts for the layout.
+function stampOf(at: Date): string {
+ return at.toISOString().replace(/\D/g, "").slice(0, 14);
+}
+
+// An alternate's name, `source-media.alt-<h>p-<stamp>.<ext>`, unique in
+// `taken` (ytdlp/savedAlternates.ts re-exports it).
+export function alternateName(file: string, height: number | null, at: Date, taken: Iterable<string> = []): string {
+ const ext = path.extname(file);
+ const stem = `source-media.alt-${height ? `${height}p-` : ""}${stampOf(at)}`;
+ const names = new Set(taken);
+ let name = `${stem}${ext}`;
+ for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
export function savedVideoPointerPath(videoDir: string): string {
return path.join(videoDir, SAVED_VIDEO_POINTER_FILENAME);
}
@@ -47,6 +74,8 @@ export async function isSavedVideo(videoDir: string): Promise<boolean> {
return (await loadSavedVideo(videoDir)) !== null;
}
+// A plain write. Every READ-MODIFY-WRITE of a pointer runs inside
+// withPointerLock and re-reads inside it (the writers below do).
export async function writePointer(
videoDir: string,
pointer: SavedVideoPointer,
@@ -55,6 +84,41 @@ export async function writePointer(
await writeJsonAtomic(file, pointer);
}
+// THE POINTER'S LOCK (jsonFile-server's per-file chain): one read-modify-write
+// of a video's saved-video.json at a time in this process. Not reentrant: a
+// writer that holds it calls the *Unlocked twins.
+export function withPointerLock<T>(videoDir: string, fn: () => Promise<T>): Promise<T> {
+ return withJsonFileLock(savedVideoPointerPath(videoDir), fn);
+}
+
+// A PLAN MADE ON AN OLDER POINTER. A writer that read the pointer, did slow
+// work, and would now write from what it read (a download's plan) refuses
+// when the active copy changed meanwhile — a compaction swapped it, another
+// persist landed — instead of writing the old copy back.
+export class SavedPointerChangedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SavedPointerChangedError";
+ }
+}
+
+export function samePointerCopy(
+ a: Pick<SavedVideoPointer, "file" | "bytes" | "storedAt">,
+ b: Pick<SavedVideoPointer, "file" | "bytes" | "storedAt">,
+): boolean {
+ return a.file === b.file && a.bytes === b.bytes && a.storedAt === b.storedAt;
+}
+
+// A COMPACTION IN PROGRESS for one video: lib/compactingMarker-server.ts
+// (`<store dir>/.compacting.json`). Every persist, attach, import, unpersist
+// and drop of the video refuses while a LIVE one is there.
+export {
+ COMPACTING_MARKER_FILENAME,
+ CompactionInProgressError,
+ assertNotCompacting,
+ liveCompactingMarker,
+} from "./compactingMarker-server";
+
// Repoint a video's saved-video.json at a new absolute store dir. Used when a
// channel is renamed: the pointer's `dir` is stored absolutely and includes the
// channel slug, so it must be rewritten after the store dir is moved or
@@ -64,11 +128,13 @@ export async function rewriteSavedVideoDir(
videoDir: string,
newDir: string,
): Promise<boolean> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer) return false;
- if (pointer.dir === newDir) return true;
- await writePointer(videoDir, { ...pointer, dir: newDir });
- return true;
+ return withPointerLock(videoDir, async () => {
+ const pointer = await loadSavedVideo(videoDir);
+ if (!pointer) return false;
+ if (pointer.dir === newDir) return true;
+ await writePointer(videoDir, { ...pointer, dir: newDir });
+ return true;
+ });
}
// Move a file, crossing device boundaries safely. A plain rename() works within
@@ -106,7 +172,7 @@ export async function resolveSavedVideo(
// Move a downloaded source container OUT of the main data dir into the saved
// store and write a pointer sidecar back into the data dir. Returns the pointer.
// Overwrites any existing stored container for this video (the redownload case).
-export async function persistSourceVideo(opts: {
+export type PersistSourceVideoOptions = {
videoDir: string;
sourceFilename: string;
storeDir: string;
@@ -135,10 +201,20 @@ export async function persistSourceVideo(opts: {
// The bytes' sha256, when the caller already hashed them (an attach hashes
// while it copies); the backup step otherwise fills it in later.
sha256?: string;
-}): Promise<SavedVideoPointer> {
+ // A person or an explicit action asked for it (SavedVideoPointer.explicit).
+ explicit?: boolean;
+};
+
+export async function persistSourceVideo(opts: PersistSourceVideoOptions): Promise<SavedVideoPointer> {
+ return withPointerLock(opts.videoDir, () => persistSourceVideoUnlocked(opts));
+}
+
+// The same, for a caller already holding the pointer's lock.
+export async function persistSourceVideoUnlocked(opts: PersistSourceVideoOptions): Promise<SavedVideoPointer> {
if (opts.paths) {
await assertSavedVideosStoreWritable(opts.paths, opts.storeDir);
}
+ await assertNotCompacting(opts.storeDir, "Persisting a container");
const src = opts.sourcePath ?? path.join(opts.videoDir, opts.sourceFilename);
const dest = path.join(opts.storeDir, opts.sourceFilename);
const st = await stat(src);
@@ -146,7 +222,35 @@ export async function persistSourceVideo(opts: {
// are still in that dir: the new pointer carries them, or they would be
// files no pointer names.
const before = await loadSavedVideo(opts.videoDir);
- const alternates = before?.dir === opts.storeDir ? before.alternates : undefined;
+ let alternates = before?.dir === opts.storeDir ? before.alternates : undefined;
+ // THE ACTIVE COPY WAS A COMPACTED RE-ENCODE, AND THIS REPLACES IT: its
+ // original is no longer the source of the active copy. It stays, re-labelled
+ // truthfully ("former-original"), and no automatic step can ever drop it.
+ if (before?.compacted && alternates?.some((a) => a.keptAs === "original")) {
+ alternates = alternates.map((a) => (a.keptAs === "original" ? { ...a, keptAs: "former-original" as const } : a));
+ }
+ // AN ALTERNATE UNDER THE NAME THIS PERSIST WRITES is moved aside first, never
+ // overwritten: a compacted video keeps its original as `source-media.<ext>`
+ // (the backup holds it under that name), and a download over it lands under
+ // the same name — the rename below would replace the original's bytes.
+ if (before && alternates?.some((a) => a.file === opts.sourceFilename)) {
+ const at = new Date();
+ const taken = new Set(await readdir(opts.storeDir).catch(() => [] as string[]));
+ const moved: SavedVideoAlternate[] = [];
+ for (const a of alternates) {
+ if (a.file !== opts.sourceFilename) {
+ moved.push(a);
+ continue;
+ }
+ const aside = alternateName(a.file, a.height ?? null, at, taken);
+ taken.add(aside);
+ await rename(path.join(opts.storeDir, a.file), path.join(opts.storeDir, aside));
+ moved.push({ ...a, file: aside });
+ }
+ alternates = moved;
+ // The pointer names the new name before the download takes the old one.
+ await writePointer(opts.videoDir, { ...before, alternates });
+ }
await moveFileCrossDevice(src, dest);
const pointer: SavedVideoPointer = {
storedAt: new Date().toISOString(),
@@ -157,6 +261,7 @@ export async function persistSourceVideo(opts: {
...(opts.sha256 ? { sha256: opts.sha256 } : {}),
...(opts.origin ? { origin: opts.origin } : {}),
...(opts.format ? { format: opts.format } : {}),
+ ...(opts.explicit ? { explicit: true as const } : {}),
...(alternates?.length ? { alternates } : {}),
};
await writePointer(opts.videoDir, pointer);
@@ -166,13 +271,77 @@ export async function persistSourceVideo(opts: {
// Record a content hash on a video's pointer (populated by the backup step so
// the store + UI can show a verified checksum). Best-effort: a missing pointer
// is a no-op.
+//
+// `file`: the basename that was hashed. The hash is written only while the
+// pointer still names that file — a backup or a remux hashes for minutes, and
+// a compaction (or a re-download) that swapped the active copy meanwhile must
+// not get the old file's hash. Rewritten from the RAW JSON under its lock.
export async function updateSavedVideoChecksum(
videoDir: string,
sha256: string,
+ file?: string,
): Promise<void> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer) return;
- await writePointer(videoDir, { ...pointer, sha256 });
+ const pointerFile = savedVideoPointerPath(videoDir);
+ await withJsonFileLock(pointerFile, async () => {
+ const read = await readJsonFile(pointerFile);
+ if (!read.ok || !parseSavedVideoPointer(read.value)) return;
+ const raw = { ...(read.value as Record<string, unknown>) };
+ if (file !== undefined && raw.file !== file) return;
+ raw.sha256 = sha256;
+ await writeJsonAtomic(pointerFile, raw);
+ });
+}
+
+// A PERSON'S REVIEW OF A COMPACTED COPY, recorded on its original's alternate
+// entry (`review`): what a video not known to be on its platform needs before
+// its original may be dropped (dropSavedAlternate). It names the copy it is
+// for — `forSha256`, the compacted copy's sha256 — and counts for that copy
+// only. Refused with no compacted block, no matching original, or checks that
+// did not pass. Raw JSON, under the pointer's lock.
+export async function recordOriginalReview(
+ videoDir: string,
+ review: Omit<SavedAlternateReview, "forSha256">,
+ // A FORMER original (`keptAs: "former-original"`) by its file name: the
+ // review is then of the active copy that replaced it (its sha256).
+ opts: { formerOriginal?: string } = {},
+): Promise<SavedVideoAlternate> {
+ const pointerFile = savedVideoPointerPath(videoDir);
+ return withJsonFileLock(pointerFile, async () => {
+ const read = await readJsonFile(pointerFile);
+ const pointer = read.ok ? parseSavedVideoPointer(read.value) : null;
+ if (!read.ok || !pointer) throw new SavedAlternateRefusal("This video has no saved-video pointer.");
+ if (opts.formerOriginal) {
+ const former = pointer.alternates?.find((a) => a.file === opts.formerOriginal && a.keptAs === "former-original");
+ if (!former) throw new SavedAlternateRefusal(`${opts.formerOriginal} is not a former original of this video.`);
+ if (!pointer.sha256) {
+ throw new SavedAlternateRefusal("The active copy has no recorded sha256 yet (the backup step or a prepare-playable records it): it cannot be reviewed.");
+ }
+ const full: SavedAlternateReview = { ...review, forSha256: pointer.sha256 };
+ const raw = { ...(read.value as Record<string, unknown>) };
+ raw.alternates = (Array.isArray(raw.alternates) ? raw.alternates : []).map((a) =>
+ a && typeof a === "object" && (a as { file?: unknown }).file === former.file ? { ...(a as object), review: full } : a,
+ );
+ await writeJsonAtomic(pointerFile, raw);
+ return { ...former, review: full };
+ }
+ if (!pointer.compacted) {
+ throw new SavedAlternateRefusal("This video's active copy is not a compacted re-encode: there is nothing to review.");
+ }
+ const original = compactedOriginalOf(pointer);
+ if (!original) {
+ throw new SavedAlternateRefusal("This video keeps no original of its compacted copy: there is nothing to review.");
+ }
+ if (!pointer.compacted.checks.passed) {
+ throw new SavedAlternateRefusal("The compacted copy's checks did not pass: it cannot be reviewed as good.");
+ }
+ const full: SavedAlternateReview = { ...review, forSha256: pointer.compacted.result.sha256 };
+ const raw = { ...(read.value as Record<string, unknown>) };
+ raw.alternates = (Array.isArray(raw.alternates) ? raw.alternates : []).map((a) =>
+ a && typeof a === "object" && (a as { file?: unknown }).file === original.file ? { ...(a as object), review: full } : a,
+ );
+ await writeJsonAtomic(pointerFile, raw);
+ return { ...original, review: full };
+ });
}
// Put a replaced pointer's provenance back on its replacement: the old
@@ -184,13 +353,15 @@ export async function restoreSavedVideoProvenance(
videoDir: string,
from: Pick<SavedVideoPointer, "keepReason" | "origin">,
): Promise<void> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer) return;
- const { keepReason: _k, origin: _o, ...rest } = pointer;
- await writePointer(videoDir, {
- ...rest,
- ...(from.keepReason ? { keepReason: from.keepReason } : {}),
- ...(from.origin ?? pointer.origin ? { origin: from.origin ?? pointer.origin } : {}),
+ await withPointerLock(videoDir, async () => {
+ const pointer = await loadSavedVideo(videoDir);
+ if (!pointer) return;
+ const { keepReason: _k, origin: _o, ...rest } = pointer;
+ await writePointer(videoDir, {
+ ...rest,
+ ...(from.keepReason ? { keepReason: from.keepReason } : {}),
+ ...(from.origin ?? pointer.origin ? { origin: from.origin ?? pointer.origin } : {}),
+ });
});
}
@@ -238,8 +409,28 @@ export async function unpersistSavedVideo(
// move in flight.
paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">,
): Promise<boolean> {
+ return withPointerLock(videoDir, () => unpersistUnlocked(videoDir, paths));
+}
+
+async function unpersistUnlocked(
+ videoDir: string,
+ paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">,
+): Promise<boolean> {
const pointer = await loadSavedVideo(videoDir);
if (!pointer) return false;
+ await assertNotCompacting(pointer.dir, "Unpersisting");
+ // A COMPACTED VIDEO (controller/compactSavedVideos.ts). With its original
+ // still kept, every copy comes back under its own name, as below: the
+ // original is `source-media.<ext>`, so it is the one the video dir takes for
+ // its source, and the re-encode is a file no reader takes for one. With the
+ // original dropped, the re-encode would be the only copy and the pointer —
+ // the one record that it is a re-encode — would go: refused.
+ if (pointer.compacted && !compactedOriginalOf(pointer)) {
+ throw new SavedAlternateRefusal(
+ `${pointer.file} is a re-encode (compacted ${pointer.compacted.at.slice(0, 10)}) and its original was dropped: ` +
+ "moving it back would leave a re-encode in the video dir with no record that it is one. Not unpersisted.",
+ );
+ }
if (paths) await assertSavedVideosStoreWritable(paths, pointer.dir);
const src = savedVideoPath(pointer);
const dest = path.join(videoDir, pointer.file);
@@ -262,16 +453,29 @@ export async function unpersistSavedVideo(
// a video that rolled out of the keep-latest window). Returns bytes freed. The
// whole video goes, its alternates with it — the prune itself never calls this
// for a video that holds any (pruneSavedVideos leaves those for the check).
+//
+// NEVER A VIDEO THAT KEEPS AN ORIGINAL (`keptAs: "original"`, the source of a
+// compacted copy): refused, nothing touched. Only a confirmed
+// dropSavedAlternate deletes an original.
export async function dropSavedVideo(videoDir: string): Promise<number> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer) return 0;
- await rm(savedVideoPath(pointer), { force: true });
- for (const alt of pointer.alternates ?? []) {
- await rm(path.join(pointer.dir, alt.file), { force: true });
- }
- await rm(savedVideoPointerPath(videoDir), { force: true });
- await pruneEmptyStoreDirs(pointer.dir);
- return savedVideoBytes(pointer);
+ return withPointerLock(videoDir, async () => {
+ const pointer = await loadSavedVideo(videoDir);
+ if (!pointer) return 0;
+ if (keepsAnyOriginal(pointer)) {
+ const o = (pointer.alternates ?? []).find((a) => a.keptAs === "original" || a.keptAs === "former-original")!;
+ throw new SavedAlternateRefusal(
+ `This video keeps an original (${o.file}) beside a compacted copy: it is never dropped whole.`,
+ );
+ }
+ await assertNotCompacting(pointer.dir, "Dropping the saved video");
+ await rm(savedVideoPath(pointer), { force: true });
+ for (const alt of pointer.alternates ?? []) {
+ await rm(path.join(pointer.dir, alt.file), { force: true });
+ }
+ await rm(savedVideoPointerPath(videoDir), { force: true });
+ await pruneEmptyStoreDirs(pointer.dir);
+ return savedVideoBytes(pointer);
+ });
}
// DROP ONE ALTERNATE (operator, 2026-10-29: a copy kept beside a newer download
@@ -322,12 +526,121 @@ export function isBareStoreName(file: string): boolean {
);
}
+//
+// AN ORIGINAL (`keptAs: "original"`: the source bytes a compacted active copy
+// was re-encoded from — controller/compactSavedVideos.ts) is refused unless:
+// - `confirmOriginal: true` names the intent;
+// - when the active copy is still that re-encode: its checks passed, and the
+// caller read it back from disk just now — `verifiedActive.sha256` equal to
+// the pointer's (compactSavedVideos' recheckCompactedCopy); a dry run is
+// answered without it;
+// - the video is still on its platform (availability public or unlisted),
+// OR a person's review is recorded on the entry (recordOriginalReview). A
+// video whose availability is unknown counts as gone.
+// The drop then records `compacted.originalDropped` (when, by whom, the file,
+// its bytes and sha256) in the same pointer write.
+// --- reading a copy back from disk ----------------------------------------------
+
+export async function sha256OfFile(file: string): Promise<string> {
+ const h = createHash("sha256");
+ for await (const chunk of createReadStream(file, { highWaterMark: 1 << 20 })) h.update(chunk as Buffer);
+ return h.digest("hex");
+}
+
+// fsync a file, then its directory: the bytes and the name are on the disk.
+export async function fsyncFileAndDir(file: string): Promise<void> {
+ const fh = await open(file, "r");
+ try {
+ await fh.sync();
+ } finally {
+ await fh.close();
+ }
+ const dh = await open(path.dirname(file), "r");
+ try {
+ await dh.sync();
+ } catch {
+ // Some filesystems refuse a directory fsync; the file's own sync stands.
+ } finally {
+ await dh.close();
+ }
+}
+
+// Drop the file's pages from the page cache (GNU dd `iflag=nocache`), so the
+// next read comes from the disk, not from what was just written. Best effort:
+// without it the read is still a full read of the file.
+export async function dropFromPageCache(file: string): Promise<void> {
+ await execa("dd", [`if=${file}`, "iflag=nocache", "count=0", "status=none"], { reject: false }).catch(() => {});
+}
+
+export type ReadBackDeps = {
+ hasher?: (file: string) => Promise<string>;
+ probe?: (file: string) => Promise<{ durationSec: number | null; hasVideo: boolean } | null>;
+};
+
+// THE COMPACTED COPY, READ BACK FROM DISK: fsynced, dropped from the cache,
+// its size against the pointer and the compaction record, its sha256 against
+// both, the container opening as a video, its length against the verified
+// one. The one implementation of the check every drop of an original runs.
+export async function readBackCompactedCopy(
+ pointer: SavedVideoPointer,
+ deps: ReadBackDeps = {},
+): Promise<{ ok: true; sha256: string } | { ok: false; why: string }> {
+ const c = pointer.compacted;
+ if (!c) return { ok: false, why: "the pointer names no compacted copy" };
+ if (pointer.file !== c.result.file) return { ok: false, why: `the pointer names ${pointer.file}, not the compacted ${c.result.file}` };
+ const file = savedVideoPath(pointer);
+ const st = await stat(file).catch(() => null);
+ if (!st?.isFile()) return { ok: false, why: `${file} is not there` };
+ if (st.size !== pointer.bytes || st.size !== c.result.bytes) {
+ return { ok: false, why: `${pointer.file} is ${st.size} bytes, ${c.result.bytes} recorded` };
+ }
+ await fsyncFileAndDir(file).catch(() => {});
+ await dropFromPageCache(file);
+ const sha = await (deps.hasher ?? sha256OfFile)(file);
+ if (sha !== pointer.sha256 || sha !== c.result.sha256) {
+ return { ok: false, why: `${pointer.file}'s sha256 is ${sha.slice(0, 12)}…, ${c.result.sha256.slice(0, 12)}… recorded` };
+ }
+ const p = await (deps.probe ?? ((f: string) => probeMedia(f)))(file);
+ if (!p || !p.hasVideo) return { ok: false, why: `${pointer.file} does not open as a video` };
+ const want = c.result.seconds;
+ if (want && p.durationSec && Math.abs(p.durationSec - want) > Math.max(0.05, c.checks.secondsTolerance)) {
+ return { ok: false, why: `${pointer.file} lasts ${p.durationSec} s, ${want} s recorded` };
+ }
+ return { ok: true, sha256: sha };
+}
+
+export type DropExpectation = { keptAs: "original"; sha256: string; file?: string };
+
export async function dropSavedAlternate(
videoDir: string,
file: string,
opts: {
dryRun?: boolean;
paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
+ // A person's word for an ORIGINAL ("keptAs": "original").
+ confirmOriginal?: boolean;
+ // A person's word for a FORMER ORIGINAL ("keptAs": "former-original").
+ // Its own flag: no automatic step passes it (a test scans the callers).
+ confirmFormerOriginal?: boolean;
+ // WHAT THE CALLER MEANS TO DROP, checked under the lock: the entry must be
+ // exactly this (kind, sha256, file) or nothing is dropped. The automatic
+ // after-verify drop always passes it — a persist landing between its read
+ // and this lock may have re-labelled the entry.
+ expect?: DropExpectation;
+ // Who drops it, for `originalDropped.by` (default "drop-saved-alternate").
+ by?: string;
+ // The gone rule's answer (default: platformPresence of the video dir,
+ // `maxAgeDays` old at most — default 7).
+ presence?: { onPlatform: boolean; why: string };
+ maxAgeDays?: number;
+ // A download or persist of this video queued or running: the reason, or
+ // null. An original is never dropped while one is.
+ busy?: () => string | null | Promise<string | null>;
+ // The compaction's own marker token: its after-verify drop passes the
+ // marker it still holds (F4); anyone else is refused while it is live.
+ markerToken?: string;
+ // The read-back's hasher and prober (tests name their own).
+ readBack?: ReadBackDeps;
} = {},
): Promise<DropSavedAlternateResult> {
if (!isBareStoreName(file)) {
@@ -347,6 +660,34 @@ export async function dropSavedAlternate(
}
const alternate = pointer.alternates?.find((a) => a.file === file);
if (!alternate) {
+ // AN INTERRUPTED DROP: the pointer was written, the file was not removed
+ // (`pendingDrops`). Asked again by name — with the same confirm an
+ // original or a former original needed — it is finished.
+ const pending = pointer.pendingDrops?.find((d) => d.file === file);
+ if (pending && !opts.expect) {
+ if (pending.keptAs === "original" && opts.confirmOriginal !== true) {
+ throw new SavedAlternateRefusal(`${file} is an original whose drop was interrupted: finish it with "confirmOriginal": true.`);
+ }
+ if (pending.keptAs === "former-original" && opts.confirmFormerOriginal !== true) {
+ throw new SavedAlternateRefusal(`${file} is a former original whose drop was interrupted: finish it with "confirmFormerOriginal": true.`);
+ }
+ const target = path.join(pointer.dir, file);
+ const st = await stat(target).catch(() => null);
+ if (!opts.dryRun) {
+ if (st) await rm(target, { force: true });
+ const raw = { ...(read.value as Record<string, unknown>) };
+ finishPending(raw, file);
+ await writeJsonAtomic(pointerFile, raw);
+ }
+ return {
+ dryRun: opts.dryRun === true,
+ alternate: { file, bytes: st?.size ?? 0, storedAt: "", setAsideAt: "", ...(pending.keptAs ? { keptAs: pending.keptAs } : {}), ...(pending.sha256 ? { sha256: pending.sha256 } : {}) },
+ path: target,
+ existed: st !== null,
+ bytes: st?.size ?? 0,
+ remaining: (pointer.alternates ?? []).length,
+ };
+ }
const listed = (pointer.alternates ?? []).map((a) => a.file);
throw new SavedAlternateRefusal(
`${file} is not one of this video's listed alternates` +
@@ -354,6 +695,68 @@ export async function dropSavedAlternate(
".",
);
}
+ // THE CALLER'S EXPECTATION, under the lock: any mismatch refuses.
+ if (opts.expect) {
+ const e = opts.expect;
+ if (alternate.keptAs !== e.keptAs || alternate.sha256 !== e.sha256 || (e.file !== undefined && alternate.file !== e.file)) {
+ throw new SavedAlternateRefusal(
+ `${file} is not what this drop expected (${e.keptAs}, sha256 ${e.sha256.slice(0, 12)}…): it is ` +
+ `${alternate.keptAs ?? "an ordinary alternate"}, sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}… now — nothing dropped.`,
+ );
+ }
+ }
+ const isOriginal = alternate.keptAs === "original";
+ const isFormer = alternate.keptAs === "former-original";
+ if (isOriginal && opts.confirmOriginal !== true) {
+ throw new SavedAlternateRefusal(
+ `${file} is the ORIGINAL the active copy was re-encoded from (sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}…): ` +
+ 'it is dropped only when the drop names it — pass "confirmOriginal": true.',
+ );
+ }
+ if (isFormer && opts.confirmFormerOriginal !== true) {
+ throw new SavedAlternateRefusal(
+ `${file} is the ORIGINAL of an earlier compacted copy (the active copy has since been replaced; sha256 ` +
+ `${alternate.sha256?.slice(0, 12) ?? "unknown"}…): it is dropped only by a person who names it — pass "confirmFormerOriginal": true.`,
+ );
+ }
+ if (isOriginal || isFormer) {
+ const busy = opts.busy ? await opts.busy() : null;
+ if (busy) throw new SavedAlternateRefusal(`${file} is kept: ${busy}.`);
+ await assertNotCompacting(pointer.dir, `Dropping ${file}`, opts.markerToken);
+ // THE GONE RULE, for both: still on its platform, freshly and
+ // first-hand — or a person's review of the copy that stays.
+ const presence =
+ opts.presence ?? (await platformPresence(videoDir, { maxAgeDays: opts.maxAgeDays ?? 7 }).catch(() => ({ onPlatform: false, why: "its availability could not be read" })));
+ if (!presence.onPlatform && !reviewIsCurrent(pointer, alternate)) {
+ throw new SavedAlternateRefusal(
+ `This video is not known to be on its platform (${presence.why}): the stored ${file} may be the only original there is. ` +
+ "Review the copy that stays first (review-compacted-original), then drop it." +
+ (alternate.review ? " (Its review is for another copy than the one active now.)" : ""),
+ );
+ }
+ }
+ if (isOriginal) {
+ // The original of THIS compacted copy, by its bytes — never by position.
+ const c = pointer.compacted;
+ if (!c) {
+ throw new SavedAlternateRefusal(`${file} is labelled an original but the active copy is not a compacted re-encode: it is kept.`);
+ }
+ if (!alternate.sha256 || alternate.sha256 !== c.source.sha256) {
+ throw new SavedAlternateRefusal(
+ `${file} is not the original the compacted copy was made from (its sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}… ` +
+ `is not the recorded source's ${c.source.sha256.slice(0, 12)}…): it is kept.`,
+ );
+ }
+ if (!c.checks.passed) {
+ throw new SavedAlternateRefusal(`The compacted copy's checks did not pass: ${file}, its original, is kept.`);
+ }
+ if (!opts.dryRun) {
+ const back = await readBackCompactedCopy(pointer, opts.readBack);
+ if (!back.ok) {
+ throw new SavedAlternateRefusal(`The compacted copy did not read back from disk (${back.why}): ${file}, its original, is kept.`);
+ }
+ }
+ }
if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, pointer.dir);
const target = path.join(pointer.dir, file);
const st = await stat(target).catch(() => null);
@@ -368,14 +771,50 @@ export async function dropSavedAlternate(
remaining,
};
if (opts.dryRun) return result;
- if (existed) await rm(target, { force: true });
+ // THE POINTER FIRST, THEN THE FILE: a crash between leaves the file listed
+ // in `pendingDrops` (any alternate, not only an original), never a pointer
+ // naming a file that is gone nor a file nothing names. Asking again
+ // finishes it (above); `get kept-originals` and the review list show it.
const raw = { ...(read.value as Record<string, unknown>) };
const kept = (Array.isArray(raw.alternates) ? raw.alternates : []).filter(
(a) => !(a && typeof a === "object" && (a as { file?: unknown }).file === file),
);
if (kept.length) raw.alternates = kept;
else delete raw.alternates;
+ const at = new Date().toISOString();
+ raw.pendingDrops = [
+ ...(Array.isArray(raw.pendingDrops) ? raw.pendingDrops : []),
+ { file, at, ...(alternate.keptAs ? { keptAs: alternate.keptAs } : {}), ...(alternate.sha256 ? { sha256: alternate.sha256 } : {}) },
+ ];
+ if (isOriginal && raw.compacted && typeof raw.compacted === "object") {
+ raw.compacted = {
+ ...(raw.compacted as Record<string, unknown>),
+ originalDropped: {
+ at,
+ by: opts.by ?? "drop-saved-alternate",
+ file,
+ bytes: st?.size ?? alternate.bytes,
+ sha256: alternate.sha256 ?? "",
+ fileRemoved: false,
+ },
+ };
+ }
+ await writeJsonAtomic(pointerFile, raw);
+ if (existed) await rm(target, { force: true });
+ finishPending(raw, file);
await writeJsonAtomic(pointerFile, raw);
return result;
});
}
+
+// The drop of `file` done: off `pendingDrops`, and an original's record says so.
+function finishPending(raw: Record<string, unknown>, file: string): void {
+ const left = (Array.isArray(raw.pendingDrops) ? raw.pendingDrops : []).filter(
+ (d) => !(d && typeof d === "object" && (d as { file?: unknown }).file === file),
+ );
+ if (left.length) raw.pendingDrops = left;
+ else delete raw.pendingDrops;
+ const c = raw.compacted as Record<string, unknown> | undefined;
+ const d = c?.originalDropped as Record<string, unknown> | undefined;
+ if (c && d && d.file === file) raw.compacted = { ...c, originalDropped: { ...d, fileRemoved: true } };
+}
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -54,6 +54,13 @@ export type SavedVideoPointer = {
// somebody asked for. Absent on every pointer written before this and on
// every automatic persist.
origin?: SavedVideoOrigin;
+ // A PERSON OR AN EXPLICIT ACTION ASKED FOR THIS CONTAINER: a download with
+ // `explicitPersist` (persist-videos, the video page's Persist source video,
+ // the whole-recording fetch) records it. `keepReason: "override"` cannot say
+ // it on its own — persist-kept, the keep-latest catch-up, writes "override"
+ // too. Absent on every pointer written before it and on every automatic
+ // persist (lib/savedVideoCompaction.ts isDeliberatelyStored reads it).
+ explicit?: true;
// WHAT WAS DOWNLOADED: the quality the persist asked for and the format
// yt-dlp actually took (its `requested_downloads[0]`, printed at download
// time). A "video_720" persist can fall through to its last-resort rung, so
@@ -72,10 +79,142 @@ export type SavedVideoPointer = {
// The active copy's own measured length and height, written when an
// alternate was recorded beside it (a landed container has no `format`).
probed?: SavedVideoProbe;
+ // THE ACTIVE COPY IS A RE-ENCODE (compact-saved-videos,
+ // controller/compactSavedVideos.ts): what it was made from, how, and every
+ // number its verification measured. `sha256`, `bytes` and `file` above are
+ // the re-encode's own; the source's are in `compacted.source`, and the
+ // source itself stays in `alternates` with `keptAs: "original"` until it is
+ // dropped (then `compacted.originalDropped` says when, and its hash). Absent
+ // on every pointer that was never compacted, which parses as before.
+ compacted?: SavedVideoCompacted;
+ // DROPS IN FLIGHT: an alternate whose pointer entry is gone and whose file
+ // is being removed (dropSavedAlternate writes this first). One left here
+ // after a crash is a file on disk no other key names: it is listed (`get
+ // kept-originals`) and dropping it again by name finishes it.
+ pendingDrops?: SavedPendingDrop[];
};
+export type SavedPendingDrop = { file: string; at: string; keptAs?: SavedAlternateKeptAs; sha256?: string };
+
export type SavedVideoProbe = { seconds?: number; height?: number };
+// What compaction asked the encoder for. The result's own measurements are in
+// `result` and `checks`.
+export type SavedVideoCompactedSettings = {
+ codec: string; // "av1"
+ encoder: string; // "libsvtav1"
+ preset: number;
+ crf: number;
+ gopSeconds: number;
+ pixFmt: string;
+ // The output frame rate when the source's was capped (60 -> 30), else null:
+ // the source's own.
+ fps: number | null;
+ audio: "copy";
+ chunkSeconds: number;
+};
+
+export type SavedVideoCompactedStream = {
+ file: string;
+ bytes: number;
+ sha256: string;
+ vcodec?: string;
+ height?: number;
+ fps?: number;
+ seconds?: number;
+ frames?: number;
+ // The video stream's own bitrate in kbit/s (container bytes minus audio,
+ // over the length), as the selector measured it.
+ videoKbps?: number;
+};
+
+// Every check compaction ran before the re-encode became active. `passed` is
+// true only when every one of them did; a pointer is never swapped otherwise.
+export type SavedVideoCompactedChecks = {
+ passed: boolean;
+ // Full decode of the re-encode, every frame, without an error.
+ decoded: boolean;
+ // [source, re-encode] video lengths in seconds, and the allowed difference.
+ seconds: [number, number];
+ secondsTolerance: number;
+ // [source frames, re-encode frames, frames expected from the fps change].
+ frames: [number, number, number];
+ // The audio packets' framemd5 of both files, hashed: "identical" or the
+ // copy fails ("different" on a failure record; "unknown" when unread).
+ audio: "identical" | "different" | "unknown";
+ audioHash: string;
+ // THE WHOLE FILE, compared: both copies decoded at `fps` frames a second,
+ // `width` px, grey, frames paired by timestamp, per-frame SSIM — the lowest
+ // (and where), the mean, the floor; and the largest gap between frames.
+ wholeFile?: {
+ fps: number;
+ width: number;
+ frames: number;
+ mean: number;
+ min: number;
+ worstAt: number;
+ minFloor: number;
+ meanFloor: number;
+ maxGapSeconds: number;
+ // Every frame since review F2: the frames' spread, the floor relative to
+ // it, the tile grid and its floor, the worst tile (lowest score, when,
+ // its longest run below the floor).
+ sd?: number;
+ relativeFloor?: number;
+ grid?: number;
+ tileFloor?: number;
+ tileRunFrames?: number;
+ worstTile?: { col: number; row: number; min: number; at: number; longestBelow: number };
+ };
+ // Every stream but the video, and the chapters: what the source holds and
+ // the copy holds ("audio:aac", "subtitle:mov_text", "chapters:3", …).
+ streams?: { source: string[]; result: string[] };
+ // The video's start against the audio's (seconds), in each file.
+ avOffset?: [number, number];
+ quality: {
+ metric: "vmaf" | "ssim";
+ mean: number;
+ min: number;
+ samples: number;
+ minMean: number;
+ minSample: number;
+ };
+ // A window cut from each copy through the evidence cutter at a few seconds,
+ // compared on a downscaled picture.
+ cuts: { at: number; ssim: number }[];
+ cutSsimMin: number;
+ // The recording clock (data/<id>/clock.json): "none" (no map), "kept" (the
+ // map re-measured against the re-encode and within tolerance of the old
+ // one, then written for it), "stale" (the map was already not current: it is
+ // measured again on the next fetch, as before).
+ clock: "none" | "kept" | "stale";
+};
+
+export type SavedVideoCompacted = {
+ at: string;
+ tool: string;
+ // `ffmpeg -version`'s first line and the encoder's banner, when it printed one.
+ encoder: string;
+ settings: SavedVideoCompactedSettings;
+ source: SavedVideoCompactedStream & { format?: SavedVideoFormat };
+ result: SavedVideoCompactedStream;
+ checks: SavedVideoCompactedChecks;
+ chunks: number;
+ // The second check, after the swap was written and before any drop: the
+ // re-encode read back from disk (size, sha256, container, length).
+ recheck?: { at: string; ok: boolean; why?: string };
+ // The original's drop, when it happened: by whom and the bytes that went.
+ // The pointer is written first (`fileRemoved: false`), then the file goes and
+ // `fileRemoved` turns true: an interrupted drop is seen and finished.
+ originalDropped?: { at: string; by: string; file: string; bytes: number; sha256: string; fileRemoved?: boolean };
+};
+
+// A person's word that a compacted copy is good (the review a video gone from
+// its platform needs before its original may be dropped).
+// Valid only for the compacted copy it watched: `forSha256` is that copy's
+// sha256 (compacted.result.sha256); a review of another copy counts for nothing.
+export type SavedAlternateReview = { at: string; by: string; note?: string; forSha256: string };
+
export type SavedVideoAlternate = {
// Basename in the pointer's `dir`.
file: string;
@@ -93,16 +232,31 @@ export type SavedVideoAlternate = {
// WHY IT IS KEPT, when on purpose rather than for a check. "proxy": the
// lower-quality copy a taller download replaced (persist-videos
// `replace: "below-height"`), kept as the light copy to work from — not a
- // suspected duplicate. Absent on every other alternate.
+ // suspected duplicate. "original": the source's own bytes a compacted
+ // active copy was re-encoded from (controller/compactSavedVideos.ts), kept
+ // until a confirmed drop. Absent on every other alternate.
keptAs?: SavedAlternateKeptAs;
+ // The copy's sha256, when it is known (an original: always).
+ sha256?: string;
+ // THIS COPY IS A RE-ENCODE of the bytes with this sha256: a compacted copy
+ // that a later download or attach replaced as the active one.
+ compactedFrom?: string;
+ // An original's review (see SavedAlternateReview).
+ review?: SavedAlternateReview;
};
-export const SAVED_ALTERNATE_KEPT_AS = ["proxy"] as const;
+export const SAVED_ALTERNATE_KEPT_AS = ["proxy", "original", "former-original"] as const;
export type SavedAlternateKeptAs = (typeof SAVED_ALTERNATE_KEPT_AS)[number];
// The words for an alternate's `keptAs`, wherever one is listed.
export const SAVED_ALTERNATE_KEPT_AS_LABELS: Record<SavedAlternateKeptAs, string> = {
proxy: "kept on purpose as the lower-quality proxy",
+ original: "the original the active copy was re-encoded from, kept until it is dropped",
+ // An original whose compacted copy was itself replaced (a later download,
+ // attach or import became the active copy): still the stored bytes of a
+ // recording, no longer the source of the active copy. Never dropped by any
+ // automatic step; only a person's confirmed drop removes it.
+ "former-original": "an original of an earlier compacted copy (the active copy has since been replaced), kept until a person drops it",
};
export type SavedVideoFormat = {
@@ -231,9 +385,217 @@ function parseAlternate(raw: unknown): SavedVideoAlternate | null {
if ((SAVED_ALTERNATE_KEPT_AS as readonly unknown[]).includes(r.keptAs)) {
out.keptAs = r.keptAs as SavedAlternateKeptAs;
}
+ if (typeof r.sha256 === "string" && r.sha256 !== "") out.sha256 = r.sha256;
+ if (typeof r.compactedFrom === "string" && r.compactedFrom !== "") out.compactedFrom = r.compactedFrom;
+ const review = parseReview(r.review);
+ if (review) out.review = review;
return out;
}
+function parseReview(raw: unknown): SavedAlternateReview | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.at !== "string" || r.at === "" || typeof r.by !== "string" || r.by === "") return null;
+ // A review that names no copy is for none (`forSha256: ""`).
+ return {
+ at: r.at,
+ by: r.by,
+ ...(typeof r.note === "string" && r.note !== "" ? { note: r.note } : {}),
+ forSha256: typeof r.forSha256 === "string" ? r.forSha256 : "",
+ };
+}
+
+function obj(v: unknown): Record<string, unknown> {
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+}
+function num(v: unknown, d = 0): number {
+ return typeof v === "number" && Number.isFinite(v) ? v : d;
+}
+function strOr(v: unknown, d = ""): string {
+ return typeof v === "string" ? v : d;
+}
+
+function parseCompactedStream(raw: unknown): SavedVideoCompactedStream {
+ const r = obj(raw);
+ const out: SavedVideoCompactedStream = { file: strOr(r.file), bytes: num(r.bytes), sha256: strOr(r.sha256) };
+ if (typeof r.vcodec === "string" && r.vcodec !== "") out.vcodec = r.vcodec;
+ for (const k of ["height", "fps", "seconds", "frames", "videoKbps"] as const) {
+ const v = positive(r[k]);
+ if (v !== undefined) out[k] = v;
+ }
+ return out;
+}
+
+// LENIENT ON PURPOSE: a `compacted` block that is there but damaged still
+// says "this is a re-encode" (missing numbers read 0, `passed` reads false),
+// because dropping it would make a re-encode read as the original's bytes.
+function parseCompacted(raw: unknown): SavedVideoCompacted | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ const s = obj(r.settings);
+ const c = obj(r.checks);
+ const q = obj(c.quality);
+ const pair = (v: unknown): [number, number] =>
+ Array.isArray(v) ? [num(v[0]), num(v[1])] : [0, 0];
+ const source = parseCompactedStream(r.source);
+ const format = parseFormat(obj(r.source).format);
+ const out: SavedVideoCompacted = {
+ at: strOr(r.at),
+ tool: strOr(r.tool),
+ encoder: strOr(r.encoder),
+ settings: {
+ codec: strOr(s.codec, "av1"),
+ encoder: strOr(s.encoder, "libsvtav1"),
+ preset: num(s.preset),
+ crf: num(s.crf),
+ gopSeconds: num(s.gopSeconds),
+ pixFmt: strOr(s.pixFmt),
+ fps: typeof s.fps === "number" && s.fps > 0 ? s.fps : null,
+ audio: "copy",
+ chunkSeconds: num(s.chunkSeconds),
+ },
+ source: { ...source, ...(format ? { format } : {}) },
+ result: parseCompactedStream(r.result),
+ checks: {
+ passed: c.passed === true,
+ decoded: c.decoded === true,
+ seconds: pair(c.seconds),
+ secondsTolerance: num(c.secondsTolerance),
+ frames: Array.isArray(c.frames) ? [num(c.frames[0]), num(c.frames[1]), num(c.frames[2])] : [0, 0, 0],
+ audio: c.audio === "identical" || c.audio === "different" ? c.audio : "unknown",
+ audioHash: strOr(c.audioHash),
+ quality: {
+ metric: q.metric === "ssim" ? "ssim" : "vmaf",
+ mean: num(q.mean),
+ min: num(q.min),
+ samples: num(q.samples),
+ minMean: num(q.minMean),
+ minSample: num(q.minSample),
+ },
+ cuts: Array.isArray(c.cuts)
+ ? c.cuts.map((x) => ({ at: num(obj(x).at), ssim: num(obj(x).ssim) }))
+ : [],
+ cutSsimMin: num(c.cutSsimMin),
+ clock: c.clock === "kept" || c.clock === "stale" ? c.clock : "none",
+ ...(c.wholeFile && typeof c.wholeFile === "object"
+ ? (() => {
+ const w = obj(c.wholeFile);
+ return {
+ wholeFile: {
+ fps: num(w.fps), width: num(w.width), frames: num(w.frames), mean: num(w.mean), min: num(w.min),
+ worstAt: num(w.worstAt), minFloor: num(w.minFloor), meanFloor: num(w.meanFloor), maxGapSeconds: num(w.maxGapSeconds),
+ ...(typeof w.sd === "number" ? { sd: w.sd } : {}),
+ ...(typeof w.relativeFloor === "number" ? { relativeFloor: w.relativeFloor } : {}),
+ ...(typeof w.grid === "number" ? { grid: w.grid } : {}),
+ ...(typeof w.tileFloor === "number" ? { tileFloor: w.tileFloor } : {}),
+ ...(typeof w.tileRunFrames === "number" ? { tileRunFrames: w.tileRunFrames } : {}),
+ ...(w.worstTile && typeof w.worstTile === "object"
+ ? (() => {
+ const t = obj(w.worstTile);
+ return { worstTile: { col: num(t.col), row: num(t.row), min: num(t.min), at: num(t.at), longestBelow: num(t.longestBelow) } };
+ })()
+ : {}),
+ },
+ };
+ })()
+ : {}),
+ ...(c.streams && typeof c.streams === "object"
+ ? {
+ streams: {
+ source: Array.isArray(obj(c.streams).source) ? (obj(c.streams).source as unknown[]).map(String) : [],
+ result: Array.isArray(obj(c.streams).result) ? (obj(c.streams).result as unknown[]).map(String) : [],
+ },
+ }
+ : {}),
+ ...(Array.isArray(c.avOffset) ? { avOffset: pair(c.avOffset) } : {}),
+ },
+ chunks: num(r.chunks),
+ };
+ const re = obj(r.recheck);
+ if (typeof re.at === "string") {
+ out.recheck = { at: re.at, ok: re.ok === true, ...(typeof re.why === "string" ? { why: re.why } : {}) };
+ }
+ const d = obj(r.originalDropped);
+ if (typeof d.at === "string") {
+ out.originalDropped = {
+ at: d.at, by: strOr(d.by), file: strOr(d.file), bytes: num(d.bytes), sha256: strOr(d.sha256),
+ ...(typeof d.fileRemoved === "boolean" ? { fileRemoved: d.fileRemoved } : {}),
+ };
+ }
+ return out;
+}
+
+// THE ORIGINAL OF THIS POINTER'S COMPACTED COPY, identified by its bytes,
+// never by position: the alternate `keptAs: "original"` whose sha256 is
+// `compacted.source.sha256`. Null with no compacted block, or none matching.
+export function compactedOriginalOf(pointer: SavedVideoPointer): SavedVideoAlternate | null {
+ const c = pointer.compacted;
+ if (!c || !c.source.sha256) return null;
+ return pointer.alternates?.find((a) => a.keptAs === "original" && a.sha256 === c.source.sha256) ?? null;
+}
+
+// Any alternate kept as an original (of this copy or an earlier one).
+export function keepsAnyOriginal(pointer: SavedVideoPointer): boolean {
+ return (pointer.alternates ?? []).some((a) => a.keptAs === "original" || a.keptAs === "former-original");
+}
+
+// Is a review valid for the copy that stays? An original's: for the compacted
+// copy this pointer names now (its result sha256). A former original's: for
+// the active copy that replaced it (the pointer's sha256).
+export function reviewIsCurrent(pointer: SavedVideoPointer, alternate: SavedVideoAlternate): boolean {
+ const r = alternate.review;
+ if (!r || r.forSha256 === "") return false;
+ if (alternate.keptAs === "former-original") return !!pointer.sha256 && r.forSha256 === pointer.sha256;
+ return !!pointer.compacted && r.forSha256 === pointer.compacted.result.sha256;
+}
+
+function codecName(vcodec: string | undefined): string {
+ if (!vcodec) return "video";
+ const v = vcodec.toLowerCase();
+ if (v.startsWith("avc") || v === "h264") return "H.264";
+ if (v.startsWith("hev") || v.startsWith("hvc") || v === "hevc" || v === "h265") return "HEVC";
+ if (v.startsWith("av01") || v === "av1") return "AV1";
+ if (v.startsWith("vp09") || v === "vp9") return "VP9";
+ return vcodec;
+}
+
+function fmtBytes(n: number): string {
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;
+ return `${n} B`;
+}
+
+function day(iso: string): string {
+ return /^\d{4}-\d{2}-\d{2}/.test(iso) ? iso.slice(0, 10) : iso || "an unknown day";
+}
+
+// THE ONE SENTENCE every surface says about a compacted copy (the video page,
+// /saved-videos, ops lines): it is a re-encode, of what, how, and where the
+// original is. Null for a pointer that was never compacted.
+// "Re-encoded copy (AV1 crf 36, 1080p30 from 60 fps, audio copied) of a
+// 12.30 GB H.264 original — 4.90 GB, 2026-11-13. The original is kept
+// beside it (source-media.mp4)."
+export function compactedLine(pointer: SavedVideoPointer): string | null {
+ const c = pointer.compacted;
+ if (!c) return null;
+ const h = c.result.height ?? c.source.height;
+ const fps = c.result.fps ?? c.settings.fps ?? c.source.fps;
+ const fromFps = c.settings.fps && c.source.fps && c.source.fps > c.settings.fps ? ` from ${Math.round(c.source.fps)} fps` : "";
+ const how =
+ `${codecName(c.settings.codec)} crf ${c.settings.crf}` +
+ `${h ? `, ${h}p${fps ? Math.round(fps) : ""}` : ""}${fromFps}, audio copied`;
+ const original = compactedOriginalOf(pointer);
+ const where = original
+ ? ` The original is kept beside it (${original.file}).`
+ : c.originalDropped
+ ? ` The original was dropped on ${day(c.originalDropped.at)} (sha256 ${c.originalDropped.sha256.slice(0, 12)}…, ${c.originalDropped.bytes} bytes).`
+ : " The original is not kept.";
+ return (
+ `Re-encoded copy (${how}) of a ${fmtBytes(c.source.bytes)} ${codecName(c.source.vcodec)} original — ` +
+ `${fmtBytes(pointer.bytes)}, ${day(c.at)}.${where}`
+ );
+}
+
// One line for a video holding alternates, for the review listing:
// "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s
// (attach-media, source-media.alt-360p-20261023172312.mp4)".
@@ -246,13 +608,19 @@ export function savedAlternatesLine(pointer: SavedVideoPointer): string {
pointer.probed?.seconds,
pointer.origin?.requestedBy ?? "download",
);
+ // A re-encode says so wherever a copy is listed.
+ const activeReencode = pointer.compacted
+ ? `, a re-encode (${codecName(pointer.compacted.settings.codec)} crf ${pointer.compacted.settings.crf})`
+ : "";
return (
- `${alts.length + 1} saved copies: active ${active}); ` +
+ `${alts.length + 1} saved copies: active ${active}${activeReencode}); ` +
alts
.map(
(a) =>
`alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file}` +
- `${a.keptAs ? `, ${SAVED_ALTERNATE_KEPT_AS_LABELS[a.keptAs]}` : ""})`,
+ `${a.keptAs ? `, ${SAVED_ALTERNATE_KEPT_AS_LABELS[a.keptAs]}` : ""}` +
+ `${a.compactedFrom ? ", a re-encode" : ""}` +
+ `${a.keptAs === "original" && a.review && reviewIsCurrent(pointer, a) ? `, reviewed ${day(a.review.at)} by ${a.review.by}` : ""})`,
)
.join("; ")
);
@@ -305,6 +673,7 @@ export function parseSavedVideoPointer(raw: unknown): SavedVideoPointer | null {
bytes: r.bytes,
};
if (isKeepReason(r.keepReason)) pointer.keepReason = r.keepReason;
+ if (r.explicit === true) pointer.explicit = true;
if (typeof r.sha256 === "string" && r.sha256 !== "") {
pointer.sha256 = r.sha256;
}
@@ -322,5 +691,23 @@ export function parseSavedVideoPointer(raw: unknown): SavedVideoPointer | null {
if (alternates.length) pointer.alternates = alternates;
const probed = parseProbe(r.probed);
if (probed) pointer.probed = probed;
+ const pending = Array.isArray(r.pendingDrops)
+ ? r.pendingDrops
+ .map((d): SavedPendingDrop | null => {
+ const o = obj(d);
+ if (typeof o.file !== "string" || o.file === "") return null;
+ return {
+ file: o.file,
+ at: strOr(o.at),
+ ...((SAVED_ALTERNATE_KEPT_AS as readonly unknown[]).includes(o.keptAs) ? { keptAs: o.keptAs as SavedAlternateKeptAs } : {}),
+ ...(typeof o.sha256 === "string" && o.sha256 ? { sha256: o.sha256 } : {}),
+ };
+ })
+ .filter((d): d is SavedPendingDrop => d !== null)
+ : [];
+ if (pending.length) pointer.pendingDrops = pending;
+ // And again: no `compacted`, the pointer parses as before.
+ const compacted = parseCompacted(r.compacted);
+ if (compacted) pointer.compacted = compacted;
return pointer;
}
diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts
@@ -0,0 +1,171 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS as D,
+ compactedFileName,
+ compactionFreeNeeded,
+ COMPACTION_DISK_MARGIN_BYTES,
+ decideCompaction,
+ estimateCompaction,
+ isDeliberatelyStored,
+ availabilitySaysPresent,
+ sanitizeSavedVideoCompaction,
+ targetFps,
+ type CompactionProbe,
+} from "./savedVideoCompaction";
+import type { SavedVideoPointer } from "./savedVideo";
+
+const pointer = (extra: Partial<SavedVideoPointer> = {}): SavedVideoPointer => ({
+ storedAt: "2026-11-01T00:00:00Z",
+ dir: "/store/kick/v1",
+ file: "source-media.mp4",
+ bytes: 12_000_000_000,
+ keepReason: "pin",
+ ...extra,
+});
+
+const probe = (extra: Partial<CompactionProbe> = {}): CompactionProbe => ({
+ hasVideo: true,
+ vcodec: "h264",
+ width: 1920,
+ height: 1080,
+ fps: 60,
+ seconds: 19_000,
+ videoKbps: 5000,
+ audioKbps: 155,
+ ...extra,
+});
+
+const decide = (o: Partial<Parameters<typeof decideCompaction>[0]> = {}) =>
+ decideCompaction({
+ pointer: pointer(),
+ platform: "kick",
+ channelExcluded: false,
+ mode: "select",
+ containerPresent: true,
+ probe: probe(),
+ settings: D,
+ ...o,
+ });
+
+test("the operator's rulings are the defaults", () => {
+ assert.equal(D.crf, 36);
+ assert.equal(D.preset, 8);
+ assert.equal(D.maxFps, 30);
+ assert.deepEqual(D.maxFpsPlatforms, ["kick", "twitch"]);
+ assert.deepEqual(D.platforms, ["kick", "twitch", "rumble"]);
+ // In this slice the original is kept by default (orchestrator, after review).
+ assert.equal(D.dropOriginal, "keep");
+ assert.equal(D.availabilityMaxAgeDays, 7);
+ assert.deepEqual(sanitizeSavedVideoCompaction(undefined), D);
+});
+
+test("sanitize clamps, lowercases platforms and refuses unknown values", () => {
+ const s = sanitizeSavedVideoCompaction({
+ platforms: [" Kick ", "kick", "YouTube", 3],
+ crf: 99,
+ preset: 2,
+ chunkMinutes: 0,
+ dropOriginal: "always",
+ maxFps: 0,
+ });
+ assert.deepEqual(s.platforms, ["kick", "youtube"]);
+ assert.equal(s.crf, D.crf);
+ assert.equal(s.preset, D.preset);
+ assert.equal(s.chunkMinutes, D.chunkMinutes);
+ assert.equal(s.dropOriginal, "keep");
+ assert.equal(s.maxFps, 0);
+ assert.equal(sanitizeSavedVideoCompaction({ dropOriginal: "after-verify" }).dropOriginal, "after-verify");
+});
+
+test("deliberately stored: a pin, an explicit persist, a requested container — never keep-latest, persist-kept or a legacy pointer", () => {
+ assert.equal(isDeliberatelyStored({ keepReason: "pin" }), true);
+ assert.equal(isDeliberatelyStored({ keepReason: "override", explicit: true }), true);
+ // persist-kept (the keep-latest catch-up) writes "override" with no explicit
+ // mark; a pointer from before the mark cannot say which it was.
+ assert.equal(isDeliberatelyStored({ keepReason: "override" }), false);
+ assert.equal(isDeliberatelyStored({ keepReason: "keep-latest", origin: { requestedBy: "umtool" } }), true);
+ assert.equal(isDeliberatelyStored({ keepReason: "keep-latest" }), false);
+ assert.equal(isDeliberatelyStored({}), false);
+});
+
+test("a record's word: public or unlisted only (the gone rule itself is platformPresence)", () => {
+ assert.equal(availabilitySaysPresent("public"), true);
+ assert.equal(availabilitySaysPresent("unlisted"), true);
+ for (const a of ["deleted", "private", "members_only", "needs_auth", "error", null, undefined] as const) {
+ assert.equal(availabilitySaysPresent(a), false, String(a));
+ }
+});
+
+test("the selector picks only deliberately stored AND platform AND bitrate AND height", () => {
+ assert.deepEqual(decide(), { ok: true });
+ assert.match((decide({ pointer: pointer({ keepReason: "keep-latest" }) }) as { reason: string }).reason, /keep-latest/);
+ assert.match((decide({ pointer: pointer({ keepReason: undefined }) }) as { reason: string }).reason, /legacy pointer/);
+ assert.match((decide({ platform: "youtube" }) as { reason: string }).reason, /platform youtube is not selected/);
+ assert.match((decide({ probe: probe({ videoKbps: 2500 }) }) as { reason: string }).reason, /below minVideoMbps 3/);
+ assert.match((decide({ probe: probe({ height: 480 }) }) as { reason: string }).reason, /below minHeight/);
+ assert.deepEqual(decide({ platform: "rumble", probe: probe({ fps: 30, videoKbps: 3200, height: 720 }) }), { ok: true });
+});
+
+test("an explicit item the selector would not pick needs belowThreshold; the deliberate rule has no override", () => {
+ const below = decide({ mode: "explicit", platform: "youtube", probe: probe({ videoKbps: 400, height: 360 }) });
+ assert.equal(below.ok, false);
+ assert.match((below as { reason: string }).reason, /platform youtube is not selected; named explicitly, it is compacted only with "belowThreshold": true/);
+ assert.deepEqual(decide({ mode: "explicit", platform: "youtube", probe: probe({ videoKbps: 400 }), belowThreshold: true }), {
+ ok: true,
+ belowThreshold: "platform youtube is not selected",
+ });
+ assert.deepEqual(decide({ mode: "explicit" }), { ok: true });
+ assert.equal(decide({ mode: "explicit", belowThreshold: true, pointer: pointer({ keepReason: "keep-latest" }) }).ok, false);
+});
+
+test("a pointer that already keeps an original (of this or an earlier copy) is never compacted again", () => {
+ for (const keptAs of ["original", "former-original"] as const) {
+ const d = decide({ pointer: pointer({ alternates: [{ file: "a.mp4", bytes: 1, storedAt: "", setAsideAt: "", keptAs }] }) });
+ assert.match((d as { reason: string }).reason, /already keeps an original/);
+ }
+});
+
+test("already compacted, opted out, audio-only, already AV1 and a missing container are skipped", () => {
+ const compacted = pointer({ compacted: { at: "x" } as SavedVideoPointer["compacted"] });
+ assert.deepEqual(decide({ pointer: compacted }), { ok: false, reason: "already compacted" });
+ assert.match((decide({ channelExcluded: true }) as { reason: string }).reason, /opts out/);
+ assert.match((decide({ probe: probe({ hasVideo: false }) }) as { reason: string }).reason, /audio-only/);
+ assert.match((decide({ probe: probe({ vcodec: "av1" }) }) as { reason: string }).reason, /already AV1/);
+ assert.match((decide({ containerPresent: false }) as { reason: string }).reason, /not in the store/);
+});
+
+test("60 -> 30 fps on Kick and Twitch only, and only above the cap", () => {
+ assert.equal(targetFps(60, "kick", D), 30);
+ assert.equal(targetFps(59.94, "twitch", D), 30);
+ assert.equal(targetFps(30, "kick", D), null);
+ assert.equal(targetFps(60, "rumble", D), null);
+ assert.equal(targetFps(60, "kick", { ...D, maxFps: 0 }), null);
+});
+
+test("the estimate follows the design's measured shares", () => {
+ const p = probe({ seconds: 20_940, videoKbps: 5000, audioKbps: 155 });
+ const at60 = estimateCompaction({ probe: p, crf: 36, fps: null });
+ assert.ok(Math.abs(at60.share - 0.64) < 1e-9);
+ const at30 = estimateCompaction({ probe: p, crf: 36, fps: 30 });
+ assert.ok(Math.abs(at30.share - 0.44) < 1e-6, String(at30.share));
+ assert.ok(at30.bytes[1] < at60.bytes[1]);
+ assert.ok(at60.bytes[0] < at60.bytes[1]);
+ assert.ok(at60.hours[0] < at60.hours[1]);
+ // crf 40 interpolates to its row.
+ assert.ok(Math.abs(estimateCompaction({ probe: p, crf: 40, fps: null }).share - 0.47) < 1e-9);
+});
+
+test("the disk floor is two outputs less what the chunks hold, plus the margin", () => {
+ assert.equal(compactionFreeNeeded(1000, 0), 2000 + COMPACTION_DISK_MARGIN_BYTES);
+ assert.equal(compactionFreeNeeded(1000, 600), 1400 + COMPACTION_DISK_MARGIN_BYTES);
+});
+
+test("the compacted copy has its own name, never the original's", () => {
+ const at = new Date("2026-11-14T03:12:09Z");
+ assert.equal(compactedFileName(at), "source-media.compact-av1-20261114031209.mp4");
+ assert.equal(
+ compactedFileName(at, ["source-media.compact-av1-20261114031209.mp4"]),
+ "source-media.compact-av1-20261114031209-2.mp4",
+ );
+});
diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts
@@ -0,0 +1,386 @@
+// COMPACTING A SAVED VIDEO — the pure half: the settings block, the selector,
+// the estimate and the names (controller/compactSavedVideos.ts does the work).
+//
+// A large stored stream (Kick, Twitch, the high-bitrate half of Rumble) is
+// re-encoded to AV1 (SVT-AV1 preset 8, crf 36, a keyframe every 5 s, the
+// source's height, 60 -> 30 fps on Kick and Twitch, the audio copied
+// bit-for-bit), verified, and made the ACTIVE copy; the original stays beside
+// it as the alternate `keptAs: "original"` until a separate step drops it.
+// Operator rulings, 13 Nov 2026:
+// - crf 36, preset 8, keyint 5 s, audio copied;
+// - Kick and Twitch above 30 fps go to 30;
+// - the original may be dropped once every check passed, in a step of its
+// own that reads the finished file back (`dropOriginal: "after-verify"`);
+// in this slice the DEFAULT is "keep" (orchestrator, 13 Nov, after review),
+// and "after-verify" drops only when the verification included the
+// whole-file comparison;
+// - DELIBERATELY STORED videos only (isDeliberatelyStored, below), never the
+// keep-latest containers and never the audio beside the record;
+// - the selector is deliberately stored AND platform in the set AND the
+// stored video bitrate above a threshold (Rumble's high-bitrate half);
+// YouTube is left alone by default;
+// - a video gone from its platform is compacted too, but its original is
+// NEVER dropped automatically: a person reviews the compacted copy first.
+//
+// Pure: no node imports (the editor's client pages read the labels).
+
+import type { FieldDocs } from "./fieldDocs";
+import { keepsAnyOriginal, type SavedVideoPointer } from "./savedVideo";
+import type { Availability } from "./availability";
+
+// --- settings -----------------------------------------------------------------
+
+export const COMPACTION_DROP_ORIGINAL = ["after-verify", "keep"] as const;
+export type CompactionDropOriginal = (typeof COMPACTION_DROP_ORIGINAL)[number];
+
+export type SavedVideoCompactionSettings = {
+ platforms: string[];
+ minVideoMbps: number;
+ minHeight: number;
+ crf: number;
+ preset: number;
+ maxFps: number;
+ maxFpsPlatforms: string[];
+ chunkMinutes: number;
+ qualitySamples: number;
+ vmafMinMean: number;
+ vmafMinSample: number;
+ ssimMinMean: number;
+ ssimMinSample: number;
+ wholeFileSsimMin: number;
+ wholeFileSsimMean: number;
+ wholeFileSigmaK: number;
+ wholeFileSigmaMargin: number;
+ wholeFileTileMin: number;
+ wholeFileTileRunFrames: number;
+ availabilityMaxAgeDays: number;
+ dropOriginal: CompactionDropOriginal;
+};
+
+export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettings = {
+ platforms: ["kick", "twitch", "rumble"],
+ minVideoMbps: 3,
+ minHeight: 720,
+ crf: 36,
+ preset: 8,
+ maxFps: 30,
+ maxFpsPlatforms: ["kick", "twitch"],
+ chunkMinutes: 10,
+ qualitySamples: 12,
+ // The design's measurement on a Kick 1080p60 sample: crf 36 scored VMAF
+ // 94.2 mean, 91.9 at its worst frame. The thresholds keep a margin under it.
+ vmafMinMean: 90,
+ vmafMinSample: 85,
+ // Only where this ffmpeg has no libvmaf: SSIM on the same samples.
+ ssimMinMean: 0.95,
+ ssimMinSample: 0.9,
+ // The whole-file comparison (64 px grey, 2 frames a second, every second of
+ // the file): no frame below the floor, the mean at least the mean floor.
+ wholeFileSsimMin: 0.9,
+ wholeFileSsimMean: 0.97,
+ wholeFileSigmaK: 8,
+ wholeFileSigmaMargin: 0.03,
+ wholeFileTileMin: 0.7,
+ wholeFileTileRunFrames: 2,
+ availabilityMaxAgeDays: 7,
+ dropOriginal: "keep",
+};
+
+export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCompactionSettings> = {
+ platforms:
+ '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:
+ "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: "The selector's other floor: a container shorter than this (pixels) is already light. Default 720.",
+ crf: "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: "SVT-AV1's preset. Default 8. 4–12.",
+ maxFps:
+ "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: 'The platforms `maxFps` applies to. Default ["kick", "twitch"]; a Rumble 60 fps stream keeps its 60.',
+ chunkMinutes:
+ "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:
+ "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: "The VMAF the excerpts' mean must reach (against the stored source). Default 90.",
+ vmafMinSample: "The VMAF no single excerpt may fall below. Default 85.",
+ ssimMinMean: "Without libvmaf: the SSIM the excerpts' mean must reach. Default 0.95.",
+ ssimMinSample: "Without libvmaf: the SSIM no excerpt may fall below. Default 0.9.",
+ wholeFileSsimMin:
+ "THE WHOLE-FILE COMPARISON scores EVERY frame of the copy against the source's (256 px wide, grey, the source taken to the copy's rate, paired frame for frame): no frame may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern scores at least 0.996; one black frame scores 0).",
+ wholeFileSsimMean: "The whole-file comparison's mean must reach this. Default 0.97.",
+ wholeFileSigmaK:
+ "The floor relative to the file itself: no frame below its mean − max(k × the frames' standard deviation, wholeFileSigmaMargin). Default k = 8 (measured: a good crf-36 copy has a spread of 0.0006, its worst frame 3 spreads under its mean).",
+ wholeFileSigmaMargin: "The least the relative floor sits under the mean, for a file whose frames barely differ. Default 0.03.",
+ wholeFileTileMin:
+ "Each frame is also split into an 8×8 grid of tiles, each scored on its own, so a change to a small region is not averaged away: a tile below this for more than wholeFileTileRunFrames frames in a row fails. Default 0.7 (a good crf-36 copy's lowest tile: 0.949; a red box over 1% of the picture: 0.46).",
+ wholeFileTileRunFrames: "How many frames in a row a tile may sit below wholeFileTileMin. Default 2: a 3-frame defect at 30 fps fails.",
+ availabilityMaxAgeDays:
+ "How fresh the platform check must be for a video to count as still on its platform: an availability record written by a real check (not a backfill), public or unlisted, at most this many days old. Anything else counts as gone, and its original waits for a person's review. Default 7.",
+ dropOriginal:
+ '"keep" (the default in this slice): every original stays until a person drops it. "after-verify": 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`); only when the verification included the whole-file comparison. There is no backup of the store: after such a drop the compacted copy is the only copy.',
+};
+
+function clampNum(v: unknown, d: number, lo: number, hi: number): number {
+ return typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi ? v : d;
+}
+
+function platformList(v: unknown, d: string[]): string[] {
+ if (!Array.isArray(v)) return [...d];
+ const out: string[] = [];
+ for (const x of v) {
+ if (typeof x !== "string") continue;
+ const p = x.trim().toLowerCase();
+ if (p && !out.includes(p)) out.push(p);
+ }
+ return out;
+}
+
+export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompactionSettings {
+ const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const d = DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS;
+ return {
+ platforms: platformList(r.platforms, d.platforms),
+ minVideoMbps: clampNum(r.minVideoMbps, d.minVideoMbps, 0, 1000),
+ minHeight: Math.round(clampNum(r.minHeight, d.minHeight, 0, 4320)),
+ crf: Math.round(clampNum(r.crf, d.crf, 20, 55)),
+ preset: Math.round(clampNum(r.preset, d.preset, 4, 12)),
+ maxFps: clampNum(r.maxFps, d.maxFps, 0, 240),
+ maxFpsPlatforms: platformList(r.maxFpsPlatforms, d.maxFpsPlatforms),
+ chunkMinutes: clampNum(r.chunkMinutes, d.chunkMinutes, 1, 60),
+ qualitySamples: Math.round(clampNum(r.qualitySamples, d.qualitySamples, 3, 60)),
+ vmafMinMean: clampNum(r.vmafMinMean, d.vmafMinMean, 0, 100),
+ vmafMinSample: clampNum(r.vmafMinSample, d.vmafMinSample, 0, 100),
+ ssimMinMean: clampNum(r.ssimMinMean, d.ssimMinMean, 0, 1),
+ ssimMinSample: clampNum(r.ssimMinSample, d.ssimMinSample, 0, 1),
+ wholeFileSsimMin: clampNum(r.wholeFileSsimMin, d.wholeFileSsimMin, 0, 1),
+ wholeFileSsimMean: clampNum(r.wholeFileSsimMean, d.wholeFileSsimMean, 0, 1),
+ wholeFileSigmaK: clampNum(r.wholeFileSigmaK, d.wholeFileSigmaK, 1, 100),
+ wholeFileSigmaMargin: clampNum(r.wholeFileSigmaMargin, d.wholeFileSigmaMargin, 0, 1),
+ wholeFileTileMin: clampNum(r.wholeFileTileMin, d.wholeFileTileMin, 0, 1),
+ wholeFileTileRunFrames: Math.round(clampNum(r.wholeFileTileRunFrames, d.wholeFileTileRunFrames, 0, 300)),
+ availabilityMaxAgeDays: clampNum(r.availabilityMaxAgeDays, d.availabilityMaxAgeDays, 0, 365),
+ dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal)
+ ? (r.dropOriginal as CompactionDropOriginal)
+ : d.dropOriginal,
+ };
+}
+
+// --- what counts --------------------------------------------------------------
+
+// DELIBERATELY STORED (ruling 4): a pointer that says a person or an explicit
+// action kept it —
+// keepReason "pin" pinned / irreplaceable; every landed container (an
+// import, a live recording, attach-media) is a pin;
+// `explicit` an explicit persist: persist-videos, the video
+// page's Persist source video, the whole-recording
+// fetch (downloadOneManaged's `explicitPersist`);
+// any `origin` a container somebody requested (umtool's
+// `full: true`, a landed or attached file).
+// NOT: keepReason "override" alone — persist-kept, the keep-latest catch-up,
+// writes it too, and a pointer from before `explicit` cannot say which it was,
+// so it is not selected; keepReason "keep-latest" with no origin (the
+// automatic window); a legacy pointer with none of these.
+export function isDeliberatelyStored(pointer: Pick<SavedVideoPointer, "keepReason" | "origin" | "explicit">): boolean {
+ if (pointer.origin) return true;
+ if (pointer.explicit === true) return true;
+ return pointer.keepReason === "pin";
+}
+
+// The record's word alone: public or unlisted. The gone rule itself is
+// availability-server's platformPresence (a fresh, first-hand check).
+export function availabilitySaysPresent(a: Availability | null | undefined): boolean {
+ return a === "public" || a === "unlisted";
+}
+
+// What the selector reads of a stored container (one ffprobe).
+export type CompactionProbe = {
+ hasVideo: boolean;
+ vcodec: string | null;
+ width: number | null;
+ height: number | null;
+ fps: number | null;
+ seconds: number | null;
+ videoKbps: number | null;
+ audioKbps: number | null;
+};
+
+// `belowThreshold`: an explicitly named video the selector would not pick
+// (ruling 9) — refused unless the run says `"belowThreshold": true`.
+export type CompactionDecision =
+ | { ok: true; belowThreshold?: string }
+ | { ok: false; reason: string; belowThreshold?: string };
+
+export function decideCompaction(opts: {
+ pointer: SavedVideoPointer;
+ platform: string | null;
+ channelExcluded: boolean;
+ // "select": the settings' selector applies; "explicit": a person named it.
+ mode: "explicit" | "select";
+ containerPresent: boolean;
+ probe: CompactionProbe | null;
+ settings: SavedVideoCompactionSettings;
+ // The run allows an explicit item the selector would not pick.
+ belowThreshold?: boolean;
+}): CompactionDecision {
+ const { pointer, settings: s, probe } = opts;
+ if (pointer.compacted) return { ok: false, reason: "already compacted" };
+ if (keepsAnyOriginal(pointer)) {
+ return { ok: false, reason: "it already keeps an original of an earlier compacted copy beside it" };
+ }
+ if (opts.channelExcluded) return { ok: false, reason: "the channel opts out (excludeFromCompaction)" };
+ if (!isDeliberatelyStored(pointer)) {
+ return {
+ ok: false,
+ reason:
+ pointer.keepReason === "keep-latest"
+ ? "an automatic keep-latest container (compaction is for deliberately stored videos only)"
+ : pointer.keepReason === "override"
+ ? 'kept as "override" with no record that a person asked for it (persist-kept, the keep-latest catch-up, writes it too): not known to be kept on purpose'
+ : "no keep reason recorded (a legacy pointer): not known to be kept on purpose",
+ };
+ }
+ if (!opts.containerPresent) return { ok: false, reason: `its container ${pointer.file} is not in the store` };
+ if (!probe) return { ok: false, reason: `ffprobe could not read ${pointer.file}` };
+ if (!probe.hasVideo) return { ok: false, reason: "no video stream (an audio-only container)" };
+ if (probe.vcodec && /^(av1|av01)/i.test(probe.vcodec)) return { ok: false, reason: "already AV1" };
+ if (!probe.seconds) return { ok: false, reason: "its length is unknown" };
+ const miss = selectorMiss(opts.platform, probe, s);
+ if (!miss) return { ok: true };
+ if (opts.mode === "select") return { ok: false, reason: miss };
+ // EXPLICITLY NAMED, NOT WHAT THE SELECTOR PICKS (ruling 9): not by accident.
+ return opts.belowThreshold
+ ? { ok: true, belowThreshold: miss }
+ : { ok: false, reason: `${miss}; named explicitly, it is compacted only with "belowThreshold": true`, belowThreshold: miss };
+}
+
+// Why the selector would not pick it, or null.
+function selectorMiss(platform: string | null, probe: CompactionProbe, s: SavedVideoCompactionSettings): string | null {
+ if (!platform || !s.platforms.includes(platform)) return `platform ${platform ?? "unknown"} is not selected`;
+ if (probe.height === null || probe.height < s.minHeight) return `${probe.height ?? "unknown "}p is below minHeight ${s.minHeight}`;
+ if (probe.videoKbps === null || probe.videoKbps < s.minVideoMbps * 1000) {
+ return `${probe.videoKbps === null ? "unknown" : (probe.videoKbps / 1000).toFixed(2)} Mbit/s video is below minVideoMbps ${s.minVideoMbps}`;
+ }
+ return null;
+}
+
+// The output frame rate: the cap when the source is above it on a capped
+// platform, else null (the source's own).
+export function targetFps(
+ sourceFps: number | null,
+ platform: string | null,
+ s: Pick<SavedVideoCompactionSettings, "maxFps" | "maxFpsPlatforms">,
+): number | null {
+ if (!s.maxFps || sourceFps === null || !platform || !s.maxFpsPlatforms.includes(platform)) return null;
+ return sourceFps > s.maxFps + 0.5 ? s.maxFps : null;
+}
+
+// --- the estimate -------------------------------------------------------------
+
+// MEASURED (design note §3, 13 Nov 2026, one Kick 1080p60 screen-share
+// sample, SVT-AV1 preset 8, against its H.264 source): the output video
+// bitrate as a share of the source's, by crf; 60 -> 30 fps at crf 36 was 0.44
+// against 0.64 at 60. Between the rows the share is interpolated. CRF output
+// follows the content, so the range around it is wide on purpose.
+const CRF_SHARE: [number, number][] = [
+ [32, 0.89],
+ [36, 0.64],
+ [40, 0.47],
+ [44, 0.36],
+];
+const HALF_FPS_FACTOR = 0.44 / 0.64;
+// Encode speed, × realtime, for 1080p60 at preset 8: 0.47 (a loaded machine,
+// crf 40) to 0.91 (crf 36) measured; 30 fps ran 1.17 / 0.91 = 1.29× faster.
+const SPEED_1080P60: [number, number] = [0.47, 0.91];
+const PIXEL_RATE_1080P60 = 1920 * 1080 * 60;
+
+export const ESTIMATE_RANGE: [number, number] = [0.8, 1.25];
+
+function crfShare(crf: number): number {
+ if (crf <= CRF_SHARE[0][0]) return CRF_SHARE[0][1];
+ for (let i = 1; i < CRF_SHARE.length; i += 1) {
+ const [c1, s1] = CRF_SHARE[i - 1];
+ const [c2, s2] = CRF_SHARE[i];
+ if (crf <= c2) return s1 + ((crf - c1) / (c2 - c1)) * (s2 - s1);
+ }
+ return CRF_SHARE[CRF_SHARE.length - 1][1];
+}
+
+export type CompactionEstimate = {
+ // Output bytes, [low, high].
+ bytes: [number, number];
+ // Encode hours, [fast, slow].
+ hours: [number, number];
+ share: number;
+};
+
+export function estimateCompaction(opts: {
+ probe: CompactionProbe;
+ crf: number;
+ fps: number | null;
+}): CompactionEstimate {
+ const { probe } = opts;
+ const seconds = probe.seconds ?? 0;
+ const srcFps = probe.fps ?? 30;
+ const outFps = opts.fps ?? srcFps;
+ const fpsFactor = outFps < srcFps ? Math.pow(outFps / srcFps, Math.log(HALF_FPS_FACTOR) / Math.log(0.5)) : 1;
+ const share = crfShare(opts.crf) * fpsFactor;
+ const videoKbps = probe.videoKbps ?? 0;
+ const point = ((videoKbps * share + (probe.audioKbps ?? 0)) * 1000 * seconds) / 8;
+ const pixels = (probe.width ?? 1920) * (probe.height ?? 1080) * outFps;
+ const scale = Math.min(4, PIXEL_RATE_1080P60 / Math.max(1, pixels));
+ const fast = SPEED_1080P60[1] * scale;
+ const slow = SPEED_1080P60[0] * scale;
+ return {
+ bytes: [Math.round(point * ESTIMATE_RANGE[0]), Math.round(point * ESTIMATE_RANGE[1])],
+ hours: [seconds / fast / 3600, seconds / slow / 3600],
+ share,
+ };
+}
+
+// The headroom a compaction needs on the store's disk: its chunks and the
+// muxed result side by side at the concat (≈ 2 × the output), less what the
+// chunks already hold, plus the playable copies' margin.
+export const COMPACTION_DISK_MARGIN_BYTES = 2 * 1024 ** 3;
+
+export function compactionFreeNeeded(estimateHighBytes: number, writtenBytes: number): number {
+ return Math.max(0, 2 * estimateHighBytes - writtenBytes) + COMPACTION_DISK_MARGIN_BYTES;
+}
+
+// --- names --------------------------------------------------------------------
+
+// The compacted copy's OWN name, never the original's: the backup mirror is
+// additive (rsync, no deletes), so a re-encode under `source-media.mp4` would
+// overwrite the backed-up original. No reader takes it for a source in a video
+// dir (lib/mediaFiles.ts anchors on `source-media.<ext>`): the pointer is the
+// only thing that names it.
+export function compactedFileName(at: Date, taken: Iterable<string> = [], ext = ".mp4"): string {
+ const stem = `source-media.compact-av1-${at.toISOString().replace(/\D/g, "").slice(0, 14)}`;
+ const names = new Set(taken);
+ let name = `${stem}${ext}`;
+ for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
+// The scratch dir a compaction works in: inside the video's own store dir, on
+// the store's drive (never /tmp, a RAM disk here, and never the corpus SSD).
+// Its state file is what a restart resumes from.
+export const COMPACTION_SCRATCH_DIRNAME = ".compact-scratch";
+export const COMPACTION_STATE_FILENAME = "state.json";
+
+export const COMPACTION_TOOL = "archilyzer compact-saved-videos 1";
+
+// The review list's states for a compacted video (`get compaction-review`).
+export type CompactionReviewState =
+ | "awaiting-review" // gone from its platform (or unknown), not reviewed: the original waits
+ | "reviewed" // reviewed; drop it with drop-saved-alternate confirmOriginal
+ | "kept" // dropOriginal "keep": the original stays until a person drops it
+ | "drop-pending" // on its platform under "after-verify": the drop step has not run or failed
+ | "dropped"; // the original is gone
+
+export const COMPACTION_REVIEW_STATE_LABELS: Record<CompactionReviewState, string> = {
+ "awaiting-review": "compacted, original awaiting review",
+ reviewed: "compacted, reviewed: the original may be dropped",
+ kept: "compacted, original kept (dropOriginal: keep)",
+ "drop-pending": "compacted, original not dropped yet",
+ dropped: "compacted, original dropped",
+};
diff --git a/common/lib/savedVideoOriginal.test.ts b/common/lib/savedVideoOriginal.test.ts
@@ -0,0 +1,496 @@
+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 { hostname, tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "./paths";
+import {
+ compactedLine,
+ compactedOriginalOf,
+ parseSavedVideoPointer,
+ savedAlternatesLine,
+} from "./savedVideo";
+import { writeCompactingMarker } from "./compactingMarker-server";
+import {
+ COMPACTING_MARKER_FILENAME,
+ CompactionInProgressError,
+ SavedAlternateRefusal,
+ dropSavedAlternate,
+ dropSavedVideo,
+ loadSavedVideo,
+ persistSourceVideo,
+ recordOriginalReview,
+ savedVideoPointerPath,
+ unpersistSavedVideo,
+ updateSavedVideoChecksum,
+} from "./savedVideo-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/savedVideoOriginal.test.ts
+//
+// A COMPACTED VIDEO'S POINTER (controller/compactSavedVideos.ts): the
+// `compacted` block and the original kept as `keptAs: "original"` parse back,
+// say "re-encode" wherever they are listed, and the original is deleted by
+// nothing but a confirmed drop — identified by its sha256, with the copy read
+// back from disk inside the drop, and for a video not freshly on its platform
+// a review of THIS copy.
+
+const ACTIVE = "source-media.compact-av1-20261114031209.mp4";
+const ORIGINAL = "source-media.mp4";
+const ACTIVE_BYTES = "av1!!";
+const ORIGINAL_BYTES = "o".repeat(1200);
+const sha = (s: string) => createHash("sha256").update(s).digest("hex");
+const SHA_ACTIVE = sha(ACTIVE_BYTES);
+const SHA_ORIGINAL = sha(ORIGINAL_BYTES);
+const READ_BACK = { probe: async () => ({ durationSec: 100, hasVideo: true }) };
+const ON = { onPlatform: true, why: "checked public" };
+const GONE = { onPlatform: false, why: "no availability record" };
+
+function compactedBlock(extra: Record<string, unknown> = {}) {
+ return {
+ at: "2026-11-14T03:12:09.000Z",
+ tool: "archilyzer compact-saved-videos 1",
+ encoder: "ffmpeg version n9.0.2",
+ settings: { codec: "av1", encoder: "libsvtav1", preset: 8, crf: 36, gopSeconds: 5, pixFmt: "yuv420p", fps: 30, audio: "copy", chunkSeconds: 600 },
+ source: { file: ORIGINAL, bytes: 1200, sha256: SHA_ORIGINAL, vcodec: "h264", height: 1080, fps: 60, seconds: 100 },
+ result: { file: ACTIVE, bytes: ACTIVE_BYTES.length, sha256: SHA_ACTIVE, vcodec: "av1", height: 1080, fps: 30, seconds: 100 },
+ checks: {
+ passed: true,
+ decoded: true,
+ seconds: [100, 100],
+ secondsTolerance: 0.034,
+ frames: [6000, 3000, 3000],
+ audio: "identical",
+ audioHash: "c".repeat(64),
+ quality: { metric: "vmaf", mean: 94.2, min: 91.9, samples: 12, minMean: 90, minSample: 85 },
+ cuts: [{ at: 10, ssim: 0.97 }],
+ cutSsimMin: 0.9,
+ clock: "none",
+ wholeFile: { fps: 2, width: 64, frames: 200, mean: 0.99, min: 0.97, worstAt: 12, minFloor: 0.9, meanFloor: 0.97, maxGapSeconds: 0.033 },
+ },
+ chunks: 1,
+ ...extra,
+ };
+}
+
+type Fixture = { paths: Paths; videoDir: string; storeDir: string };
+
+async function withCompacted(fn: (f: Fixture) => Promise<void>): Promise<void> {
+ const root = await mkdtemp(path.join(tmpdir(), "compacted-original-"));
+ const paths = {
+ transcriptsDir: root,
+ channelsDir: path.join(root, "channels"),
+ savedVideosDir: path.join(root, "saved-videos"),
+ } as Paths;
+ const videoDir = path.join(paths.channelsDir, "kick", "data", "v1");
+ const storeDir = path.join(paths.savedVideosDir, "kick", "v1");
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(storeDir, { recursive: true });
+ await writeFile(path.join(storeDir, ACTIVE), ACTIVE_BYTES);
+ await writeFile(path.join(storeDir, ORIGINAL), ORIGINAL_BYTES);
+ const pointer = {
+ storedAt: "2026-11-01T00:00:00.000Z",
+ dir: storeDir,
+ file: ACTIVE,
+ bytes: ACTIVE_BYTES.length,
+ sha256: SHA_ACTIVE,
+ keepReason: "pin",
+ format: { preset: "original", height: 1080, vcodec: "av1" },
+ compacted: compactedBlock(),
+ alternates: [
+ {
+ file: ORIGINAL,
+ bytes: 1200,
+ storedAt: "2026-11-01T00:00:00.000Z",
+ setAsideAt: "2026-11-14T03:12:09.000Z",
+ height: 1080,
+ vcodec: "h264",
+ keptAs: "original",
+ sha256: SHA_ORIGINAL,
+ },
+ ],
+ };
+ await writeFile(savedVideoPointerPath(videoDir), JSON.stringify(pointer, null, 2) + "\n");
+ try {
+ await fn({ paths, videoDir, storeDir });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+const readRaw = async (videoDir: string) => JSON.parse(await readFile(savedVideoPointerPath(videoDir), "utf8"));
+const writeRaw = (videoDir: string, raw: unknown) => writeFile(savedVideoPointerPath(videoDir), JSON.stringify(raw));
+const CONFIRM = { confirmOriginal: true, readBack: READ_BACK } as const;
+const liveMarker = (storeDir: string) => writeCompactingMarker(storeDir);
+
+test("a pointer without `compacted` parses exactly as before", () => {
+ const raw = { storedAt: "x", dir: "/s", file: "source-media.mp4", bytes: 3, keepReason: "pin" };
+ assert.deepEqual(parseSavedVideoPointer(raw), raw);
+ assert.equal(compactedLine(parseSavedVideoPointer(raw)!), null);
+});
+
+test("the compacted block and the original parse back, and every line says re-encode", () => {
+ const p = parseSavedVideoPointer({
+ storedAt: "x",
+ dir: "/s",
+ file: ACTIVE,
+ bytes: 4_900_000_000,
+ compacted: compactedBlock({ source: { file: ORIGINAL, bytes: 12_300_000_000, sha256: SHA_ORIGINAL, vcodec: "h264", height: 1080, fps: 60 } }),
+ alternates: [{ file: ORIGINAL, bytes: 12_300_000_000, storedAt: "", setAsideAt: "", keptAs: "original", sha256: SHA_ORIGINAL }],
+ })!;
+ assert.equal(p.compacted?.checks.passed, true);
+ assert.equal(p.compacted?.checks.wholeFile?.min, 0.97);
+ assert.equal(compactedOriginalOf(p)?.file, ORIGINAL);
+ const line = compactedLine(p)!;
+ assert.match(line, /^Re-encoded copy \(AV1 crf 36, 1080p30 from 60 fps, audio copied\) of a 11\.46 GB H\.264 original — 4\.56 GB, 2026-11-14\./);
+ assert.match(line, /The original is kept beside it \(source-media\.mp4\)\./);
+ const alts = savedAlternatesLine(p);
+ assert.match(alts, /active .*a re-encode \(AV1 crf 36\)/);
+ assert.match(alts, /the original the active copy was re-encoded from, kept until it is dropped/);
+});
+
+test("the original is found by its sha256, never by position", () => {
+ const p = parseSavedVideoPointer({
+ storedAt: "x",
+ dir: "/s",
+ file: ACTIVE,
+ bytes: 3,
+ compacted: compactedBlock(),
+ alternates: [
+ { file: "source-media.alt-1080p-1.mp4", bytes: 1, storedAt: "", setAsideAt: "", keptAs: "original", sha256: "f".repeat(64) },
+ { file: ORIGINAL, bytes: 1200, storedAt: "", setAsideAt: "", keptAs: "original", sha256: SHA_ORIGINAL },
+ ],
+ })!;
+ assert.equal(compactedOriginalOf(p)?.file, ORIGINAL);
+});
+
+test("a damaged compacted block still reads as a re-encode, its checks as not passed, its audio as unknown", () => {
+ const p = parseSavedVideoPointer({ storedAt: "x", dir: "/s", file: ACTIVE, bytes: 3, compacted: { at: 7, checks: "?" } })!;
+ assert.ok(p.compacted);
+ assert.equal(p.compacted.checks.passed, false);
+ assert.equal(p.compacted.checks.audio, "unknown");
+ assert.match(compactedLine(p)!, /^Re-encoded copy/);
+});
+
+test("an original is not dropped without confirmOriginal", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { presence: ON, readBack: READ_BACK }),
+ (e: Error) => e instanceof SavedAlternateRefusal && /ORIGINAL .*confirmOriginal/.test(e.message),
+ );
+ await stat(path.join(storeDir, ORIGINAL));
+ });
+});
+
+test("the drop reads the compacted copy back itself: a copy whose bytes changed keeps the original", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ // Same size, other bytes on disk: the default hasher reads the disk.
+ await writeFile(path.join(storeDir, ACTIVE), "av1??");
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON }), /did not read back from disk .*sha256/);
+ await stat(path.join(storeDir, ORIGINAL));
+ // A hasher that disagrees, a container that does not open: kept too.
+ await writeFile(path.join(storeDir, ACTIVE), ACTIVE_BYTES);
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, presence: ON, readBack: { ...READ_BACK, hasher: async () => "0".repeat(64) } }),
+ /did not read back/,
+ );
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, presence: ON, readBack: { probe: async () => null } }),
+ /does not open as a video/,
+ );
+ await stat(path.join(storeDir, ORIGINAL));
+ // A dry run answers without reading back.
+ const dry = await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, presence: ON, dryRun: true });
+ assert.equal(dry.dryRun, true);
+ });
+});
+
+test("an alternate labelled original whose sha256 is not the compacted copy's source is never dropped", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ const raw = await readRaw(videoDir);
+ raw.alternates[0].sha256 = "e".repeat(64);
+ await writeRaw(videoDir, raw);
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON }), /is not the original the compacted copy was made from/);
+ await stat(path.join(storeDir, ORIGINAL));
+ });
+ await withCompacted(async ({ videoDir }) => {
+ const raw = await readRaw(videoDir);
+ delete raw.compacted;
+ await writeRaw(videoDir, raw);
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON }), /active copy is not a compacted re-encode/);
+ });
+});
+
+test("a video not known to be on its platform keeps its original until a review of THIS copy is recorded", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: GONE }),
+ /not known to be on its platform \(no availability record\).*Review the copy that stays first/,
+ );
+ // With no availability record on disk at all, the default reads it as gone.
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, CONFIRM), /not known to be on its platform \(no availability record/);
+ await stat(path.join(storeDir, ORIGINAL));
+ const reviewed = await recordOriginalReview(videoDir, { at: "2026-11-20T10:00:00.000Z", by: "editor", note: "watched it" });
+ assert.equal(reviewed.review?.forSha256, SHA_ACTIVE);
+ const r = await dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: GONE, by: "test" });
+ assert.equal(r.existed, true);
+ await assert.rejects(stat(path.join(storeDir, ORIGINAL)));
+ const raw = await readRaw(videoDir);
+ assert.equal(raw.alternates, undefined);
+ assert.equal(raw.compacted.originalDropped.by, "test");
+ assert.equal(raw.compacted.originalDropped.sha256, SHA_ORIGINAL);
+ assert.equal(raw.compacted.originalDropped.bytes, 1200);
+ assert.equal(raw.compacted.originalDropped.fileRemoved, true);
+ assert.match(compactedLine((await loadSavedVideo(videoDir))!)!, /The original was dropped on 20\d\d-\d\d-\d\d \(sha256 [0-9a-f]{12}…, 1200 bytes\)/);
+ });
+});
+
+test("a fresh, first-hand check is what counts as on the platform: a backfilled or old public is unknown", async () => {
+ await withCompacted(async ({ videoDir }) => {
+ const write = (rec: unknown) => writeFile(path.join(videoDir, "availability.json"), JSON.stringify(rec));
+ const now = new Date().toISOString();
+ await write({ checkedAt: now, availability: "public", checkedBy: "backfill" });
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, CONFIRM), /was not read by a check of the platform \(backfill\)/);
+ await write({ checkedAt: now, availability: "public" });
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, CONFIRM), /was not read by a check of the platform/);
+ await write({ checkedAt: "2026-01-01T00:00:00.000Z", availability: "public", checkedBy: "check" });
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, CONFIRM), /older than 7 day\(s\).*Check availability/);
+ await write({ checkedAt: now, availability: "needs_auth", checkedBy: "check" });
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, CONFIRM), /its check says needs_auth/);
+ await write({ checkedAt: now, availability: "public", checkedBy: "check" });
+ await dropSavedAlternate(videoDir, ORIGINAL, CONFIRM);
+ });
+});
+
+test("a review of another copy counts for nothing", async () => {
+ await withCompacted(async ({ videoDir }) => {
+ await recordOriginalReview(videoDir, { at: "2026-11-20T10:00:00.000Z", by: "editor" });
+ const raw = await readRaw(videoDir);
+ raw.alternates[0].review.forSha256 = "1".repeat(64);
+ await writeRaw(videoDir, raw);
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: GONE }), /review is for another copy/);
+ });
+});
+
+test("recordOriginalReview refuses a pointer with no compacted block", async () => {
+ await withCompacted(async ({ videoDir }) => {
+ const raw = await readRaw(videoDir);
+ delete raw.compacted;
+ await writeRaw(videoDir, raw);
+ await assert.rejects(recordOriginalReview(videoDir, { at: "x", by: "editor" }), /not a compacted re-encode/);
+ });
+});
+
+test("a video on its platform drops its original with confirm and the read-back, no review needed", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON });
+ await assert.rejects(stat(path.join(storeDir, ORIGINAL)));
+ await stat(path.join(storeDir, ACTIVE));
+ });
+});
+
+test("no drop while a download or persist of the video runs, nor while it is being compacted", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await assert.rejects(
+ dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON, busy: () => "a persist-videos job (running, j1) may write this video's saved copy" }),
+ /is kept: a persist-videos job/,
+ );
+ await liveMarker(storeDir);
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON }), (e: Error) => e instanceof CompactionInProgressError);
+ await stat(path.join(storeDir, ORIGINAL));
+ });
+});
+
+test("the drop writes the pointer first; an interrupted drop is seen and finished when asked again", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ // The state a crash between the pointer write and the rm leaves.
+ const raw = await readRaw(videoDir);
+ delete raw.alternates;
+ raw.compacted.originalDropped = { at: "2026-11-20T00:00:00.000Z", by: "x", file: ORIGINAL, bytes: 1200, sha256: SHA_ORIGINAL, fileRemoved: false };
+ raw.pendingDrops = [{ file: ORIGINAL, at: "2026-11-20T00:00:00.000Z", keptAs: "original", sha256: SHA_ORIGINAL }];
+ await writeRaw(videoDir, raw);
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { presence: ON }), /drop was interrupted: finish it with "confirmOriginal": true/);
+ const r = await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true });
+ assert.equal(r.existed, true);
+ await assert.rejects(stat(path.join(storeDir, ORIGINAL)));
+ assert.equal((await readRaw(videoDir)).compacted.originalDropped.fileRemoved, true);
+ });
+});
+
+test("an original whose compacted copy's checks did not pass is never dropped, nor reviewed", async () => {
+ await withCompacted(async ({ videoDir }) => {
+ const raw = await readRaw(videoDir);
+ raw.compacted.checks.passed = false;
+ await writeRaw(videoDir, raw);
+ await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: ON }), /checks did not pass/);
+ await assert.rejects(recordOriginalReview(videoDir, { at: "x", by: "editor" }), /checks did not pass/);
+ });
+});
+
+test("dropSavedVideo (the prune's delete) refuses a video that keeps an original", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await assert.rejects(dropSavedVideo(videoDir), (e: Error) => e instanceof SavedAlternateRefusal);
+ await stat(path.join(storeDir, ORIGINAL));
+ await stat(path.join(storeDir, ACTIVE));
+ assert.ok(await loadSavedVideo(videoDir));
+ });
+});
+
+test("unpersist brings every copy back with the original as the source; refused once the original is gone", async () => {
+ await withCompacted(async ({ videoDir }) => {
+ assert.equal(await unpersistSavedVideo(videoDir), true);
+ assert.equal(await readFile(path.join(videoDir, ORIGINAL), "utf8"), ORIGINAL_BYTES);
+ await stat(path.join(videoDir, ACTIVE));
+ });
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ const raw = await readRaw(videoDir);
+ delete raw.alternates;
+ await writeRaw(videoDir, raw);
+ await rm(path.join(storeDir, ORIGINAL));
+ await assert.rejects(unpersistSavedVideo(videoDir), /re-encode .*original was dropped/);
+ assert.ok(await loadSavedVideo(videoDir));
+ await stat(path.join(storeDir, ACTIVE));
+ });
+});
+
+test("a persist over a compacted copy moves the original aside, re-labels it, and nothing can drop it automatically", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await writeFile(path.join(videoDir, ORIGINAL), "a new download");
+ const p = await persistSourceVideo({ videoDir, sourceFilename: ORIGINAL, storeDir, keepReason: "override" });
+ assert.equal(p.file, ORIGINAL);
+ assert.equal(p.compacted, undefined);
+ assert.equal(await readFile(path.join(storeDir, ORIGINAL), "utf8"), "a new download");
+ const kept = p.alternates?.find((a) => a.sha256 === SHA_ORIGINAL);
+ assert.ok(kept && kept.file !== ORIGINAL && /^source-media\.alt-1080p-\d{14}\.mp4$/.test(kept.file), kept?.file);
+ // No longer "the original the active copy was re-encoded from".
+ assert.equal(kept.keptAs, "former-original");
+ assert.match(savedAlternatesLine(p), /an original of an earlier compacted copy .*kept until a person drops it/);
+ assert.equal(compactedOriginalOf(p), null);
+ assert.equal(await readFile(path.join(storeDir, kept.file), "utf8"), ORIGINAL_BYTES);
+ assert.ok((await readdir(storeDir)).includes(ACTIVE));
+ // Never by the prune, never without a person's confirm.
+ await assert.rejects(dropSavedVideo(videoDir), /keeps an original/);
+ await assert.rejects(dropSavedAlternate(videoDir, kept.file, { presence: ON }), /ORIGINAL of an earlier compacted copy/);
+ });
+});
+
+test("a persist of a video being compacted is refused, its container left where it was; a stale marker is not", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await liveMarker(storeDir);
+ await writeFile(path.join(videoDir, "source-media.webm"), "dl");
+ await assert.rejects(
+ persistSourceVideo({ videoDir, sourceFilename: "source-media.webm", storeDir }),
+ (e: Error) => e instanceof CompactionInProgressError && /being compacted/.test(e.message),
+ );
+ await stat(path.join(videoDir, "source-media.webm"));
+ // A marker whose process is gone is stale.
+ await writeFile(path.join(storeDir, COMPACTING_MARKER_FILENAME), JSON.stringify({ pid: 2 ** 22 + 7, host: hostname(), startedAt: "x" }));
+ await persistSourceVideo({ videoDir, sourceFilename: "source-media.webm", storeDir });
+ });
+});
+
+test("a checksum is written only while the pointer names the file that was hashed", async () => {
+ await withCompacted(async ({ videoDir }) => {
+ await updateSavedVideoChecksum(videoDir, "d".repeat(64), ORIGINAL);
+ assert.equal((await readRaw(videoDir)).sha256, SHA_ACTIVE);
+ await updateSavedVideoChecksum(videoDir, "e".repeat(64), ACTIVE);
+ const raw = await readRaw(videoDir);
+ assert.equal(raw.sha256, "e".repeat(64));
+ assert.ok(raw.compacted, "the rest of the pointer is kept");
+ });
+});
+
+// --- review round 2 ------------------------------------------------------------
+
+async function makeFormer(videoDir: string, storeDir: string): Promise<string> {
+ // A download of another container extension lands: no rename, the original relabelled.
+ await writeFile(path.join(videoDir, "source-media.mkv"), "a new download");
+ const p = await persistSourceVideo({ videoDir, sourceFilename: "source-media.mkv", storeDir, keepReason: "pin" });
+ const former = p.alternates!.find((a) => a.sha256 === SHA_ORIGINAL)!;
+ assert.equal(former.keptAs, "former-original");
+ assert.equal(former.file, ORIGINAL);
+ return former.file;
+}
+
+test("F1: the after-verify drop names exactly what it means; a re-labelled original is not dropped", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ const captured = compactedOriginalOf((await loadSavedVideo(videoDir))!)!;
+ await makeFormer(videoDir, storeDir);
+ await assert.rejects(
+ dropSavedAlternate(videoDir, captured.file, {
+ confirmOriginal: true,
+ expect: { keptAs: "original", sha256: SHA_ORIGINAL, file: captured.file },
+ presence: ON,
+ busy: () => null,
+ readBack: READ_BACK,
+ }),
+ /not what this drop expected \(original, .*it is former-original, .*nothing dropped/,
+ );
+ await stat(path.join(storeDir, ORIGINAL));
+ // Even without `expect`, confirmOriginal alone never drops a former original.
+ await assert.rejects(dropSavedAlternate(videoDir, captured.file, { ...CONFIRM, presence: ON }), /pass "confirmFormerOriginal": true/);
+ await stat(path.join(storeDir, ORIGINAL));
+ });
+});
+
+test("F1: a former original is dropped only with confirmFormerOriginal and the same gone/review rule", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ const file = await makeFormer(videoDir, storeDir);
+ await assert.rejects(
+ dropSavedAlternate(videoDir, file, { confirmFormerOriginal: true, presence: GONE }),
+ /not known to be on its platform .*Review the copy that stays first/,
+ );
+ // The review is of the active copy that replaced it: it needs that copy's sha256.
+ await assert.rejects(recordOriginalReview(videoDir, { at: "x", by: "editor" }, { formerOriginal: file }), /no recorded sha256/);
+ await updateSavedVideoChecksum(videoDir, sha("a new download"), "source-media.mkv");
+ const r = await recordOriginalReview(videoDir, { at: "2026-11-20T00:00:00.000Z", by: "editor" }, { formerOriginal: file });
+ assert.equal(r.review?.forSha256, sha("a new download"));
+ await dropSavedAlternate(videoDir, file, { confirmFormerOriginal: true, presence: GONE });
+ await assert.rejects(stat(path.join(storeDir, ORIGINAL)));
+ });
+});
+
+test("F1: no automatic step passes confirmFormerOriginal (a scan of every caller)", async () => {
+ const roots = ["controller", "lib", "jobs", "ytdlp", "bin"].map((d) => path.join(import.meta.dirname, "..", d));
+ const editorApp = path.join(import.meta.dirname, "..", "..", "editor", "app");
+ // The flag's definition, and the person-driven ways in: the drop button, the
+ // ops route, the server action that both call.
+ const allowed = new Set([
+ path.join(import.meta.dirname, "savedVideo-server.ts"),
+ path.join(editorApp, "api", "ops", "drop-saved-alternate", "route.ts"),
+ path.join(editorApp, "channels", "[slug]", "videos", "[id]", "videoActions.ts"),
+ path.join(editorApp, "channels", "[slug]", "videos", "[id]", "components", "cards", "SourceVideoSection.tsx"),
+ ]);
+ const found: string[] = [];
+ const walk = async (d: string): Promise<void> => {
+ for (const e of await readdir(d, { withFileTypes: true }).catch(() => [])) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) {
+ if (e.name !== "node_modules" && !e.name.startsWith(".")) await walk(p);
+ } else if (/\.(ts|tsx|mjs)$/.test(e.name) && !/\.test\./.test(e.name)) {
+ if ((await readFile(p, "utf8")).includes("confirmFormerOriginal")) found.push(p);
+ }
+ }
+ };
+ for (const r of [...roots, editorApp]) await walk(r);
+ assert.deepEqual(found.filter((f) => !allowed.has(f)), [], "an unexpected caller names confirmFormerOriginal");
+ const compactor = await readFile(path.join(import.meta.dirname, "..", "controller", "compactSavedVideos.ts"), "utf8");
+ assert.ok(!compactor.includes("confirmFormerOriginal"));
+ assert.match(compactor, /expect: \{ keptAs: "original", sha256: pointer\.compacted!\.source\.sha256, file: original\.file \}/);
+});
+
+test("an interrupted drop of an ordinary alternate is listed and finished by asking again", async () => {
+ await withCompacted(async ({ videoDir, storeDir }) => {
+ await writeFile(path.join(storeDir, "source-media.alt-360p-1.mp4"), "alt");
+ const raw = await readRaw(videoDir);
+ // The state a crash between the pointer write and the rm leaves.
+ raw.pendingDrops = [{ file: "source-media.alt-360p-1.mp4", at: "2026-11-20T00:00:00.000Z" }];
+ await writeRaw(videoDir, raw);
+ assert.equal((await loadSavedVideo(videoDir))!.pendingDrops?.[0].file, "source-media.alt-360p-1.mp4");
+ const r = await dropSavedAlternate(videoDir, "source-media.alt-360p-1.mp4");
+ assert.equal(r.existed, true);
+ await assert.rejects(stat(path.join(storeDir, "source-media.alt-360p-1.mp4")));
+ assert.equal((await readRaw(videoDir)).pendingDrops, undefined);
+ });
+});
diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts
@@ -223,6 +223,10 @@ export async function cutSavedVideoWindow(opts: {
// When the window landed — for a cut, when it was cut.
fetchedAt: now,
source: "saved-video",
+ // A cut from a compacted copy says it is one generation further on.
+ ...(source.pointer.compacted
+ ? { fromReencode: { file: source.pointer.file, originalSha256: source.pointer.compacted.source.sha256 } }
+ : {}),
...(height !== null ? { height } : {}),
...(mapped && source.clock
? {
@@ -245,7 +249,7 @@ export async function cutSavedVideoWindow(opts: {
opts.onLog?.(
`Cut ${from.toFixed(2)}–${to.toFixed(2)}${onClock} from the saved video ${source.pointer.file} into ` +
`clips/${clipWindowFile(from, to, tier)} (${bytes} bytes` +
- `${height !== null ? `, ${height}p` : ""}); nothing fetched.\n`,
+ `${height !== null ? `, ${height}p` : ""}${source.pointer.compacted ? ", from the compacted re-encode" : ""}); nothing fetched.\n`,
);
return {
file: clipWindowFile(from, to, tier),
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/common/ytdlp/finalizeAppExtraction.ts b/common/ytdlp/finalizeAppExtraction.ts
@@ -162,6 +162,7 @@ export async function finalizeAppExtraction(opts: {
origin: opts.origin,
format: opts.format,
...(opts.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}),
+ ...(opts.explicitPersist ? { explicit: true } : {}),
paths: opts.paths,
deps: alternatesDeps,
onLog: opts.onLog,
@@ -173,6 +174,9 @@ export async function finalizeAppExtraction(opts: {
keepReason,
origin: opts.origin,
...(opts.format ? { format: opts.format } : {}),
+ // A person or an explicit action asked for it: what tells an
+ // explicit persist from persist-kept's "override" (savedVideo.ts).
+ ...(opts.explicitPersist ? { explicit: true } : {}),
// The store-in-transition guard. A move of the saved-video store is a
// multi-hour copy, and a container landing in the middle of it is lost
// three different ways — see lib/savedVideoStore.ts. The catch below is
diff --git a/common/ytdlp/savedAlternates.ts b/common/ytdlp/savedAlternates.ts
@@ -38,6 +38,9 @@
// page's "Drop this alternate" — deletes one listed alternate and its pointer
// entry, never the active copy. Nothing else deletes one but `dropSavedVideo`
// (the whole video) and `unpersistSavedVideo` (which brings them back).
+// An ORIGINAL (`keptAs: "original"`, the source of a compacted copy —
+// controller/compactSavedVideos.ts) goes only by a confirmed
+// dropSavedAlternate: dropSavedVideo refuses a video that keeps one.
//
// Audio is not part of this: the landed guard's audio half still keeps the
// longer audio.<fmt> (a transcript was made from it), as before.
@@ -54,9 +57,14 @@ import {
type SavedVideoProbe,
} from "../lib/savedVideo";
import {
+ SavedPointerChangedError,
+ alternateName,
+ assertNotCompacting,
loadSavedVideo,
moveFileCrossDevice,
- persistSourceVideo,
+ persistSourceVideoUnlocked,
+ samePointerCopy,
+ withPointerLock,
writePointer,
} from "../lib/savedVideo-server";
import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore";
@@ -127,19 +135,9 @@ export async function planSavedContainer(opts: {
};
}
-function stampOf(at: Date): string {
- return at.toISOString().replace(/\D/g, "").slice(0, 14);
-}
-
-// `source-media.alt-<h>p-<stamp>.<ext>`, unique in `taken`.
-export function alternateName(file: string, height: number | null, at: Date, taken: Iterable<string> = []): string {
- const ext = path.extname(file);
- const stem = `source-media.alt-${height ? `${height}p-` : ""}${stampOf(at)}`;
- const names = new Set(taken);
- let name = `${stem}${ext}`;
- for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
- return name;
-}
+// `source-media.alt-<h>p-<stamp>.<ext>`, unique in `taken` (lib/savedVideo-server.ts:
+// persistSourceVideo moves an alternate aside under the same kind of name).
+export { alternateName };
function describe(height: number | null, seconds: number | null): string {
return `${height ? `${height}p` : "height unknown"}, ${seconds !== null ? `${seconds.toFixed(1)} s` : "length unknown"}`;
@@ -179,7 +177,31 @@ export async function keepDownloadAsAlternate(
onLog: (s: string) => void;
},
): Promise<string> {
- const { existing, videoDir } = plan;
+ // UNDER THE POINTER'S LOCK, ON THE POINTER AS IT IS NOW: the plan was made
+ // before the extraction (minutes), and a compaction or another persist may
+ // have swapped the active copy since. Then this refuses rather than write
+ // the plan's older pointer back over the new one.
+ return withPointerLock(plan.videoDir, () => keepDownloadAsAlternateLocked(plan, opts));
+}
+
+async function currentFor(plan: SavedContainerPlan, what: string): Promise<SavedVideoPointer> {
+ const now = await loadSavedVideo(plan.videoDir);
+ if (!now || !samePointerCopy(now, plan.existing)) {
+ throw new SavedPointerChangedError(
+ `${what} refused: the saved copy changed since this download was planned ` +
+ `(${plan.existing.file} then, ${now ? now.file : "no pointer"} now). The download stays in the data dir; run it again.`,
+ );
+ }
+ await assertNotCompacting(now.dir, what);
+ return now;
+}
+
+async function keepDownloadAsAlternateLocked(
+ plan: SavedContainerPlan,
+ opts: Parameters<typeof keepDownloadAsAlternate>[1],
+): Promise<string> {
+ const { videoDir } = plan;
+ const existing = await currentFor(plan, "Keeping the download as an alternate");
if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, existing.dir);
const at = opts.deps.now?.() ?? new Date();
const src = path.join(videoDir, opts.sourceFilename);
@@ -228,14 +250,24 @@ export async function persistOverExisting(
format?: SavedVideoFormat | null;
// Mark the old copy as the proxy when the download is taller (see top).
oldCopyAsProxy?: boolean;
+ // An explicit persist (SavedVideoPointer.explicit).
+ explicit?: boolean;
paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
deps: SavedAlternatesDeps;
onLog: (s: string) => void;
},
): Promise<SavedVideoPointer> {
+ return withPointerLock(plan.videoDir, () => persistOverExistingLocked(plan, opts));
+}
+
+async function persistOverExistingLocked(
+ plan: SavedContainerPlan,
+ opts: Parameters<typeof persistOverExisting>[1],
+): Promise<SavedVideoPointer> {
const { videoDir } = plan;
- // Re-read: an extraction ran since the plan.
- const old = (await loadSavedVideo(videoDir)) ?? plan.existing;
+ // Re-read under the lock: an extraction ran since the plan, and the active
+ // copy must still be the one the plan measured.
+ const old = await currentFor(plan, "Persisting the download over the saved copy");
if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, old.dir);
const at = opts.deps.now?.() ?? new Date();
const alt = alternateName(old.file, plan.oldHeight, at, await readdir(old.dir).catch(() => []));
@@ -243,7 +275,7 @@ export async function persistOverExisting(
const keptOrigin = old.origin && !LANDED_BY.has(old.origin.requestedBy) ? old.origin : undefined;
let pointer: SavedVideoPointer;
try {
- pointer = await persistSourceVideo({
+ pointer = await persistSourceVideoUnlocked({
videoDir,
sourceFilename: opts.sourceFilename,
storeDir: old.dir,
@@ -251,6 +283,7 @@ export async function persistOverExisting(
keepReason: old.keepReason ?? opts.keepReason,
origin: opts.origin ?? keptOrigin,
...(opts.format ? { format: opts.format } : {}),
+ ...(opts.explicit || old.explicit ? { explicit: true } : {}),
...(opts.paths ? { paths: opts.paths } : {}),
});
} catch (err) {
@@ -279,6 +312,9 @@ export async function persistOverExisting(
...(old.origin ? { origin: old.origin } : {}),
...(old.format?.preset ? { preset: old.format.preset } : {}),
...(proxy ? { keptAs: "proxy" as const } : {}),
+ // The copy set aside was itself a re-encode (a compacted active copy):
+ // it says so wherever it is listed.
+ ...(old.compacted ? { compactedFrom: old.compacted.source.sha256, ...(old.sha256 ? { sha256: old.sha256 } : {}) } : {}),
},
],
};
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -96,6 +96,56 @@
- `umtool vertical`'s form now offers `--landscape`.
- `umtool vertical` and `umtool shorts` now read the project's fetched windows for a draft take that was never
rendered, as a made take does. Before, such a take found no window unless the corpus had one.
+- **umtool: the diet strip, the promise clock and the other layers are no longer drawn over a teaser, the brand
+ intro or a full-frame card.** The deck already slid away over them, but the measure extras, the side panels, the
+ chapters and the finale's pages stayed on screen over the teaser's card. Now they are left out over every item that
+ takes the whole frame, as they already were over a video entry and an analysis item.
+ - Full frame: a teaser (unless it counts: marks and no dip), the brand intro, an analysis item, a video entry
+ (unless `deck: "shown"`), and a card, scroll, chart or ledger under `deck.overCards: "hide"` (the default).
+ - Those layers go at the first frame of the item's dissolve in, or, for a teaser that dips, at the frame the dip has
+ made black. They are back on the last frame of its dissolve out, which shows only the next clip.
+ - The deck, the dial, the odometer, the trail and the feed are laid as before: they keep their own slide away and
+ back.
+ - The finale's pages finish their fade out through the dissolve into the item. A teaser that carries marks keeps
+ its stamps.
+ - A chapter bumper on the clip after such an item starts once the item has gone, so its entrance plays whole.
+ - Play the cut hides the same layers while such an item is on screen.
+ - A cut with none of these items is laid exactly as before. The change is in how the overlays are laid (and, after
+ such an item, in a chapter's window): other cached chrome frames are reused.
+- **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}`, which is a dry run unless it says
+ `"dryRun": false`) 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). Every other stream and the chapters are
+ 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, length, frames, gaps and the
+ picture's start against the sound, identical audio packets, every stream present, a whole-file comparison at
+ 2 frames a second, VMAF across every chunk join and inside every chunk, frame-exact windows cut through the
+ evidence cutter, and the recording clock. The original stays beside it as `"keptAs": "original"`, known by its
+ sha256.
+ - The original is kept by default (`dropOriginal: "keep"`). Under `"after-verify"` it is dropped in a later step,
+ after the copy is read back from disk. That needs the whole-file comparison, no download of the video queued or
+ running, and a fresh, first-hand availability check (`availabilityMaxAgeDays`, 7). A video without one waits for
+ a person's review of that copy (`get compaction-review` gives an `smplayer` command for both files). There is no
+ backup of the store: after a drop the compacted copy is the only copy.
+ - A video named explicitly that the selector would not pick needs `"belowThreshold": true`; the refusal says how
+ little it would save. persist-kept's `keepReason: "override"` is not "deliberately stored": an explicit persist
+ now records `explicit` on its pointer.
+ - `drop-saved-alternate` drops an original only with `"confirmOriginal": true`, and re-reads the compacted copy
+ itself. Nothing else deletes one: the prune keeps the video, unpersist brings the original back, and a persist,
+ attach or import over a compacted copy moves the original aside as `"former-original"`, which nothing drops
+ automatically.
+ - Saved-video pointer writes now go under the pointer's lock and re-read it there. A download planned before a
+ compaction refuses to write over it, and a persist of a video being compacted waits for a re-run.
+ - A channel opts out with `excludeFromCompaction`. There is no lane: it runs only when asked.
+ - The whole-file comparison scores EVERY frame, whole and in an 8×8 grid of tiles, against a hard floor, the
+ file's own spread and a tile floor held for more than 2 frames. The after-verify drop names exactly the original
+ it means. A former original needs its own `"confirmFormerOriginal": true`. The `.compacting.json` marker is held
+ through the drop and checked against boot, host, pid start time and job. Stale ones are swept, and listed or
+ cleared with `compaction-markers`. The prune goes on past a video it may not drop. An interrupted drop of any
+ alternate is listed (`pendingDrops`) and finished by asking again.
+ - **ROLLBACK: do not roll the editor back past this release while `pnpm ops get kept-originals` lists anything.**
+ An older editor does not know `"keptAs": "original"` / `"former-original"`, would treat them as ordinary
+ alternates, and could prune or drop the only original.
- **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/media/fetch-window/[jobId]/route.ts b/editor/app/api/media/fetch-window/[jobId]/route.ts
@@ -9,7 +9,7 @@ import { getJobEntry, readLogChunk } from "yt-dlp-transcript-common/jobs/listJob
import { clipWindowPath } from "yt-dlp-transcript-common/lib/clipWindow-server";
import { clipWindowSidecar } from "yt-dlp-transcript-common/lib/clipWindow";
import { loadSavedVideo } from "yt-dlp-transcript-common/lib/savedVideo-server";
-import { savedVideoPath } from "yt-dlp-transcript-common/lib/savedVideo";
+import { compactedLine, savedVideoPath } from "yt-dlp-transcript-common/lib/savedVideo";
export const dynamic = "force-dynamic";
@@ -94,6 +94,8 @@ export async function GET(
if (pointer?.format?.height !== undefined) {
out.height = pointer.format.height;
}
+ // A whole recording that is a compacted RE-ENCODE says so.
+ if (pointer?.compacted) out.reencode = compactedLine(pointer) ?? "a re-encoded copy";
}
if (file) {
const st = await stat(file).catch(() => null);
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,80 @@
+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);
+});
+
+test("the selector is a dry run unless it says dryRun: false; a named video below the selector needs belowThreshold", async () => {
+ const before = await readdir(ROOT, { recursive: true });
+ const s = await post({ select: true });
+ assert.equal(s.status, 200, JSON.stringify(s.json));
+ assert.equal(s.json.dryRun, true);
+ assert.deepEqual((await readdir(ROOT, { recursive: true })).sort(), before.sort());
+ // The keep-latest container is refused whatever the flags say.
+ const r = await post({ items: [{ slug: "kick", id: "aaaaaaaaaaa" }], belowThreshold: true });
+ assert.equal(r.status, 400);
+ assert.match(r.json.error!, /Nothing to compact — kick\/aaaaaaaaaaa: .*keep-latest/);
+});
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,71 @@
+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?, belowThreshold?, 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.
+//
+// `{"select": true}` IS A DRY RUN unless the body says `"dryRun": false`; an
+// explicit list keeps the usual default (a real run). An explicit item the
+// selector would not pick (YouTube, below the bitrate or height floors) is
+// refused — the refusal and the dry run say how little it would save — unless
+// `"belowThreshold": true`. The deliberately-stored rule has no override.
+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", "belowThreshold", "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") } : {}),
+ // The selector's default is a dry run: a real one is asked by name.
+ dryRun: optBool(body, "dryRun") ?? select,
+ retryFailed: optBool(body, "retryFailed") ?? false,
+ belowThreshold: optBool(body, "belowThreshold") ?? 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-markers/route.ts b/editor/app/api/ops/compaction-markers/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+import { compactionMarkersAction } from "../../../saved-videos/compactActions";
+import { ops, reqSlug, reqVideoId, type OpsBody, OpsInputError } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST {} | { clear: { slug, id } }
+// -> { ok, markers: [{ slug, id, dir, live, why, marker }], cleared? }
+//
+// The "being compacted" markers (`<store dir>/.compacting.json`,
+// lib/compactingMarker-server.ts): each one, LIVE (its compaction runs: same
+// kernel boot, host, pid and pid start time, its job running, younger than
+// 72 h) or STALE, and why. `clear` removes one video's marker when it is
+// stale; a live one is refused — cancel its job instead. Stale markers are
+// also swept at editor boot and at the start of every compaction run.
+function optClear(body: OpsBody): { slug: string; id: string } | undefined {
+ if (body.clear === undefined) return undefined;
+ if (!body.clear || typeof body.clear !== "object" || Array.isArray(body.clear)) {
+ throw new OpsInputError('"clear" must be { "slug", "id" }');
+ }
+ const c = body.clear as OpsBody;
+ return { slug: reqSlug(c, "slug"), id: reqVideoId(c, "id") };
+}
+
+export async function POST(request: Request) {
+ return ops(request, ["clear"], async (body) => {
+ const clear = optClear(body);
+ const res = await compactionMarkersAction(clear ? { clear } : {});
+ return NextResponse.json({ ok: true, ...res });
+ });
+}
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?, confirmFormerOriginal? }
// -> { 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,25 @@ 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.
+// A FORMER original (`keptAs: "former-original"`) needs its own
+// "confirmFormerOriginal": true — a person's word, never an automatic step's.
export async function POST(request: Request) {
- return ops(request, ["slug", "id", "file", "dryRun"], async (body) => {
+ return ops(request, ["slug", "id", "file", "dryRun", "confirmOriginal", "confirmFormerOriginal"], 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,
+ confirmFormerOriginal: optBool(body, "confirmFormerOriginal") ?? false,
+ },
);
if (!res.ok) return opsFail(res.error);
const r = res.result;
diff --git a/editor/app/api/ops/kept-originals/route.ts b/editor/app/api/ops/kept-originals/route.ts
@@ -0,0 +1,27 @@
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { keptOriginalsList } from "../../../saved-videos/compactActions";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET [?slug=<channel>]
+// -> { ok, count, videos: [{ slug, id, active, compacted, kept: [{ file,
+// keptAs: "original" | "former-original", sha256?, bytes }],
+// pendingDrops: [{ file, keptAs?, at }] }], notAnswering }
+//
+// Every saved video that keeps an ORIGINAL or a FORMER ORIGINAL beside its
+// active copy, or has a drop in flight (a file the pointer no longer lists,
+// still on disk: drop it again by name to finish). An editor built from
+// before compaction does not know those labels and would treat such a copy
+// as an ordinary droppable alternate: while this list is not empty, do not
+// roll the editor back past that release (OPERATING.md, "Compact saved
+// videos"). Pointers 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 keptOriginalsList(slug ? { slug } : {});
+ return { count: rows.length, videos: rows, notAnswering };
+ });
+}
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,30 @@
+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?, formerOriginal? }
+// -> { ok, original, watched }
+//
+// A person's review of a compacted copy: "the compacted copy is proven good" —
+// after watching it (`get compaction-review` gives each video's two files and
+// a `smplayer` command for them). It names the copy it is for (`watched`, that
+// copy's sha256) and counts for that copy only.
+// 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", "formerOriginal"], async (body) => {
+ const res = await reviewCompactedOriginalAction(reqSlug(body, "slug"), reqVideoId(body, "id"), {
+ by: "ops",
+ // A FORMER original by its file name: the review is of the active copy that replaced it.
+ ...(optString(body, "formerOriginal") ? { formerOriginal: optString(body, "formerOriginal") } : {}),
+ ...(optString(body, "note") ? { note: optString(body, "note") } : {}),
+ });
+ if (!res.ok) return opsFail(res.error);
+ return NextResponse.json({ ok: true, original: res.original, watched: res.watched });
+ });
+}
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/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -445,7 +445,9 @@ export function VideoPanel({
title="Source video"
summary={
savedVideo
- ? `Persisted to the saved-video store (${formatBytes(savedVideo.bytes)}).`
+ ? savedVideo.compacted
+ ? `Persisted to the saved-video store as a re-encoded copy (${formatBytes(savedVideo.bytes)}, AV1 crf ${savedVideo.compacted.settings.crf}).`
+ : `Persisted to the saved-video store (${formatBytes(savedVideo.bytes)}).`
: "Persist the source video to the saved-video store."
}
defaultOpen={!!savedVideo}
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,24 @@ 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 {savedVideo.compacted.checks.audio},{" "}
+ {savedVideo.compacted.checks.wholeFile
+ ? `whole file SSIM ${savedVideo.compacted.checks.wholeFile.mean} (lowest ${savedVideo.compacted.checks.wholeFile.min} at ${savedVideo.compacted.checks.wholeFile.worstAt} s), `
+ : "no whole-file comparison, "}
+ {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 +260,12 @@ function PersistedSourceVideo({
slug={slug}
videoId={videoId}
alternate={a}
+ compacted={!!savedVideo.compacted}
+ watch={
+ savedVideo.compacted
+ ? `smplayer "${savedVideo.dir}/${savedVideo.file}" "${savedVideo.dir}/${a.file}"`
+ : undefined
+ }
/>
))}
</ul>
@@ -276,14 +309,22 @@ function SavedAlternateRow({
slug,
videoId,
alternate,
+ compacted,
+ watch,
}: {
slug: string;
videoId: string;
alternate: SavedVideoAlternate;
+ compacted: boolean;
+ // The command that plays the compacted copy and its original (this page
+ // has no player for the store).
+ watch?: string;
}) {
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 +334,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 +355,13 @@ 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."}
+ {alternate.keptAs === "former-original"
+ ? "This is the ORIGINAL of an earlier compacted copy; the active copy has replaced it since. A video not known to be on its platform needs a review of the active copy first. Delete it? 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 +374,11 @@ function SavedAlternateRow({
slug,
videoId,
alternate.file,
+ original
+ ? { confirmOriginal: true }
+ : alternate.keptAs === "former-original"
+ ? { confirmFormerOriginal: true }
+ : {},
);
if (!res.ok) setError(res.error);
setArmed(false);
@@ -331,7 +386,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 +398,67 @@ 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>
+ Watch both first, outside this page: <code className="break-all">{watch}</code>. 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,7 +76,9 @@ 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 { videoPersistBusyReason } from "yt-dlp-transcript-common/controller/videoBusy";
import {
+ CompactionInProgressError,
dropSavedAlternate,
loadSavedVideo,
SavedAlternateRefusal,
@@ -1439,7 +1441,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 || e instanceof CompactionInProgressError) return { ok: false, error: e.message };
+ throw e;
+ }
if (!reversed) {
return { ok: false, error: "This video has no persisted source to restore." };
}
@@ -1455,11 +1464,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 inside dropSavedAlternate (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; confirmFormerOriginal?: boolean } = {},
): Promise<{ ok: true; result: DropSavedAlternateResult } | { ok: false; error: string }> {
const paths = getPaths();
const config = await readChannelConfig(paths, slug);
@@ -1467,15 +1482,24 @@ 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 result: DropSavedAlternateResult;
try {
- result = await dropSavedAlternate(videoDirOf(slug, videoId), file, {
+ result = await dropSavedAlternate(videoDir, file, {
dryRun: opts.dryRun,
paths,
+ ...(opts.confirmOriginal ? { confirmOriginal: true } : {}),
+ // A person's word only (this action is the button and the ops route).
+ ...(opts.confirmFormerOriginal ? { confirmFormerOriginal: true } : {}),
+ // The gone rule's freshness, and no drop while a download or persist
+ // of this video is queued or running.
+ maxAgeDays: getSettings().savedVideoCompaction.availabilityMaxAgeDays,
+ busy: () => videoPersistBusyReason(slug, videoId),
});
} catch (e) {
if (
e instanceof SavedAlternateRefusal ||
+ e instanceof CompactionInProgressError ||
e instanceof SavedVideosStoreInTransitionError ||
e instanceof SavedVideosStoreNotAnsweringError
) {
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,20 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
minFreeMemMb: num(p.minFreeMemMb),
});
},
+ // The same list, mode and overrides: a replay (a person's Retry) 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 } : {}),
+ ...(p.belowThreshold === true ? { belowThreshold: true } : {}),
+ });
+ },
};
diff --git a/editor/app/saved-videos/compactActions.ts b/editor/app/saved-videos/compactActions.ts
@@ -0,0 +1,241 @@
+"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 {
+ clearCompactionMarker,
+ compactSavedVideos,
+ effectiveCompactionSettings,
+ listCompactionMarkers,
+ listKeptOriginals,
+ 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 (the job's Retry, after a
+// cancel or a restart) re-runs the same list, resuming the chunks already
+// encoded. The boot pass never re-runs it by itself: it may drop originals.
+export async function compactChannelVideosAction(
+ slug: string,
+ ids: string[],
+ opts: { mode: "explicit" | "select"; overrides?: CompactOverrides; retryFailed?: boolean; belowThreshold?: 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 } : {}),
+ ...(opts.belowThreshold ? { belowThreshold: 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,
+ jobId: ctx.jobId,
+ settings: settingsFor(overrides),
+ items: wanted.map((id) => ({ slug, id })),
+ mode: opts.mode,
+ ...(opts.retryFailed ? { retryFailed: true } : {}),
+ ...(opts.belowThreshold ? { belowThreshold: 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;
+ belowThreshold?: 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 } : {}),
+ ...(input.belowThreshold ? { belowThreshold: 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 } : {}),
+ ...(input.belowThreshold ? { belowThreshold: 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) {
+ // Nothing to start: the plan's lines say why each one was skipped.
+ const why = plan.items.map((i) => `${i.slug}/${i.id}: ${i.reason ?? "?"}`).join("; ");
+ return { ok: false, error: `Nothing to compact${why ? ` — ${why}` : ""}.` };
+ }
+ if (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(),
+ settings: getSettings().savedVideoCompaction,
+ ...(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; formerOriginal?: string } = {},
+): Promise<{ ok: true; original: SavedVideoAlternate; watched: string } | { 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() } : {}),
+ }, opts.formerOriginal ? { formerOriginal: opts.formerOriginal } : {});
+ safeRevalidate([`/channels/${slug}/videos/${videoId}`, "/saved-videos"]);
+ return { ok: true, original, watched: original.review?.forSha256 ?? "" };
+ } catch (e) {
+ if (e instanceof SavedAlternateRefusal) return { ok: false, error: e.message };
+ throw e;
+ }
+}
+
+// Every pointer that keeps an original or a former one, or has a drop in
+// flight: what a rollback past this release would mistreat (OPERATING.md).
+export async function keptOriginalsList(opts: { slug?: string } = {}) {
+ const notAnswering: string[] = [];
+ const rows = await listKeptOriginals({ paths: getPaths(), ...(opts.slug ? { channelSlug: opts.slug } : {}), notAnswering });
+ return { rows, notAnswering: notAnswering.sort() };
+}
+
+// The `.compacting.json` markers, and clearing a stale one.
+export async function compactionMarkersAction(opts: { clear?: CompactItem } = {}) {
+ const paths = getPaths();
+ const cleared = opts.clear ? { ...opts.clear, ...(await clearCompactionMarker(paths, opts.clear)) } : null;
+ return { markers: await listCompactionMarkers(paths), ...(cleared ? { cleared } : {}) };
+}
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,
+ settings: settings.savedVideoCompaction,
+ 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,45 @@ 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 ? "" : ` (${c.presence})`}.
+ </span>
+ <span className="text-muted-foreground"> {c.line}</span>
+ {c.state === "awaiting-review" && (
+ <span className="text-muted-foreground">
+ {" "}
+ To review, watch both: <code className="break-all">{c.watch.command}</code>
+ </span>
+ )}
+ {c.leftover && (
+ <span className="text-destructive"> An interrupted drop left {c.leftover} on disk: drop it again to finish.</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/editor/app/storage/lib/storeBusy.ts b/editor/app/storage/lib/storeBusy.ts
@@ -50,6 +50,8 @@ const STORE_TOUCHING_KINDS = new Set([
"persist-kept",
"persist-videos",
"check-kept-deleted",
+ // Writes a re-encode into the store and swaps the pointer.
+ "compact-saved-videos",
"backup-saved-videos",
"verify-saved-video-backup",
]);
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -103,6 +103,26 @@ export async function register() {
/* a health pass that fails to arm must not block server readiness */
}
+ // STALE "BEING COMPACTED" MARKERS (common/lib/compactingMarker-server.ts):
+ // none survives a restart — every compaction of the last process is over —
+ // so each is removed, on an idle boot too (it starts no work). The job
+ // registry probe a live marker is checked against is registered here.
+ void (async () => {
+ try {
+ const { registerCompactionJobProbe } = await import("yt-dlp-transcript-common/lib/compactingMarker-server");
+ const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+ registerCompactionJobProbe((id) => {
+ const j = getRegistry().get(id);
+ return !!j && (j.status === "running" || j.status === "queued");
+ });
+ const { sweepCompactingMarkers } = await import("yt-dlp-transcript-common/controller/compactSavedVideos");
+ const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+ await sweepCompactingMarkers(getPaths(), (line) => console.log(line.trimEnd()));
+ } catch {
+ /* a sweep that fails must not block server readiness */
+ }
+ })();
+
// ONE PASS OVER THE STORAGE LOCATIONS, and it runs on an IDLE BOOT TOO: it
// only reads, like the health pass above.
//
diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts
@@ -332,6 +332,9 @@ export type FetchClipOutcome =
waited: number;
height?: number;
maxHeight?: number;
+ // A whole recording whose saved copy is a compacted re-encode: the
+ // editor's sentence for it.
+ reencode?: string;
}
| { kind: "queued"; jobId: string; status: string; waited: number }
| { kind: "cooldown"; platform: string; cooldownMs: number; error: string }
@@ -507,6 +510,7 @@ export async function fetchClip(
bytes: num(body.bytes),
waited: waited(),
...heightFields(num(body.height), maxHeight),
+ ...(str(body.reencode) ? { reencode: str(body.reencode) } : {}),
};
}
if (status === "failed" || status === "cancelled") {
@@ -636,10 +640,13 @@ function footer(
requestedBy?: string;
height?: number;
maxHeight?: number;
+ reencode?: string;
},
cached = false,
): string {
const lines = [`file: ${f.file}`];
+ // A re-encode is named as one, never passed off as the source's bytes.
+ if (f.reencode) lines.push(`re-encode: ${f.reencode}`);
if (mode === "window" && f.from !== undefined && f.to !== undefined) {
lines.push(
`window: ${fmtSeconds(f.from)}–${fmtSeconds(f.to)} (${fmtSpan(f.to - f.from)})`,
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -293,6 +293,14 @@ 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 pointer that keeps an original or a former original (what an editor
+ // rolled back past compaction would mistreat), and drops in flight.
+ "kept-originals": (slug) =>
+ slug ? `/api/ops/kept-originals?slug=${encodeURIComponent(slug)}` : "/api/ops/kept-originals",
// 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 +385,8 @@ const GET_ARG_OPTIONAL = new Set([
"settings",
"storage",
"saved-alternates",
+ "compaction-review",
+ "kept-originals",
"sites",
"archives",
"workers",
@@ -497,6 +507,17 @@ 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? (select: a dry run by default), retryFailed?, belowThreshold?,
+ // 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",
+ // The "being compacted" markers, live or stale, and clearing a stale one
+ // ({} | {clear: {slug, id}}).
+ "compaction-markers",
// 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 +1139,8 @@ 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 kept-originals [<slug>]",
" pnpm ops get services",
" pnpm ops get x-session [<slug>]",
" pnpm ops get x-run [<run id>]",
@@ -1178,6 +1201,20 @@ 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 freshly checked 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 and why, the original's entry, sizes, checks, the re-check,",
+ ' "watch" (both files and an smplayer command that plays them) and any',
+ ' "leftover" of an interrupted drop.',
+ "get kept-originals [<slug>] lists every saved video that keeps an original",
+ ' ("keptAs": "original") or a former original ("former-original") beside',
+ " its active copy, or has a drop in flight (pendingDrops: a file the pointer",
+ " no longer lists, still on disk -- drop it again by name to finish). An",
+ " editor from before compaction would treat those as ordinary droppable",
+ " alternates: while this is not empty, do not roll the editor back past it.",
"get sites lists every site: id, title, siteUrl, Pages project, audience,",
" listed, search, publish policy, channels, citedChannels. (`get publish`",
" is the status.)",
@@ -1435,6 +1472,14 @@ 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; a video not freshly",
+ " checked on its platform needs a review of this copy recorded first; and",
+ " nothing goes while a download or persist of the video is queued or",
+ " running, or while it is being compacted. A FORMER original",
+ ' ("former-original") needs its own "confirmFormerOriginal": true, and',
+ " the same gone/review rule.",
"",
'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 +1892,42 @@ 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, every other stream",
+ ' and the chapters 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: a pin, an explicit',
+ ' persist, a requested or landed container -- never keep-latest, never',
+ " persist-kept's override); {\"select\": true, \"slugs\"?} asks the selector",
+ ' (and platform, height and video bitrate) and is a DRY RUN unless',
+ ' "dryRun": false. A named video the selector would not pick is refused',
+ ' unless "belowThreshold": true (the refusal says how little it saves).',
+ " \"dryRun\": true answers each video's line -- size, bitrate, height, fps,",
+ " the estimate (size, hours), the disk it needs, or why it is skipped. \"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 Retry resumes. The checks include a whole-file",
+ " comparison and excerpts across every chunk join. dropOriginal is \"keep\" by",
+ ' default; under "after-verify" the original is dropped in a later step',
+ " once the copy re-checks from disk -- never for a video not freshly",
+ " checked on its platform (get compaction-review). There is no backup of",
+ " the store: after a drop the compacted copy is the only copy.",
+ "",
+ 'compaction-markers lists the "being compacted" markers (.compacting.json),',
+ ' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale',
+ " one; a live one is refused (cancel its job). Stale ones are also swept at",
+ " editor boot and at the start of every compaction run.",
+ "",
+ 'review-compacted-original records a person\'s review of one compacted copy',
+ ' (watch it first: get compaction-review\'s "watch"): {"slug", "id",',
+ ' "note"?}. It names the copy it is for ("watched", its sha256) and counts',
+ " for that copy only; it changes nothing on disk. It is what lets",
+ ' drop-saved-alternate ("confirmOriginal": true) drop the original of a',
+ " video not freshly checked on its platform. \"formerOriginal\": \"<file>\"",
+ " reviews the active copy that replaced a former original instead.",
+ "",
'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,36 @@
"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,
+ "wholeFileSsimMin": 0.9,
+ "wholeFileSsimMean": 0.97,
+ "wholeFileSigmaK": 8,
+ "wholeFileSigmaMargin": 0.03,
+ "wholeFileTileMin": 0.7,
+ "wholeFileTileRunFrames": 2,
+ "availabilityMaxAgeDays": 7,
+ "dropOriginal": "keep"
+ },
"storage": {
"locations": [],
"defaultLocationId": ""
diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts
@@ -23,6 +23,7 @@ import { counterOrder } from "umtool-report-to-video/counter";
import { cachedTakeManifest, takePlayDir, writePlayManifest } from "@/lib/report/takeManifest.mjs";
import { isTakeId } from "@/lib/report/takes.mjs";
import { stackedOn } from "umtool-report-to-video/vertical-deck";
+import { MODULES } from "umtool-report-to-video/modules";
export const dynamic = "force-dynamic";
@@ -301,6 +302,13 @@ export async function POST(request: Request) {
...(stampDoc ? { stamp: stampDoc } : {}),
...(finale ? { finale } : {}),
layers,
+ // Each region's traits over a full-frame item (its module's `fullFrame`, full-frame.mjs): Play hides the feed,
+ // the stamps and the finale by them, as the build lays them.
+ fullFrame: Object.fromEntries(
+ (MODULES as readonly { region?: string; fullFrame?: Record<string, boolean> }[])
+ .filter((m) => m.fullFrame && m.region)
+ .map((m) => [m.region, m.fullFrame]),
+ ),
// The lead-in breath before a clip's cut (render.leadIn): the play
// window's start, which the live preview maps the source through.
leadIn: typeof render.leadIn === "number" ? render.leadIn : 0.4,
diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx
@@ -113,6 +113,8 @@ export type DeckPreviewDoc = {
verdictLabels?: Record<string, string>;
/** The play layers: every module that declares `play` (the module contract) and that the cut draws, by z. */
layers?: PlayLayer[];
+ /** Each region's `fullFrame` traits (its module's), for the regions that carry any: the feed's, the stamps', the finale's. */
+ fullFrame?: Record<string, FullFrameTraits>;
};
/**
* One module's live layer (the module contract's `play`, onscreen.mjs
@@ -133,7 +135,11 @@ export type PlayLayer = {
src?: string;
error?: string;
windows?: { segment: string | null; from: number; to: number; src?: string; error?: string }[];
+ /** How it is laid over a full-frame item (its module's `fullFrame`, full-frame.mjs); absent, it is off over every one. */
+ fullFrame?: FullFrameTraits;
};
+/** A module's `fullFrame` traits (full-frame.mjs regionSpans, layerOffOver). */
+export type FullFrameTraits = { followsDeck?: boolean; ownFade?: boolean; drawsMarks?: boolean };
/** An unsaved change to a post, as PUT /api/report/posts takes it. */
export type PostPatch = { attachTo?: string | null; hide?: boolean; thread?: boolean };
/** What each segment's panel should say right now, by entry id. */
@@ -2356,11 +2362,14 @@ export function ModuleLayers({
frame: g,
t,
testid = "module-layer",
+ off,
}: {
layers: PlayLayer[] | undefined;
frame: DeckGeometry;
t: number;
testid?: string;
+ /** A layer not drawn now (a full-frame item on screen, full-frame.mjs layerOffOver): kept mounted, transparent. */
+ off?: (layer: PlayLayer) => boolean;
}) {
if (!layers?.length) return null;
type Row = { key: string; layer: PlayLayer; segment: string | null; src?: string; error?: string; up: boolean };
@@ -2383,7 +2392,8 @@ export function ModuleLayers({
data-play-layer={r.layer.id}
data-play-layer-segment={r.segment ?? undefined}
data-play-layer-up={r.up ? "1" : "0"}
- style={{ opacity: r.up ? 1 : 0 }}
+ data-play-layer-off={off?.(r.layer) ? "1" : undefined}
+ style={{ opacity: r.up && !off?.(r.layer) ? 1 : 0 }}
>
<FeedOverlay
feed={{ geometry: r.layer.geometry!, src: r.src, error: r.error }}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -821,8 +821,9 @@ export default function PlayCut({
data-play-state={ui.ended ? "ended" : ui.playing ? (ui.waiting ? "waiting" : "playing") : "paused"}
data-play-t={String(Math.round(t * 100) / 100)}
data-play-item={item?.id ?? ""}
- // A video entry with the chrome off over it is on screen (video-entry.mjs): nothing of the deck shows.
- data-play-chrome={videoNow?.video.noChrome ? "off" : undefined}
+ // A full-frame item is on screen (full-frame.mjs: a video entry with the chrome off, a teaser the deck hides
+ // over, the intro, an analysis item, a card under overCards "hide"): the deck is away and its layers are off.
+ data-play-chrome={videoNow?.video.noChrome || core.chromeOff ? "off" : undefined}
data-play-compose={composeState}
data-play-basic={view.basic ? "" : undefined}
data-play-edges={edges.state}
diff --git a/umtool/components/projects/review/playCore.tsx b/umtool/components/projects/review/playCore.tsx
@@ -5,7 +5,8 @@ import { footageAt } from "@/lib/report/footage-move.mjs";
import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
import { chromeTime, playPlan, skipEntries } from "@/lib/report/playCut.mjs";
import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck";
-import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
+import { fullFrameItems, layerOffOver } from "umtool-report-to-video/full-frame";
+import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type FullFrameTraits, type Rect } from "../OnscreenSection";
import { usePlayEngine } from "./playEngine/usePlayEngine";
import { useRenderCuts } from "./playEngine/useRenderCuts";
import type { ItemGate, MediaRef } from "./playEngine/engine";
@@ -286,6 +287,16 @@ export function usePlayCore(view: PlayViewData, { showRejected = false }: { show
// it did not compose -- a placeholder that says so.
const introNow = item && entry?.type === "intro" && introPage && "src" in introPage ? { item, page: introPage } : null;
const placeholder = item && !postNow && !videoNow && !teaserNow && !introNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
+ // A FULL-FRAME item on screen (full-frame.mjs: a teaser the deck hides over, the intro, an analysis item, a card
+ // under overCards "hide", a video entry with the chrome off): the layers that keep no time of their own are off over
+ // it, as the build lays their overlays with an `enable` that leaves its span out. Play cuts at mid-dissolve, so
+ // "over it" is while it is the item on screen.
+ const fullItems = useMemo(() => fullFrameItems(schedule), [schedule]);
+ const fullNow = item ? (fullItems.find((x) => x.id === item.id) ?? null) : null;
+ const chromeOff = !!fullNow;
+ // Each layer by its module's traits: the deck's page, the feed and the instruments keep their own slide; the
+ // stamps stay over a teaser with marks; the finale's pages finish their fade out.
+ const layerOff = useCallback((region: string, traits?: FullFrameTraits | null) => layerOffOver(fullNow, traits ?? doc?.fullFrame?.[region] ?? null, tc), [fullNow, doc?.fullFrame, tc]);
// The clips' sound fades with the picture into a video entry and is off over it (its element plays its own).
const duck = vstage ? vstage.duck : 1;
useEffect(() => {
@@ -340,7 +351,7 @@ export function usePlayCore(view: PlayViewData, { showRejected = false }: { show
teaserPages, introPage, engine, onPostReady, bg,
asPublished, setAsPublished, uncensored, setUncensored,
// what is on screen
- t, tc, item, entry, g, box, move, rect, tally, stamp, finaleNow, postsWin, missing, broken,
+ t, tc, item, entry, g, box, move, rect, tally, stamp, finaleNow, postsWin, missing, broken, chromeOff, layerOff,
postNow, vstage, videoNow, teaserPage, teaserNow, introNow, placeholder, sideEntry,
};
}
@@ -357,7 +368,7 @@ const pct = (n: number, of: number) => `${(n / of) * 100}%`;
* `basic`: a basic cut -- the bare footage, as the basic render cuts it.
*/
export function PlayStage({ core, basic = false, plainClassName }: { core: PlayCore; basic?: boolean; plainClassName?: string }) {
- const { project, take, doc, g, box, rect, move, tc, t, bg, engine, postNow, entryOf, plan, videoNow, vstage, teaserNow, introNow, placeholder, teaserPage, introPage, sideEntry, item, postsWin, finaleNow, asPublished, uncensored, onPostReady } = core;
+ const { project, take, doc, g, box, rect, move, tc, t, bg, engine, postNow, entryOf, plan, videoNow, vstage, teaserNow, introNow, placeholder, teaserPage, introPage, sideEntry, item, postsWin, finaleNow, asPublished, uncensored, onPostReady, layerOff } = core;
const { ui, rate, failed } = engine;
const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
<canvas ref={engine.canvasRef} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
@@ -484,13 +495,24 @@ export function PlayStage({ core, basic = false, plainClassName }: { core: PlayC
{introCard}
{placeholderCard}
{sideNow && rect && <div className="pointer-events-none absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }}>{sideNow}</div>}
+ {/* Over a full-frame item (full-frame.mjs) a layer that keeps no time of its own is not drawn (layerOff):
+ kept mounted, transparent, so its page is ready and seeked when the item after it comes up. The feed
+ follows the deck (followsDeck), as the deck's own page does. */}
{doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
- {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
- {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
+ {postsWin && doc.posts && (
+ <div className="pointer-events-none absolute inset-0" style={layerOff("posts") ? { opacity: 0 } : undefined} data-play-off={layerOff("posts") ? "posts" : undefined}>
+ <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />
+ </div>
+ )}
+ {doc.stamp && (
+ <div className="pointer-events-none absolute inset-0" style={layerOff("stamp") ? { opacity: 0 } : undefined} data-play-off={layerOff("stamp") ? "stamp" : undefined}>
+ <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />
+ </div>
+ )}
{/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */}
- <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" />
+ <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" off={(l) => layerOff(l.region, l.fullFrame ?? {})} />
{doc.finale && finaleNow && (
- <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale="">
+ <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2, ...(layerOff("finale") ? { opacity: 0 } : {}) }} data-play-finale="">
<FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={tc} ready="finale:ready" testid="play-finale" name="finale" />
</div>
)}
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -2710,7 +2710,7 @@ The panel at the foot of the frame and each clip's title (`render.chrome.deck`);
| `deck.height` | 120–400 px · default 190 | `umtool look <p> deck.height=210` |
| `deck.footageScale` | 0.5–1 (the footage must fit above the deck) · default 0.82 | `umtool look <p> deck.footageScale=0.8` |
| `deck.background` | `panel` · `flush` · default `panel` | `umtool look <p> deck.background=flush` |
-| `deck.overCards` | `hide` (the deck slides away over a card) · `show` · default `hide` | `umtool look <p> deck.overCards=show` |
+| `deck.overCards` | `hide` (the deck slides away over a card, and the layers that keep no time of their own are left out over it: a full-frame item, [report-video.md](report-video.md#no-chrome-over-a-full-frame-item)) · `show` (the deck and every layer stay over it) · default `hide` | `umtool look <p> deck.overCards=show` |
| `deck.title` | `{size 24–96, maxChars 10–120}` · default 54, 48 | `umtool look <p> deck.title='{"size":60}'` |
| `deck.motion` | `{out 0–2, in 0–2, pip 0–3}` s · default 0.3, 0.45, 0.7 | `umtool look <p> deck.motion='{"in":0.6}'` |
@@ -2794,7 +2794,7 @@ A timeline entry `{ type: "analysis", … }` (analysis-plan.mjs; [report-video.m
### Teaser
-A timeline entry `{ type: "teaser", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)).
+A timeline entry `{ type: "teaser", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)). Full frame: the deck, the instruments and the feed slide away over it, and every layer that keeps no time of its own -- the diet strip, the promise clock, the goals, the streak, the side panels, the chapters, the finale's pages -- is left out from its first frame (a dip's black) to the frame before its dissolve out ends ([report-video.md](report-video.md#no-chrome-over-a-full-frame-item)); its stamps stay when it carries marks; a teaser that counts (marks, no dip) keeps the deck and every layer up.
| Knob | Range · default | From a terminal |
|---|---|---|
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -424,9 +424,10 @@ window framed into the deck's box, a video entry is drawn over by **nothing**: n
no header or date line, no QR, no rail, markers or section titles, no counters, captions, clock,
thread map, watermark or any overlay layer. The build lays every chrome region (the deck's shell,
the feed, the posts windows, stamps, stats, effects, the finale) with an `enable` that leaves the
-entry's span out (`video-entry.mjs videoBlackouts`: from the frame the entrance's dip has made black
-to its end -- mid-dissolve into the next entry, or the cut's end), and the deck hides over it as over
-a teaser. Play draws it the same way. `deck: "shown"` keeps the chrome.
+entry's span out (`video-entry.mjs videoBlackouts`, its share of every full-frame item's spans --
+[No chrome over a full-frame item](#no-chrome-over-a-full-frame-item): from the frame the entrance's dip
+has made black to its end -- mid-dissolve into the next entry, or the cut's end), and the deck hides over
+it as over a teaser. Play draws it the same way. `deck: "shown"` keeps the chrome.
**The entrance** (`enter`, default `{out: 0.5, in: 0.5}`): the item before -- its picture and every
overlay, and its sound -- fades to black over its last `out` seconds (the teaser's dip, with no held
@@ -547,8 +548,10 @@ source file, its offset, its gain) and the encode, so an unchanged item is not e
`--chrome-only` rebuilds it from the cache; a `--cut-window` preview lays it as any segment. Its page is the
whole frame: **no chrome layer is laid over it** -- the deck, the instruments, the diet strip and the goal notes,
the promise clock, the stamps, the effects, the chapter bands, every region -- each region's overlay leaves its
-span out (`chromeBlackouts`, as a video entry's), from the first frame of its dissolve in to the end of its
-dissolve out (to the cut's end when it is last). It draws in the deck's faces: a cut without `render.fontRegular` and `render.fontBold`
+span out (`chromeBlackouts`, as a video entry's and a teaser's: [No chrome over a full-frame
+item](#no-chrome-over-a-full-frame-item)), from the first frame of its dissolve in to the end of its
+dissolve out (to the cut's end when it is last) -- a frame sooner for the layers that keep no time of their own,
+the finale's pages once the dissolve in is over; Play hides those layers while it is on screen. It draws in the deck's faces: a cut without `render.fontRegular` and `render.fontBold`
is refused early. No vertical form: a 9:16 cut, or `--vertical` on a landscape one, refuses it before
anything is spent. Its date axis is by days alone (`trailLayout`'s `dayShare: 1`), whatever share the
by-date trail gives its weights: a span's width says its days. `umtool ledger rm` refuses
@@ -1841,6 +1844,44 @@ stays one line. The schedule carries each segment's `subtitleLines` beside `subt
(only in two lines), the page's items carry the markup, so a frame key changes with the
lines. Absent or `1`: the deck, its page and its keys are what they were.
+### No chrome over a full-frame item
+
+An item that is the whole frame is its own picture: a **teaser** (unless it counts), the **brand intro**, an
+**analysis item**, a **video entry** (unless `deck: "shown"`), and a **card** -- `card`, `scroll`, `chart`,
+`ledger` -- under `deck.overCards: "hide"` (the default). The deck slides away over each (deck.mjs `hidesDeck`, the
+segment's `hideDeck`), and so do the layers that follow its choreography. **Every layer that keeps no time of its
+own is left out over it**: the measure extras (the diet strip, the promise clock's days-since, the goals, the
+streak chain, the peak), the shelf, the posts windows, the stamps, the stats, the effects, the thread map, the
+flips, the status ledger, the pair strip, the chat, the chapter bands, the finale's pages. The build lays each of
+those regions with an `enable` that leaves the item's span out -- one list, `full-frame.mjs fullFrameItems`, each
+region taking its share by its module's `fullFrame` traits (`regionSpans`; build-video.mjs `chromeOverlayChain`),
+for the full cut, a preview, a `--cut-window` and every chunk of a chunked encode:
+
+| Item | Off from | Off to |
+|---|---|---|
+| a teaser, the intro, an analysis item, a card | the first frame of its dissolve in (0 when it is first); for a teaser that **dips**, the frame the dip has made black -- the clip before, overlays and all, fades to black first | the frame BEFORE the end of its dissolve out (that frame is the next segment's alone), or past the cut's end when it is last |
+| a video entry | the frame the entrance's dip has made black (mid-dissolve for `enter: "cut"`) | mid-dissolve into the next entry, or past the cut's end |
+
+What a region's module says (`fullFrame` in the module contract):
+
+- **`followsDeck`** -- the deck's shell (title, subtitle, QR, rail, section title, counter; the stacked deck's page
+ too), the dial, the odometer, the trail, the feed. They hide themselves over the item and slide back after it
+ (deckChoreography), so they keep exactly the blackouts they had: a video entry's span and an analysis item's
+ (to the end of its dissolve out), nothing over a teaser, the intro or a card.
+- **`ownFade`** -- the finale, the dial's finale, the diet runs. Their page fades out through the dissolve after the
+ run, so over an item that follows the finale they are left out only once the dissolve into it is over.
+- **`drawsMarks`** -- the stamps. A teaser that carries marks keeps its stamps over it, a teaser that dips too: the
+ stamp is that card's own content, and its tally steps as it lands.
+
+**A chapter bumper** on the clip right after a full-frame item starts on the first frame after the item's span
+(its entrance plays whole, never cut by the span), for its `seconds`, never past the clip. **What keeps every
+layer**: a teaser that counts (marks and no dip, deck.mjs `teaserCounts`: the deck stays up so the count is seen to
+step), a card under `overCards: "show"`, a video entry with `deck: "shown"`. A cut with none of these items lays
+every overlay exactly as before. **Play the cut** does the same while such an item is on screen (it cuts at
+mid-dissolve): each layer by the same traits (the preview's `fullFrame` map; a play layer's own `fullFrame`), kept
+loaded and seeked; the deck's page, the feed and the instruments draw their own slide; `data-play-chrome="off"` on
+its root. Present draws no chrome at all.
+
### The video's knobs (the pipeline's side)
Every knob below is a manifest key the build reads; absent, the render is
@@ -3684,7 +3725,8 @@ lockup's own glyph paths (brands/archilyzer-media.json), not a font.
"intro", id: "brand-intro"}`, so the build, the deck's schedule, the chapters
and umtool's Play view and export all see the same first segment: the cut
grows by the intro's seconds less the join, and every entry starts that much
-later. The deck hides over it (it is full frame, like a teaser). It is not a
+later. The deck hides over it, and no chrome layer is drawn over it (it is full frame, like a teaser:
+[No chrome over a full-frame item](#no-chrome-over-a-full-frame-item)). It is not a
chapter of its own: the first entry's chapter starts at 0 and takes it in
(YouTube keeps no chapter under 10 s). A timeline entry of your own named
`brand-intro` is refused.
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -1016,7 +1016,11 @@ export async function composePlayLayers(project, variant, schedule, render, { sr
const rows = await composeLayerPreviews(project, variant, schedule, mods.map((m) => m.id), render, { compose });
return rows.map((l, i) => {
const m = mods[i];
- const base = { id: l.id, region: l.region, kind: l.kind ?? m.kind, z: m.z, clock: m.play.clock, ready: m.play.ready, geometry: l.geometry ?? null };
+ const base = {
+ id: l.id, region: l.region, kind: l.kind ?? m.kind, z: m.z, clock: m.play.clock, ready: m.play.ready, geometry: l.geometry ?? null,
+ // How it is laid over a full-frame item (full-frame.mjs): Play hides it by the same traits the build lays it by.
+ ...(m.fullFrame ? { fullFrame: m.fullFrame } : {}),
+ };
if (Array.isArray(l.windows)) {
return {
...base,
diff --git a/umtool/lib/report/shortsBatch.test.mjs b/umtool/lib/report/shortsBatch.test.mjs
@@ -295,3 +295,38 @@ test("a record's look keeps its fonts by name (the pipeline's) or relative to th
// A font elsewhere on the machine stays as written (there is no name to give it).
assert.equal(lookSnapshotOf({ fontRegular: "/usr/share/fonts/X.ttf" }, { projectDir: dir }).fontRegular, "/usr/share/fonts/X.ttf");
});
+
+test("a short or a desktop clip of a take with a cold-open teaser and an analysis ending: the clip alone is planned, as without them (per-clip builds have no deck, so no full-frame blackout)", async () => {
+ const w = await world();
+ try {
+ const m = JSON.parse(await readFile(path.join(w.dir, "video.manifest.json"), "utf8"));
+ const plain = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true }, { reportsRoot: w.reportsRoot });
+ const plainDesk = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true, desktop: true }, { reportsRoot: w.reportsRoot });
+ m.render.chrome = { engine: "hyperframes", layout: "deck", deck: {} };
+ m.timeline = [
+ { type: "teaser", id: "t-open", seconds: 4, lines: ["Coming up"], dip: true },
+ ...m.timeline,
+ { type: "analysis", id: "a-end", seconds: 7, kind: "ending" },
+ ];
+ await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify(m));
+ const withThem = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true }, { reportsRoot: w.reportsRoot });
+ const desk = await buildShort({ project: "proj", take: "kit", items: ["w01"], dryRun: true, desktop: true }, { reportsRoot: w.reportsRoot });
+ assert.deepEqual(withThem.dryRun.items, plain.dryRun.items);
+ assert.deepEqual(withThem.dryRun.pieces, plain.dryRun.pieces);
+ assert.deepEqual(desk.dryRun.items, plainDesk.dryRun.items);
+ assert.deepEqual(withThem.dryRun.items.map((i) => i.type), ["clip"]);
+ } finally {
+ await rm(w.root, { recursive: true, force: true });
+ }
+});
+
+test("the per-clip renders drop the deck (a desktop clip, a bare short): no chrome, so no full-frame blackout; the stacked deck keeps it, over the planned clips alone", async () => {
+ const { desktopRender, verticalRender } = await import("umtool-report-to-video/vertical");
+ const { fullFrameItems } = await import("umtool-report-to-video/full-frame");
+ const render = { width: 1920, height: 1080, fps: 30, chrome: { engine: "hyperframes", layout: "deck", deck: {} } };
+ assert.equal(desktopRender(render).chrome, undefined);
+ assert.equal(verticalRender({ ...render, format: "vertical", vertical: { deck: "bare" } }).chrome, undefined, "a bare short");
+ assert.deepEqual(verticalRender({ ...render, format: "vertical" }).chrome, render.chrome, "the stacked deck keeps it");
+ // Its schedule is the planned clips': no teaser, intro or analysis item among them, so no full-frame item.
+ assert.deepEqual(fullFrameItems({ segments: [{ id: "w01", type: "clip", start: 0, end: 8, duration: 8 }], total: 8, fps: 30, transition: 0.5 }), []);
+});
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -1370,6 +1370,15 @@ trailer hit under each pop. Put it after the last clip; the ordinary crossfade
joins them, and `render.endFade` — which fades the cut's last segment — now
falls on the teaser.
+Under the deck it is full frame: the deck slides away over it, the instruments and
+the feed with it, and the layers that keep no time of their own — the measure
+extras (the diet strip, the promise clock, the goals, the streak), the side
+panels, the chapters, the finale's pages — are left out over it, from its first
+frame (for one that dips, the frame the dip has made black) to the frame before
+its dissolve out ends (`full-frame.mjs`; umtool's report-video.md, "No chrome
+over a full-frame item"). Its stamps stay when it carries marks. A teaser that
+counts (marks, no dip) keeps the deck up, and every layer with it.
+
```jsonc
{ "type": "teaser", "id": "fin", "seconds": 7,
"lines": ["Pirate Software",
diff --git a/umtool/report-to-video/analysis-chrome-off.test.mjs b/umtool/report-to-video/analysis-chrome-off.test.mjs
@@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url";
import { chromeBlackouts, chromeOverlayChain } from "./build-video.mjs";
import { analysisBlackouts } from "./analysis-plan.mjs";
+import { fullFrameSpans, regionSpans } from "./full-frame.mjs";
import { deckOverlays } from "./modules/index.mjs";
import { videoBlackouts } from "./video-entry.mjs";
@@ -47,7 +48,8 @@ test("every overlay module's region is off over the analysis segment, from its f
const regions = on.flatMap((m) => m.regions(SCHEDULE, { render: RENDER, outDir: "/out", frames: `/out/chrome/${m.region}-frames`, shift: 0 }));
assert.ok(regions.length >= ids.length);
const blackouts = chromeBlackouts(SCHEDULE);
- assert.deepEqual(blackouts, [[732.6, 740.6]]);
+ assert.deepEqual(fullFrameSpans(SCHEDULE), [[732.6, 740.6]]);
+ assert.deepEqual(regionSpans(blackouts, { followsDeck: true }), [[732.6, 740.6]]);
const chain = chromeOverlayChain(RENDER, regions, "[0:v]", 1, { blackouts });
const overlays = chain.chain.split(";").filter((p) => p.includes("overlay="));
assert.equal(overlays.length, regions.length);
@@ -69,12 +71,17 @@ test("in a window of the cut (--cut-window, a preview) the span is shifted to th
assert.equal(enabledAt(part, 2.5), true);
});
-test("a cut without an analysis item: the blackouts it always had (a teaser's span is not one -- reported, unchanged)", () => {
+test("a cut without an analysis item: no analysis span (a teaser that hides the deck is full frame by the same rule: teaser-chrome-off.test.mjs)", () => {
const withTeaser = { ...SCHEDULE, segments: [SCHEDULE.segments[0], { ...SCHEDULE.segments[1], id: "t", type: "teaser" }] };
- assert.deepEqual(chromeBlackouts(withTeaser), videoBlackouts(withTeaser));
- assert.deepEqual(chromeBlackouts(withTeaser), []);
+ assert.deepEqual(videoBlackouts(withTeaser), []);
assert.deepEqual(analysisBlackouts(withTeaser), []);
+ assert.deepEqual(fullFrameSpans(withTeaser), [[732.6, 740.6]]);
+ assert.deepEqual(regionSpans(chromeBlackouts(withTeaser), { followsDeck: true }), []);
+ assert.deepEqual(chromeBlackouts({ ...SCHEDULE, segments: [SCHEDULE.segments[0]] }), []);
// An analysis item mid-cut: off from its dissolve in to the end of its dissolve out.
const mid = { ...SCHEDULE, total: 760, segments: [...SCHEDULE.segments, { id: "b", type: "clip", start: 739.2, duration: 20.8, end: 760 }] };
- assert.deepEqual(chromeBlackouts(mid), [[732.6, 739.6]]);
+ // The deck's own regions to the end of its dissolve out, as before; every other to the frame before (that frame
+ // is the next clip's alone).
+ assert.deepEqual(regionSpans(chromeBlackouts(mid), { followsDeck: true }), [[732.6, 739.6]]);
+ assert.deepEqual(fullFrameSpans(mid), [[732.6, 739.5667]]);
});
diff --git a/umtool/report-to-video/analysis-plan.mjs b/umtool/report-to-video/analysis-plan.mjs
@@ -36,6 +36,7 @@ import { playEdges } from "./mute.mjs";
import { gapsOf } from "./gaps.mjs";
import { trailLayout, trailLine } from "./trail-plan.mjs";
import { endFadeOf, transitionOf } from "./deck.mjs";
+import { itemSpans } from "./full-frame.mjs";
/** The item's length: the silent default and ceiling (no dead air), the floor any item has, the longest audio. */
export const ANALYSIS_SECONDS = Object.freeze({ silent: 7, silentMax: 8, min: 4, audioMax: 30 });
@@ -234,20 +235,10 @@ export function analysisSeconds(entry) {
/**
* THE CUT SECONDS NO CHROME DRAWS OVER, for an analysis item (its page is the whole frame): each analysis segment
* of the schedule as `[from, to]` cut seconds -- from the first frame of its dissolve in (its segment's start) to the
- * last of its dissolve out (its end), the cut's end + 1 when it is last. The build lays every chrome region with an
- * `enable` that leaves these out, as it does a video entry's (video-entry.mjs videoBlackouts). [] without one.
+ * last of its dissolve out (its end), the cut's end + 1 when it is last: the span the deck's own regions leave out
+ * (full-frame.mjs regionSpans `followsDeck`; every other region's ends a frame sooner). [] without one.
*/
-export function analysisBlackouts(schedule) {
- const segs = schedule?.segments ?? [];
- const out = [];
- segs.forEach((s, i) => {
- if (s?.type !== "analysis" || !Number.isFinite(Number(s.start))) return;
- const end = Number.isFinite(Number(s.end)) ? Number(s.end) : Number(s.start) + Number(s.duration);
- const to = i === segs.length - 1 ? Number(schedule.total ?? end) + 1 : end;
- out.push([Math.round(Number(s.start) * 1e4) / 1e4, Math.round(to * 1e4) / 1e4]);
- });
- return out;
-}
+export const analysisBlackouts = (schedule) => itemSpans(schedule, "analysis");
/** The ledger a cut's analysis reads: the variant's whole measure record (selectVariant keeps it), else the ledger. */
export const analysisLedger = (manifest) => (Array.isArray(manifest?.measureLedger) ? manifest.measureLedger : manifest?.ledger ?? []);
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -155,8 +155,9 @@ import {
} from "./sources.mjs";
// A clip whose media is a file beside the manifest (`src`, `cues`).
import { clipLabel, createLocalMedia, hasLocalMedia, resolveManifestPath, validateLocalMedia } from "./local-media.mjs";
-import { analysisBlackouts, analysisSeconds, validateAnalysisEntries } from "./analysis-plan.mjs";
-import { blackoutEnable, validateVideoEntries, videoBlackouts, videoFit, videoLoudnessTarget, videoLead, videoMeasureFilter, videoSeconds, videoSegmentGraph, videoSegmentKey, videoSpan } from "./video-entry.mjs";
+import { analysisSeconds, validateAnalysisEntries } from "./analysis-plan.mjs";
+import { fullFrameItems, regionSpans } from "./full-frame.mjs";
+import { blackoutEnable, validateVideoEntries, videoFit, videoLoudnessTarget, videoLead, videoMeasureFilter, videoSeconds, videoSegmentGraph, videoSegmentKey, videoSpan } from "./video-entry.mjs";
import { createPostChannelResolver, resolvePostLinks } from "./post-links.mjs";
import { ensureWriteDir } from "../lib/report/storage.mjs";
// The deck (`render.chrome`): its geometry, validation and schedule are pure
@@ -185,7 +186,7 @@ import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
-import { deckOverlays, moduleById, placementOf } from "./modules/index.mjs";
+import { deckOverlays, moduleById, moduleOfRegion, placementOf } from "./modules/index.mjs";
import { CHAT_CUES_FILE, chatWanted } from "./chat.mjs";
import { counterOrder } from "./counter.mjs";
// The upload's text (release 28 M6): composed by code, written beside the cut.
@@ -4025,8 +4026,9 @@ export function railFilterChain(rail, assets, times, render, inLabel, firstInput
*/
export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts = {}) {
const { outLabel = "[hfout]", final = true, blackouts = null, shift = 0 } = opts;
- // The video entries' spans (video-entry.mjs videoBlackouts), cut seconds; "" with none.
- const off = blackoutEnable(blackouts, shift);
+ // The full-frame items (chromeBlackouts, full-frame.mjs): each region's share of them, by its module's traits,
+ // cut seconds; "" with none. (`[a, b]` pairs: the same pairs for every region.)
+ const offOf = (name) => blackoutEnable(regionBlackouts(blackouts, name), shift);
const inputs = [];
const parts = [];
let lab = inLabel;
@@ -4081,7 +4083,7 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts
parts.push(`${src}format=rgba[hfa${i}]`);
src = `[hfa${i}]`;
}
- parts.push(`${lab}${src}overlay=x=${r.x}:y=${r.y}:format=yuv444:${posts ? "eof_action=pass" : "shortest=1"}${off}${out}`);
+ parts.push(`${lab}${src}overlay=x=${r.x}:y=${r.y}:format=yuv444:${posts ? "eof_action=pass" : "shortest=1"}${offOf(r.name)}${out}`);
lab = out;
});
if (final) parts.push(`${lab}format=yuv420p[vout]`);
@@ -6253,22 +6255,26 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
await logRebuild(outDir, { phase: "chrome", seconds: Number(((Date.now() - tAll) / 1000).toFixed(1)), workers: pool.budget,
renders: CHROME_LAYERS, layers });
}
- // Over a video entry the chrome is OFF (video-entry.mjs): each region's overlay leaves its span out.
+ // Over a full-frame item -- a video entry, an analysis item, a teaser, the intro, a card the deck hides over --
+ // the chrome is OFF (full-frame.mjs): each region's overlay leaves its span out.
// Only when the cut has one, so every other cut's graph is the one it was.
const blackouts = chromeBlackouts(schedule);
return { regions, outLabel: "[hfout]", ...(blackouts.length ? { blackouts } : {}) };
}
/**
- * The cut seconds every chrome region leaves out (its overlay's `enable`): a video entry's span (video-entry.mjs
- * videoBlackouts) and an analysis item's, whose page is the whole frame (analysis-plan.mjs analysisBlackouts) --
- * no layer at all over it. A cut with neither: [].
+ * What every chrome region's overlay `enable` leaves out: the cut's FULL-FRAME items (full-frame.mjs fullFrameItems)
+ * -- a video entry, an analysis item, a teaser that hides the deck, the brand intro, a card under `overCards:
+ * "hide"` -- each region taking its share by its module's `fullFrame` traits (chromeOverlayChain, regionSpans). A
+ * cut with none: [].
*/
-export function chromeBlackouts(schedule) {
- const blackouts = videoBlackouts(schedule);
- const analysisOff = analysisBlackouts(schedule);
- if (analysisOff.length) blackouts.push(...analysisOff), blackouts.sort((x, y) => x[0] - y[0]);
- return blackouts;
+export const chromeBlackouts = (schedule) => fullFrameItems(schedule);
+
+/** The spans region `name` leaves out of `blackouts`: `[a, b]` pairs as given, or full-frame items by its traits. */
+export function regionBlackouts(blackouts, name) {
+ if (!blackouts?.length) return null;
+ if (Array.isArray(blackouts[0])) return blackouts;
+ return regionSpans(blackouts, moduleOfRegion(name)?.fullFrame ?? null);
}
/**
diff --git a/umtool/report-to-video/chrome-story.mjs b/umtool/report-to-video/chrome-story.mjs
@@ -19,6 +19,7 @@ import { deckGeometry, feedGeometry, overlayBox, pictureK } from "./deck.mjs";
import { rgba } from "./chrome-deck.mjs";
import { compileCues, cuePageHtml, dateText, esc, joinSpans, r4, segmentSpans, spanEvents, INSTANT } from "./chrome-cues.mjs";
import { CHAPTER_DEFAULTS, PAIR_DEFAULTS, STATUS_DEFAULTS } from "./modules/story-settings.mjs";
+import { fullFrameItems, regionSpans } from "./full-frame.mjs";
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -192,13 +193,23 @@ export function resolveChapter(render) {
export function chapterWindows(schedule, render) {
const C = resolveChapter(render);
const at = segmentSpans(schedule);
+ // A clip whose start is inside a full-frame item's span (the dissolve out of a teaser, the intro, a card: no
+ // chrome is drawn there, full-frame.mjs): its bumper starts on the first frame after that span, so its entrance
+ // plays whole. None: it starts with its clip, as ever.
+ const fps = Number(schedule?.fps) || 30;
+ const off = regionSpans(fullFrameItems(schedule));
+ const after = (t) => {
+ for (const [a, b] of off) if (t >= a && t <= b) return r4(b + 1 / fps);
+ return t;
+ };
const out = [];
C.list.forEach((c, n) => {
const sp = at.get(c?.at);
if (!sp) return;
- const to = Math.min(sp.out, sp.in + C.seconds);
- if (!(to - sp.in > 0.2)) return;
- const w = { segment: c.at, from: sp.in, to, n, title: c.title, subtitle: c.subtitle ?? "", date: c.date ?? null };
+ const from = after(sp.in);
+ const to = Math.min(sp.out, from + C.seconds);
+ if (!(to - from > 0.2)) return;
+ const w = { segment: c.at, from, to, n, title: c.title, subtitle: c.subtitle ?? "", date: c.date ?? null };
// Where it stands (chapterPlacement): a lower band that would cover a post card moves into the card's free side
// margin -- or, where neither margin can hold it, the cut has no bumper over that card.
const place = chapterPlacement(schedule, render, w);
diff --git a/umtool/report-to-video/full-frame.mjs b/umtool/report-to-video/full-frame.mjs
@@ -0,0 +1,162 @@
+// full-frame.mjs — THE FULL-FRAME ITEMS: the cut seconds a chrome layer that keeps no time of its own is not drawn.
+//
+// An item that takes the whole frame -- a teaser, the brand intro, an analysis item, a video entry, a card
+// (`card`, `scroll`, `chart`, `ledger`) under `deck.overCards: "hide"` -- is its own picture. The deck slides away
+// over it (deck.mjs hidesDeck, the segment's `hideDeck`), and the layers that follow the deck's choreography go with
+// it: the shell, the dial, the odometer, the trail, the feed (their module's `fullFrame.followsDeck`). The others --
+// the measure extras (the diet strip, the promise clock, the goals, the streak, the peak), the shelf, the stamps,
+// the side panels, the chapters, the posts windows, the finale's pages -- keep no such time, so the build lays each
+// with an `enable` that leaves these items' spans out (build-video.mjs chromeOverlayChain, by `regionSpans`), and
+// Play hides them while such an item is on screen (playCore.tsx, `layerOffOver`). One list (`fullFrameItems`), and
+// what each region takes of it (`regionSpans`, by its module's `fullFrame` traits):
+//
+// every region but those below: every item's span --
+// a video entry that hides the chrome (`noChrome`; `deck: "shown"` keeps it): from the frame the dip into it has
+// made black (its start + the dissolve − a frame; mid-dissolve for `enter: "cut"`) to mid-dissolve out of it,
+// or past the cut's end when it is last -- as it always was;
+// every other item: from the first frame its picture is in -- its dissolve's first frame, or, for a teaser that
+// dips, the frame the dip has made black (the dip fades the whole frame, overlays with it) -- to the frame
+// BEFORE the end of its dissolve out (that frame is the next segment's alone), or past the cut's end when it is
+// last. A first item is off from 0.
+// `followsDeck` (shell, dial, odometer, trail, feed): only a video entry's and an analysis item's spans, as the
+// build laid them before (an analysis item's to the end of its dissolve out) -- over a teaser, the intro or a
+// card their own slide away and back is kept.
+// `ownFade` (the finale, the dial's finale, the diet runs): an item's span starts once its dissolve in is over, so
+// the page's own fade out through that dissolve plays whole (a video entry's as above).
+// `drawsMarks` (the stamps): not over a teaser that carries marks -- the stamp is that card's own content.
+//
+// A segment that keeps the deck up is not full frame: a teaser that COUNTS (deck.mjs teaserCounts: marks, no dip),
+// a card under `overCards: "show"`, a video entry with `deck: "shown"`. A cut with no full-frame item: [] -- and
+// every graph is the one it was.
+//
+// A LEAF with no imports: the build, umtool's server and its client (Play) read the same rule.
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r4 = (v) => Math.round(v * 1e4) / 1e4;
+
+/** A module's `fullFrame` traits (contract.mjs): how its region is laid over a full-frame item. */
+export const FULL_FRAME_TRAITS = Object.freeze(["followsDeck", "ownFade", "drawsMarks"]);
+
+/**
+ * Is this schedule segment full frame? A video entry by its `noChrome`, an analysis item always, anything else by
+ * its `hideDeck`.
+ *
+ * @param {{ type?: string, hideDeck?: boolean, noChrome?: boolean } | null | undefined} seg
+ */
+export function fullFrameSegment(seg) {
+ if (!seg) return false;
+ if (seg.type === "video") return !!seg.noChrome;
+ if (seg.type === "analysis") return true;
+ return !!seg.hideDeck;
+}
+
+/**
+ * @typedef {{ id: string, type: string, kind: "video" | "analysis" | "page", index: number, start: number,
+ * end: number, last: boolean, marks: boolean, fps: number, D: number, span: [number, number] }} FullFrameItem
+ * `span` is the item's span as the build laid it before the measure extras were left out (a video entry's
+ * rule; any other's from its first frame to the END of its dissolve out, inclusive).
+ */
+
+/**
+ * The schedule's full-frame items, in order, each with its span and what a region's traits read of it.
+ *
+ * @param {{ segments?: any[], total?: number, fps?: number, transition?: number } | null | undefined} schedule
+ * @returns {FullFrameItem[]}
+ */
+export function fullFrameItems(schedule) {
+ const segs = schedule?.segments ?? [];
+ const D = Number(schedule?.transition ?? 0) || 0;
+ const fps = Number(schedule?.fps ?? 30) || 30;
+ /** @type {FullFrameItem[]} */
+ const out = [];
+ segs.forEach((s, i) => {
+ if (!fullFrameSegment(s) || !fin(Number(s?.start))) return;
+ const start = Number(s.start);
+ const end = fin(Number(s.end)) ? Number(s.end) : start + Number(s.duration);
+ const last = i === segs.length - 1;
+ const kind = s.type === "video" ? "video" : s.type === "analysis" ? "analysis" : "page";
+ let a;
+ let b;
+ if (kind === "video") {
+ a = i > 0 && s.enter ? start + D - 1 / fps : i > 0 ? start + D / 2 : 0;
+ b = last ? Number(schedule.total ?? end) + 1 : end - D / 2;
+ } else {
+ a = i === 0 ? 0 : s.dip ? start + D - 1 / fps : start;
+ b = last ? Number(schedule.total ?? end) + 1 : end;
+ }
+ out.push({
+ id: s.id, type: s.type, kind, index: i, start, end, last,
+ marks: !!(s.claim || (Array.isArray(s.claims) && s.claims.length)),
+ fps, D, span: [Math.max(0, r4(a)), r4(b)],
+ });
+ });
+ return out;
+}
+
+/**
+ * The spans one region leaves out, `[from, to]` cut seconds by start, for its module's `fullFrame` traits (none:
+ * every region but the deck's own and the finale's). Overlapping pairs (two full-frame items back to back) are kept as
+ * they are: `not(between(…)+between(…))` is off over their union. [] without one.
+ *
+ * @param {FullFrameItem[]} items
+ * @param {{ followsDeck?: boolean, ownFade?: boolean, drawsMarks?: boolean } | null | undefined} [traits]
+ * @returns {Array<[number, number]>}
+ */
+export function regionSpans(items, traits = {}) {
+ const t = traits ?? {};
+ /** @type {Array<[number, number]>} */
+ const out = [];
+ for (const it of items ?? []) {
+ if (t.followsDeck) {
+ if (it.kind !== "page") out.push([it.span[0], it.span[1]]);
+ continue;
+ }
+ if (t.drawsMarks && it.type === "teaser" && it.marks) continue;
+ let [a, b] = it.span;
+ // The frame at the end of its dissolve out is the next segment's alone: the layer is drawn on it.
+ if (it.kind !== "video" && !it.last) b = r4(b - 1 / it.fps);
+ // Its own fade out through the dissolve in plays whole.
+ if (t.ownFade && it.kind !== "video" && it.index > 0) a = Math.max(a, r4(it.start + it.D));
+ if (b >= a) out.push([a, b]);
+ }
+ return out.sort((x, y) => x[0] - y[0]);
+}
+
+/**
+ * The spans a region with no traits leaves out (the measure extras, the stamps, every side panel): `regionSpans`
+ * with none. `only` narrows the items (video-entry.mjs videoBlackouts: the video entries' alone).
+ *
+ * @param {{ segments?: any[], total?: number, fps?: number, transition?: number } | null | undefined} schedule
+ * @param {{ only?: (item: FullFrameItem) => boolean }} [opts]
+ */
+export function fullFrameSpans(schedule, { only = () => true } = {}) {
+ return regionSpans(fullFrameItems(schedule).filter(only));
+}
+
+/** The items' spans as the build laid them before (`span`), of one kind: a video entry's, an analysis item's. */
+export function itemSpans(schedule, kind) {
+ return fullFrameItems(schedule).filter((it) => it.kind === kind).map((it) => /** @type {[number, number]} */ ([it.span[0], it.span[1]]));
+}
+
+/**
+ * PLAY: is a layer with these traits hidden while `item` (a full-frame item, or null) is the one on screen, at cut
+ * second `tc`? Play cuts at mid-dissolve, so "over it" is while it is on screen. A `followsDeck` layer hides itself;
+ * the stamps stay over a teaser with marks; an `ownFade` page goes once the dissolve into the item is over.
+ *
+ * @param {FullFrameItem | null | undefined} item
+ * @param {{ followsDeck?: boolean, ownFade?: boolean, drawsMarks?: boolean } | null | undefined} traits
+ * @param {number} tc
+ */
+export function layerOffOver(item, traits, tc) {
+ if (!item) return false;
+ const t = traits ?? {};
+ if (t.followsDeck) return false;
+ if (t.drawsMarks && item.type === "teaser" && item.marks) return false;
+ if (t.ownFade && item.kind !== "video" && item.index > 0) return tc >= item.start + item.D;
+ return true;
+}
+
+/** The ids of the schedule's full-frame segments. */
+export function fullFrameIds(schedule) {
+ return new Set((schedule?.segments ?? []).filter(fullFrameSegment).map((s) => s.id));
+}
diff --git a/umtool/report-to-video/modules/contract.mjs b/umtool/report-to-video/modules/contract.mjs
@@ -32,6 +32,8 @@
// imported by the build, the composer and umtool alike.
/** What a module is: how its pixels reach the cut. */
+import { FULL_FRAME_TRAITS } from "../full-frame.mjs";
+
export const MODULE_KINDS = Object.freeze([
// A page over the whole cut (or a window of it), laid by its region at frame 1.
"overlay-whole",
@@ -117,6 +119,7 @@ const SPEC = Object.freeze({
names: "a function ({ preview, window, entry, suffix }) => { project, stem }",
entry: "a function (manifest, segment) => the timeline entry a segment module draws",
seconds: "a function (entry, transition, fps) => how long a segment module's page is",
+ fullFrame: "how its region is laid over a full-frame item (full-frame.mjs): { followsDeck?, ownFade?, drawsMarks? } -- each true; absent, it is off over every one",
});
/**
@@ -185,6 +188,13 @@ export function defineModule(def) {
if (def.docs !== undefined && !(isObj(def.docs) && typeof def.docs.heading === "string")) throw new Error(`${where}: docs must be ${SPEC.docs}`);
if (def.vertical !== undefined && !(isObj(def.vertical) && VERTICAL_SLOTS.includes(def.vertical.slot))) throw new Error(`${where}: vertical must be ${SPEC.vertical}`);
if (def.workers !== undefined && !["wide", "narrow"].includes(def.workers)) throw new Error(`${where}: workers must be ${SPEC.workers}`);
+ if (def.fullFrame !== undefined) {
+ const f = def.fullFrame;
+ if (!isObj(f) || !Object.keys(f).length || Object.entries(f).some(([k, v]) => !FULL_FRAME_TRAITS.includes(k) || v !== true)) {
+ throw new Error(`${where}: fullFrame must be ${SPEC.fullFrame}`);
+ }
+ if (!(def.kind === "overlay-whole" || def.kind === "overlay-window")) throw new Error(`${where}: only an overlay is laid over a full-frame item`);
+ }
return Object.freeze({ ...def });
}
diff --git a/umtool/report-to-video/modules/dial-finale.mjs b/umtool/report-to-video/modules/dial-finale.mjs
@@ -35,6 +35,8 @@ export default defineModule({
],
},
region: "dial-finale",
+ // Out through the finale's dissolve, as the finale: full-frame.mjs `ownFade`.
+ fullFrame: { ownFade: true },
workers: "narrow",
noun: "the dial finale's",
on: (schedule, render) => !!schedule?.finale && hasMeasure(schedule) && wanted(render),
diff --git a/umtool/report-to-video/modules/dial.mjs b/umtool/report-to-video/modules/dial.mjs
@@ -70,6 +70,8 @@ export default defineModule({
],
},
region: "dial",
+ // It comes and goes with the deck (chrome-instruments.mjs): full-frame.mjs `followsDeck`.
+ fullFrame: { followsDeck: true },
workers: "narrow",
noun: "the dial's",
on: (schedule, render) => hasMeasure(schedule) && !!resolveDial(render),
diff --git a/umtool/report-to-video/modules/feed.mjs b/umtool/report-to-video/modules/feed.mjs
@@ -42,6 +42,8 @@ export default defineModule({
],
},
region: "feed",
+ // The column slides with the deck's visibility (chrome-feed.mjs): full-frame.mjs `followsDeck`.
+ fullFrame: { followsDeck: true },
workers: "wide",
noun: "the feed's",
on: (schedule) => schedule?.layout === "feed",
diff --git a/umtool/report-to-video/modules/finale.mjs b/umtool/report-to-video/modules/finale.mjs
@@ -47,6 +47,9 @@ export default defineModule({
],
},
region: "finale",
+ // Its page fades out through the dissolve after the run: over a full-frame item it is left out only once that
+ // dissolve is over (full-frame.mjs `ownFade`).
+ fullFrame: { ownFade: true },
workers: "narrow",
noun: "the finale's",
on: (schedule) => !!schedule?.finale,
diff --git a/umtool/report-to-video/modules/odometer.mjs b/umtool/report-to-video/modules/odometer.mjs
@@ -44,6 +44,8 @@ export default defineModule({
],
},
region: "odometer",
+ // It comes and goes with the deck (chrome-instruments.mjs): full-frame.mjs `followsDeck`.
+ fullFrame: { followsDeck: true },
workers: "narrow",
noun: "the odometer's",
on: (schedule, render) => hasMeasure(schedule) && !!resolveOdometer(render),
diff --git a/umtool/report-to-video/modules/runs-finale.mjs b/umtool/report-to-video/modules/runs-finale.mjs
@@ -32,6 +32,8 @@ export default defineModule({
],
},
region: "runs-finale",
+ // In the finale's page, out with it: full-frame.mjs `ownFade`.
+ fullFrame: { ownFade: true },
workers: "narrow",
noun: "the finale's diet runs'",
on: drawn,
diff --git a/umtool/report-to-video/modules/shell.mjs b/umtool/report-to-video/modules/shell.mjs
@@ -48,12 +48,15 @@ export default defineModule({
["`deck.height`", "120–400 px · default 190", "`umtool look <p> deck.height=210`"],
["`deck.footageScale`", "0.5–1 (the footage must fit above the deck) · default 0.82", "`umtool look <p> deck.footageScale=0.8`"],
["`deck.background`", "`panel` · `flush` · default `panel`", "`umtool look <p> deck.background=flush`"],
- ["`deck.overCards`", "`hide` (the deck slides away over a card) · `show` · default `hide`", "`umtool look <p> deck.overCards=show`"],
+ ["`deck.overCards`", "`hide` (the deck slides away over a card, and the layers that keep no time of their own are left out over it: a full-frame item, [report-video.md](report-video.md#no-chrome-over-a-full-frame-item)) · `show` (the deck and every layer stay over it) · default `hide`", "`umtool look <p> deck.overCards=show`"],
["`deck.title`", "`{size 24–96, maxChars 10–120}` · default 54, 48", "`umtool look <p> deck.title='{\"size\":60}'`"],
["`deck.motion`", "`{out 0–2, in 0–2, pip 0–3}` s · default 0.3, 0.45, 0.7", "`umtool look <p> deck.motion='{\"in\":0.6}'`"],
],
},
region: "deck",
+ // It slides away over a full-frame item and back on its own (deckChoreography): only a video entry's and an
+ // analysis item's spans are left out of it (full-frame.mjs).
+ fullFrame: { followsDeck: true },
workers: "wide",
noun: "the deck's",
on: () => true,
diff --git a/umtool/report-to-video/modules/stamp.mjs b/umtool/report-to-video/modules/stamp.mjs
@@ -43,6 +43,8 @@ export default defineModule({
],
},
region: "stamp",
+ // A teaser that carries marks keeps its stamps (they are the card's own content): full-frame.mjs `drawsMarks`.
+ fullFrame: { drawsMarks: true },
workers: "narrow",
noun: "the stamps'",
on: (schedule, render) => stampsDrawn(schedule, render),
diff --git a/umtool/report-to-video/modules/teaser.mjs b/umtool/report-to-video/modules/teaser.mjs
@@ -19,7 +19,7 @@ export default defineModule({
validate: (_value, { manifest }) => validateTeasers(manifest),
docs: {
heading: "Teaser",
- intro: "A timeline entry `{ type: \"teaser\", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)).",
+ intro: "A timeline entry `{ type: \"teaser\", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)). Full frame: the deck, the instruments and the feed slide away over it, and every layer that keeps no time of its own -- the diet strip, the promise clock, the goals, the streak, the side panels, the chapters, the finale's pages -- is left out from its first frame (a dip's black) to the frame before its dissolve out ends ([report-video.md](report-video.md#no-chrome-over-a-full-frame-item)); its stamps stay when it carries marks; a teaser that counts (marks, no dip) keeps the deck and every layer up.",
rows: [
["a `teaser` entry", "`lines` (each `{text, role?, hold?, …}`), `tail?`, `dip?`", "`umtool timeline <p> insert …`"],
],
diff --git a/umtool/report-to-video/modules/trail.mjs b/umtool/report-to-video/modules/trail.mjs
@@ -50,6 +50,8 @@ export default defineModule({
],
},
region: "trail",
+ // It comes and goes with the deck (chrome-instruments.mjs): full-frame.mjs `followsDeck`.
+ fullFrame: { followsDeck: true },
workers: "narrow",
noun: "the trail's",
on: (schedule, render) => hasMeasure(schedule) && !!resolveTrail(render),
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -19,6 +19,7 @@
"exports": {
"./attribution": "./attribution.mjs",
"./video-entry": "./video-entry.mjs",
+ "./full-frame": "./full-frame.mjs",
"./analysis-plan": "./analysis-plan.mjs",
"./site-links": "./site-links.mjs",
"./brand": "./brand.mjs",
diff --git a/umtool/report-to-video/teaser-chrome-off.test.mjs b/umtool/report-to-video/teaser-chrome-off.test.mjs
@@ -0,0 +1,371 @@
+// NO CHROME OVER A TEASER, OR ANY OTHER FULL-FRAME ITEM (lane teaser-chrome, 13 Nov: the diet strip and the promise
+// clock were drawn over a teaser -- the leak the analysis item had, analysis-chrome-off.test.mjs). Every overlay
+// module that keeps no time of its own (the measure extras, the stamps, the side panels, the chapters, the finale's
+// pages) gets an `enable` that leaves each full-frame item's span out (full-frame.mjs fullFrameItems / regionSpans,
+// build-video.mjs chromeOverlayChain): a teaser that hides the deck, the brand intro, a card under `overCards:
+// "hide"`, as the video entry and the analysis item already were. The regions that follow the deck's choreography
+// (`followsDeck`: the shell, the dial, the odometer, the trail, the feed) keep exactly the blackouts they had --
+// their own slide away and back over a teaser is kept. A teaser that counts, a card under `overCards: "show"` and a
+// video entry with `deck: "shown"` keep their chrome; a cut with none of them lays exactly the graph it did.
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { chromeBlackouts, chromeOverlayChain, xfadeConcatArgs } from "./build-video.mjs";
+import { analysisBlackouts } from "./analysis-plan.mjs";
+import { chapterWindows } from "./chrome-story.mjs";
+import { deckSchedule, estimateSchedule, scheduleFrom } from "./deck.mjs";
+import { fullFrameIds, fullFrameItems, fullFrameSegment, fullFrameSpans, layerOffOver, regionSpans } from "./full-frame.mjs";
+import { deckOverlays, moduleOfRegion } from "./modules/index.mjs";
+import { blackoutEnable, videoBlackouts } from "./video-entry.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures/measure-extras/measure.json"), "utf8"));
+const RENDER = {
+ width: 1920, height: 1080, fps: 30,
+ palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, odometer: true, trail: true, diet: {}, goals: {}, promise: {}, peak: true, streak: {} } },
+};
+const D = 0.4;
+const FPS = 30;
+// A clip to 400.4 s, a teaser 400.0–406.4 (dissolved in and out), the clips after it to 739.6.
+const SCHEDULE = {
+ kind: "deck", fps: FPS, total: 739.6, transition: D,
+ segments: [
+ { id: "a", type: "clip", start: 0, duration: 400.4, end: 400.4, hideDeck: false },
+ { id: "t", type: "teaser", start: 400, duration: 6.4, end: 406.4, hideDeck: true },
+ { id: "b", type: "clip", start: 406, duration: 333.6, end: 739.6, hideDeck: false },
+ ],
+ measure: MEASURE,
+};
+
+/** Each overlay's enable, as a predicate of cut second t (blackoutEnable's `not(between(...)+...)`). */
+function enabledAt(part, t) {
+ const m = /enable='not\((.*)\)'/.exec(part);
+ if (!m) return true;
+ const spans = [...m[1].matchAll(/between\(t,(-?[\d.]+),(-?[\d.]+)\)/g)].map((x) => [Number(x[1]), Number(x[2])]);
+ return !spans.some(([a, b]) => t >= a && t <= b);
+}
+
+/** Every overlay part of the full cut's chain for `schedule`, one per region, with the module that laid it. */
+function overlayParts(schedule) {
+ const on = deckOverlays().filter((m) => m.on(schedule, RENDER));
+ const regions = on.flatMap((m) => m.regions(schedule, { render: RENDER, outDir: "/out", frames: `/out/chrome/${m.region}-frames`, shift: 0 }).map((r) => ({ ...r, mod: m.id })));
+ const blackouts = chromeBlackouts(schedule);
+ const chain = chromeOverlayChain(RENDER, regions, "[0:v]", 1, { blackouts });
+ const parts = chain.chain.split(";").filter((p) => p.includes("overlay="));
+ assert.equal(parts.length, regions.length);
+ return { ids: on.map((m) => m.id), parts: parts.map((p, i) => ({ part: p, mod: regions[i].mod })), blackouts };
+}
+
+/** Every frame from `a` to `b` cut seconds (inclusive), as seconds. */
+const frames = (a, b) => {
+ const out = [];
+ for (let f = Math.round(a * FPS); f <= Math.round(b * FPS); f += 1) out.push(f / FPS);
+ return out;
+};
+
+const END = Math.round((406.4 - 1 / FPS) * 1e4) / 1e4; // the frame before the end of its dissolve out
+
+// THE LEAKING LAYERS, one test each: the measure extras (the diet strip, the promise clock, the goals, the streak,
+// the peak) -- off from the teaser's first frame to the frame before its dissolve out ends.
+{
+ const { ids } = overlayParts(SCHEDULE);
+ for (const id of ["diet", "promise", "goals", "streak", "peak"]) {
+ test(`over a teaser: ${id}'s region is off from the teaser's first frame to its last, and only there`, () => {
+ assert.ok(ids.includes(id), `${id} is laid (${ids.join(", ")})`);
+ const { parts } = overlayParts(SCHEDULE);
+ assert.deepEqual(fullFrameSpans(SCHEDULE), [[400, END]]);
+ const mine = parts.filter((p) => p.mod === id);
+ assert.ok(mine.length >= 1);
+ for (const { part } of mine) {
+ // Its dissolve in (400.0–400.4), its page, its dissolve out (406.0–406.4) but its last frame.
+ for (const t of frames(400, END)) assert.equal(enabledAt(part, t), false, `${id} at ${t}`);
+ assert.equal(enabledAt(part, 400 - 1 / FPS), true, `${id} the frame before`);
+ // The frame at 406.4 is the next clip's alone: the layer is on it.
+ assert.equal(enabledAt(part, 406.4), true, `${id} the end frame`);
+ assert.equal(enabledAt(part, 100), true);
+ }
+ });
+ }
+ // THE DECK'S OWN REGIONS keep their slide: the enable main laid (none over a teaser), byte for byte.
+ for (const id of ["shell", "dial", "odometer", "trail"]) {
+ test(`over a teaser: ${id} follows the deck -- no enable of its own, as before`, () => {
+ assert.ok(ids.includes(id));
+ for (const { part } of overlayParts(SCHEDULE).parts.filter((p) => p.mod === id)) assert.doesNotMatch(part, /enable=/);
+ });
+ }
+}
+
+test("a teaser that dips: off from the frame the dip has made black (the clip's last) to the frame before its dissolve out ends", () => {
+ const sch = { ...SCHEDULE, segments: SCHEDULE.segments.map((s) => (s.id === "t" ? { ...s, dip: { fade: 1, black: 0.5 } } : s)) };
+ const [[a, b]] = fullFrameSpans(sch);
+ assert.equal(a, Math.round((400 + D - 1 / FPS) * 1e4) / 1e4);
+ assert.equal(b, END);
+ // The dip fades the whole frame, overlays with it, until then: the chrome is there to fade.
+ const { parts } = overlayParts(sch);
+ for (const { part, mod } of parts) {
+ if (["shell", "dial", "odometer", "trail"].includes(mod)) continue;
+ assert.equal(enabledAt(part, 400.3), true, mod);
+ for (const t of frames(400.4, END)) assert.equal(enabledAt(part, t), false, `${mod} at ${t}`);
+ }
+});
+
+test("a teaser at the very start (before the deck is up): off from 0", () => {
+ const sch = {
+ ...SCHEDULE, total: 339.6,
+ segments: [{ id: "t", type: "teaser", start: 0, duration: 6.4, end: 6.4, hideDeck: true }, { id: "b", type: "clip", start: 6, duration: 333.6, end: 339.6 }],
+ };
+ assert.deepEqual(fullFrameSpans(sch), [[0, Math.round((6.4 - 1 / FPS) * 1e4) / 1e4]]);
+});
+
+test("back-to-back teasers: off over both and the dissolve between them; a last one to past the cut's end", () => {
+ const sch = {
+ ...SCHEDULE, total: 412.4,
+ segments: [
+ SCHEDULE.segments[0],
+ { id: "t1", type: "teaser", start: 400, duration: 6.4, end: 6.4 + 400, hideDeck: true },
+ { id: "t2", type: "teaser", start: 406, duration: 6.4, end: 412.4, hideDeck: true },
+ ],
+ };
+ assert.deepEqual(fullFrameSpans(sch), [[400, END], [406, 413.4]]);
+ const { parts } = overlayParts(sch);
+ for (const { part, mod } of parts) {
+ if (["shell", "dial", "odometer", "trail"].includes(mod)) continue;
+ for (const t of frames(400, 412.4)) assert.equal(enabledAt(part, t), false, `${mod} at ${t}`);
+ assert.equal(enabledAt(part, 400 - 1 / FPS), true);
+ }
+});
+
+test("in a window of the cut (--cut-window, a preview, a chunk) the span is shifted to the window's clock; a span before it is negative", () => {
+ const regions = deckOverlays().filter((m) => m.id === "diet").flatMap((m) => m.regions(SCHEDULE, { render: RENDER, outDir: "/out", frames: "/f" }));
+ const chain = chromeOverlayChain(RENDER, regions, "[0:v]", 1, { blackouts: chromeBlackouts(SCHEDULE), shift: 398 });
+ const part = chain.chain.split(";").find((p) => p.includes("overlay="));
+ assert.equal(enabledAt(part, 2), false);
+ assert.equal(enabledAt(part, 1.9), true);
+ assert.equal(enabledAt(part, 8.4), true);
+ // A window that starts after the teaser: its span is in the window's past.
+ const later = chromeOverlayChain(RENDER, regions, "[0:v]", 1, { blackouts: chromeBlackouts(SCHEDULE), shift: 410 });
+ const lp = later.chain.split(";").find((p) => p.includes("overlay="));
+ assert.match(lp, /between\(t,-10,-3\.6333\)/);
+ assert.equal(enabledAt(lp, 0), true);
+});
+
+// ---- the traits: the finale's fade out, the stamps over a card with marks ----------------------------------------
+
+test("ownFade (the finale's pages): over a teaser it is left out only once the dissolve into it is over", () => {
+ const items = fullFrameItems(SCHEDULE);
+ assert.deepEqual(regionSpans(items, { ownFade: true }), [[400.4, END]]);
+ for (const name of ["finale", "dial-finale", "runs-finale"]) assert.equal(moduleOfRegion(name)?.fullFrame?.ownFade, true, name);
+ const chain = chromeOverlayChain(RENDER, [{ name: "finale", frames: "/f/finale", x: 0, y: 0, offset: 390 }], "[0:v]", 1, { blackouts: items });
+ const part = chain.chain.split(";").find((p) => p.includes("overlay="));
+ for (const t of frames(400, 400.4 - 1 / FPS)) assert.equal(enabledAt(part, t), true, `the fade out at ${t}`);
+ assert.equal(enabledAt(part, 400.4), false);
+});
+
+test("drawsMarks (the stamps): a teaser that dips and carries marks keeps its stamps; the other layers go", () => {
+ const sch = { ...SCHEDULE, segments: SCHEDULE.segments.map((s) => (s.id === "t" ? { ...s, dip: { fade: 1, black: 0.5 }, claim: { id: "t", verdict: "L" } } : s)) };
+ const items = fullFrameItems(sch);
+ assert.equal(items[0].marks, true);
+ assert.deepEqual(regionSpans(items, { drawsMarks: true }), []);
+ const chain = chromeOverlayChain(RENDER, [{ name: "stamp", frames: "/f/stamp", x: 0, y: 0 }, { name: "diet", frames: "/f/diet", x: 0, y: 0 }], "[0:v]", 1, { blackouts: items });
+ const [stamp, diet] = chain.chain.split(";").filter((p) => p.includes("overlay="));
+ assert.doesNotMatch(stamp, /enable=/);
+ assert.equal(enabledAt(diet, 403), false);
+ // A teaser without marks: the stamps' region is off over it as any other.
+ assert.deepEqual(regionSpans(fullFrameItems(SCHEDULE), { drawsMarks: true }), [[400, END]]);
+});
+
+test("a chapter bumper on the clip after a full-frame item starts when the item's span ends, its entrance whole", () => {
+ const r = { ...RENDER, chrome: { ...RENDER.chrome, chapter: { list: [{ at: "b", title: "Part two" }] } } };
+ const [w] = chapterWindows(SCHEDULE, r);
+ assert.equal(w.segment, "b");
+ assert.equal(w.from, 406.4);
+ assert.equal(w.to, 409.4);
+ // After a clip: with its clip, as ever.
+ const clips = { ...SCHEDULE, segments: SCHEDULE.segments.map((s) => (s.id === "t" ? { ...s, type: "clip", hideDeck: false } : s)) };
+ assert.equal(chapterWindows(clips, r)[0].from, 406);
+});
+
+test("Play: a layer is off while a full-frame item is on screen, by the same traits", () => {
+ const [it] = fullFrameItems(SCHEDULE);
+ assert.equal(layerOffOver(it, null, 403), true);
+ assert.equal(layerOffOver(it, { followsDeck: true }, 403), false);
+ assert.equal(layerOffOver(it, { ownFade: true }, 400.3), false);
+ assert.equal(layerOffOver(it, { ownFade: true }, 400.4), true);
+ assert.equal(layerOffOver(it, { drawsMarks: true }, 403), true);
+ assert.equal(layerOffOver({ ...it, marks: true }, { drawsMarks: true }, 403), false);
+ assert.equal(layerOffOver(null, null, 403), false);
+});
+
+// ---- which segments are full frame: the deck's own rule (deck.mjs hidesDeck), from real schedules ---------------
+
+const card = (extra = {}) => ({ type: "teaser", id: "tz", seconds: 5, lines: [{ text: "A line", role: "kicker" }], ...extra });
+const manifestWith = (mid, render = {}) => ({
+ provenance: {}, posts: [],
+ render: { width: 1920, height: 1080, fps: 30, transition: 0.5, chrome: { engine: "hyperframes", layout: "deck", deck: { counter: { series: [{ id: "L", label: "L", color: "#5b9bd5" }] } } }, ...render },
+ timeline: [
+ { type: "clip", id: "c1", video: "v1", start: 0, end: 10 },
+ mid,
+ { type: "clip", id: "c2", video: "v2", start: 0, end: 10 },
+ ],
+});
+const less = (v) => Math.round((v - 1 / 30) * 1e4) / 1e4;
+
+test("a teaser that hides the deck is full frame; a teaser that COUNTS keeps the deck, and every layer with it", () => {
+ const plain = estimateSchedule(manifestWith(card()));
+ const seg = plain.segments[1];
+ assert.equal(seg.hideDeck, true);
+ assert.equal(fullFrameSegment(seg), true);
+ assert.deepEqual(fullFrameSpans(plain), [[seg.start, less(seg.end)]]);
+ assert.deepEqual([...fullFrameIds(plain)], ["tz"]);
+ const counts = estimateSchedule(manifestWith(card({ claim: { id: "tz", verdict: "L", at: 1 } })));
+ assert.equal(counts.segments[1].hideDeck, false);
+ assert.deepEqual(chromeBlackouts(counts), []);
+ assert.equal(fullFrameIds(counts).size, 0);
+});
+
+test("a card under overCards: hide (the default) is full frame; under overCards: show it keeps its chrome", () => {
+ const k = { type: "card", id: "k1", seconds: 3, heading: "Part two" };
+ const hide = estimateSchedule(manifestWith(k));
+ assert.equal(hide.segments[1].hideDeck, true);
+ assert.deepEqual(fullFrameSpans(hide), [[hide.segments[1].start, less(hide.segments[1].end)]]);
+ const m = manifestWith(k);
+ m.render.chrome.deck.overCards = "show";
+ assert.deepEqual(chromeBlackouts(estimateSchedule(m)), []);
+});
+
+test("the brand intro (the first segment, full frame): off from 0 to the frame before its dissolve into the first entry ends", () => {
+ const render = { width: 1920, height: 1080, fps: 30, chrome: { engine: "hyperframes", layout: "deck", deck: {} } };
+ const entries = [{ type: "intro", id: "brand-intro" }, { type: "clip", id: "c1", video: "v1", start: 0, end: 10 }];
+ const doc = deckSchedule({ entries, durs: [4.18, 10], D: 0.5, render });
+ assert.equal(doc.segments[0].hideDeck, true);
+ assert.deepEqual(fullFrameSpans(doc), [[0, less(doc.segments[0].end)]]);
+ assert.deepEqual(regionSpans(chromeBlackouts(doc), { followsDeck: true }), []);
+});
+
+test("the deck's own regions are laid as main laid them: a video entry's and an analysis item's spans alone (pinned)", () => {
+ const sch = {
+ fps: 30, transition: 0.4, total: 60, segments: [
+ { id: "a", type: "clip", start: 0, end: 10.4, duration: 10.4 },
+ { id: "v", type: "video", start: 10, end: 20.4, duration: 10.4, hideDeck: true, noChrome: true, enter: { out: 0.5, in: 0.5 } },
+ { id: "b", type: "clip", start: 20, end: 30.4, duration: 10.4 },
+ { id: "vc", type: "video", start: 30, end: 40.4, duration: 10.4, hideDeck: true, noChrome: true },
+ { id: "an", type: "analysis", start: 40, end: 47.4, duration: 7.4, hideDeck: true },
+ { id: "tz", type: "teaser", start: 47, end: 53.4, duration: 6.4, hideDeck: true },
+ { id: "c", type: "clip", start: 53, end: 60, duration: 7 },
+ ],
+ };
+ // Literals printed by the build at main bf1b4f461 (chromeBlackouts = videoBlackouts + analysisBlackouts; the
+ // teaser was not one).
+ const main = [[10.3667, 20.2], [30.2, 40.2], [40, 47.4]];
+ const items = chromeBlackouts(sch);
+ assert.deepEqual(regionSpans(items, { followsDeck: true }), main);
+ assert.deepEqual(videoBlackouts(sch), main.slice(0, 2));
+ assert.deepEqual(analysisBlackouts(sch), [[40, 47.4]]);
+ for (const name of ["deck", "dial", "odometer", "trail", "feed"]) {
+ assert.equal(moduleOfRegion(name)?.fullFrame?.followsDeck, true, name);
+ const chain = chromeOverlayChain(RENDER, [{ name, frames: `/f/${name}`, x: 0, y: 0 }], "[0:v]", 1, { blackouts: items });
+ assert.ok(chain.chain.includes(`shortest=1${blackoutEnable(main)}[`), `${name}: ${chain.chain}`);
+ }
+ // Every other region: the video spans as they were, the analysis and the teaser to the frame before their ends.
+ assert.deepEqual(fullFrameSpans(sch), [[10.3667, 20.2], [30.2, 40.2], [40, less(47.4)], [47, less(53.4)]]);
+ assert.deepEqual(regionSpans(chromeBlackouts({ ...sch, total: 47.4, segments: sch.segments.slice(0, 5) }), { followsDeck: true }), [[10.3667, 20.2], [30.2, 40.2], [40, 48.4]]);
+ assert.deepEqual(regionSpans(chromeBlackouts({ ...sch, total: 40.4, segments: sch.segments.slice(0, 4) }), { followsDeck: true }), [[10.3667, 20.2], [30.2, 41.4]]);
+ // A video entry with deck: "shown" keeps the chrome.
+ const shown = { ...sch, segments: sch.segments.map((s) => (s.id === "v" ? { ...s, hideDeck: false, noChrome: undefined } : s)) };
+ assert.deepEqual(videoBlackouts(shown), [[30.2, 40.2]]);
+});
+
+test("a cut with no full-frame item: no blackouts, and the overlay chain is byte for byte the one it was", () => {
+ const clips = { ...SCHEDULE, segments: [SCHEDULE.segments[0], { ...SCHEDULE.segments[2], start: 400, duration: 339.6 }] };
+ assert.deepEqual(chromeBlackouts(clips), []);
+ assert.equal(fullFrameIds(clips).size, 0);
+ const on = deckOverlays().filter((m) => m.on(clips, RENDER));
+ const regions = on.flatMap((m) => m.regions(clips, { render: RENDER, outDir: "/out", frames: `/out/chrome/${m.region}-frames`, shift: 0 }));
+ const plain = chromeOverlayChain(RENDER, regions, "[0:v]", 1, {});
+ // renderDeck passes `blackouts` only when there is one (`...(blackouts.length ? { blackouts } : {})`).
+ const bo = chromeBlackouts(clips);
+ const laid = chromeOverlayChain(RENDER, regions, "[0:v]", 1, bo.length ? { blackouts: bo } : {});
+ assert.equal(laid.chain, plain.chain);
+ assert.deepEqual(laid.inputs, plain.inputs);
+ assert.doesNotMatch(laid.chain, /enable=/);
+});
+
+// ---- real ffmpeg: a few seconds at 320x180 -----------------------------------------------------------------------
+
+const have = spawnSync("ffmpeg", ["-version"]).status === 0;
+const ff = (args) => {
+ const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args], { maxBuffer: 1 << 28 });
+ assert.equal(r.status, 0, String(r.stderr));
+ return r.stdout;
+};
+
+test("ffmpeg: over a teaser's frames no diet-strip pixel is drawn, on the clips either side it is; the deck's band is laid as before",
+ { skip: !have && "no ffmpeg" }, () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "teaser-chrome-"));
+ try {
+ const W = 320, H = 180, Dx = 0.5;
+ // Three lossless segments: two dark clips, a mid-grey teaser between them.
+ const seg = (name, seconds, color) => {
+ const f = path.join(dir, `${name}.mov`);
+ ff(["-f", "lavfi", "-i", `color=c=${color}:s=${W}x${H}:r=30:d=${seconds}`, "-f", "lavfi", "-i", `anullsrc=r=48000:cl=stereo`,
+ "-t", String(seconds), "-map", "0:v", "-map", "1:a", "-c:v", "ffv1", "-pix_fmt", "yuv420p", "-c:a", "pcm_s16le", f]);
+ return f;
+ };
+ const durs = [2, 2, 2];
+ const segs = [seg("a", 2, "0x202020"), seg("t", 2, "0x808080"), seg("b", 2, "0x202020")];
+ const { starts, total } = scheduleFrom(durs, Dx);
+ const schedule = {
+ fps: 30, transition: Dx, total,
+ segments: ["a", "t", "b"].map((id, i) => ({ id, type: id === "t" ? "teaser" : "clip", start: starts[i], duration: durs[i], end: starts[i] + durs[i], hideDeck: id === "t" })),
+ };
+ const blackouts = chromeBlackouts(schedule);
+ assert.deepEqual(fullFrameSpans(schedule), [[1.5, 3.4667]]);
+ // White, opaque stand-ins for the deck's band and the diet strip, as long as the cut.
+ const n = Math.round(total * 30);
+ const seq = (name, w, h) => {
+ const d = path.join(dir, `${name}-frames`);
+ mkdirSync(d);
+ ff(["-f", "lavfi", "-i", `color=c=white:s=${w}x${h}:r=30`, "-frames:v", String(n), "-start_number", "1", path.join(d, "frame_%06d.png")]);
+ return d;
+ };
+ const regions = [
+ { name: "deck", frames: seq("deck", W, 30), x: 0, y: 150, width: W, height: 30 },
+ { name: "diet", frames: seq("diet", 60, 40), x: 10, y: 10, width: 60, height: 40 },
+ ];
+ const R = { width: W, height: H, fps: 30, transition: Dx, audioRate: 48000, audioChannels: 2 };
+ const picture = (chrome) => {
+ const args = xfadeConcatArgs({ segments: segs, durs, render: R, outPath: "-", chrome });
+ const inputs = args.slice(4, args.indexOf("-filter_complex"));
+ const fc = args[args.indexOf("-filter_complex") + 1];
+ const [v, a] = args.filter((_, i) => args[i - 1] === "-map");
+ // The sound to a null muxer (an unmapped graph output is refused; an in-graph nullsink aborts ffmpeg 7.1).
+ const pic = ff([...inputs, "-filter_complex", fc, "-map", v, "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", "-map", a, "-f", "null", "-"]);
+ const size = W * H * 1.5;
+ const out = [];
+ for (let o = 0; o + size <= pic.length; o += size) out.push(pic.subarray(o, o + size));
+ return out;
+ };
+ const bare = picture(null);
+ const laid = picture({ regions, outLabel: "[hfout]", blackouts });
+ assert.equal(laid.length, n);
+ const luma = (frame, x, y) => frame[y * W + x];
+ const [dx, dy] = [40, 30]; // inside the diet strip
+ const [kx, ky] = [160, 165]; // inside the deck's band: it follows the deck (its own page hides it), never cut
+ for (let f = 0; f < n; f += 1) {
+ const t = f / 30;
+ // Frames 45 (1.5 s, the dissolve's first) to 104; frame 105 (3.5 s) is the next clip's alone.
+ const off = f >= 45 && f <= 104;
+ if (off) assert.equal(luma(laid[f], dx, dy), luma(bare[f], dx, dy), `frame ${f} (${t.toFixed(3)} s): the teaser's own pixel`);
+ else assert.ok(luma(laid[f], dx, dy) > 230, `frame ${f} (${t.toFixed(3)} s): the diet stand-in is drawn (${luma(laid[f], dx, dy)})`);
+ assert.ok(luma(laid[f], kx, ky) > 230, `frame ${f}: the deck stand-in is laid as before`);
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
diff --git a/umtool/report-to-video/video-entry.mjs b/umtool/report-to-video/video-entry.mjs
@@ -34,6 +34,7 @@
import { NARRATION_DEFAULTS } from "./narration.mjs";
import { POST_NARRATION_DEFAULTS } from "./post-narration.mjs";
+import { itemSpans } from "./full-frame.mjs";
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const fin = (v) => typeof v === "number" && Number.isFinite(v);
@@ -261,24 +262,13 @@ export function videoSegmentKey({ entry, file, render, lead, target = null }) {
* segments: each video entry that hides it, from the frame the dip into it
* has made black (the segment's start + the dissolve − a frame; mid-dissolve
* for `enter: "cut"`) to its end (mid-dissolve into the next, or the cut's
- * end). Empty for a cut without one -- and then nothing changes.
+ * end). Empty for a cut without one -- and then nothing changes. The video
+ * entries' share of the full-frame items (full-frame.mjs fullFrameItems,
+ * which the build lays every chrome region's `enable` from).
*
* @param {{ segments: Array<{ type: string, start: number, end: number, noChrome?: boolean, dip?: object }>, total: number, fps?: number, transition?: number }} schedule
*/
-export function videoBlackouts(schedule) {
- const segs = schedule?.segments ?? [];
- const D = Number(schedule?.transition ?? 0) || 0;
- const fps = Number(schedule?.fps ?? 30) || 30;
- const out = [];
- segs.forEach((s, i) => {
- if (s.type !== "video" || !s.noChrome) return;
- const entered = i > 0 && s.enter ? s.start + D - 1 / fps : i > 0 ? s.start + D / 2 : 0;
- const last = i === segs.length - 1;
- const b = last ? Number(schedule.total ?? s.end) + 1 : s.end - D / 2;
- out.push([Math.max(0, Math.round(entered * 1e4) / 1e4), Math.round(b * 1e4) / 1e4]);
- });
- return out;
-}
+export const videoBlackouts = (schedule) => itemSpans(schedule, "video");
/** An overlay's `enable` for blackouts in a stream whose clock starts `shift` s into the cut; "" with none. */
export function blackoutEnable(blackouts, shift = 0) {