Archilyzer · Source

archilyzer

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

commit fd78d4bfadf264f5d07296262c2418c089d57659
parent 5126ff0d26e5919e4f2e86396c5c26f6ca322a20
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 22:34:57 -0500

compaction review fixes: a whole-file comparison, originals by sha256, locked pointer writes

From the independent review (H1-H4, M1-M9 and the lows) and the orchestrator's
rulings of 13 Nov:

- dropOriginal defaults to "keep"; "after-verify" drops only when the
  verification included the whole-file comparison, nothing is downloading the
  video, and its availability was read by a real check at most
  availabilityMaxAgeDays (7) ago -- anything else is gone and waits for a
  review of that very copy (review.forSha256).
- Verification: the whole file decoded at 2 fps, 64 px grey, frames paired by
  time; VMAF across every chunk join and inside every chunk; chunk frames
  counted from what the encoder wrote (ended by an input -to, never forced);
  gaps, the picture's start against the sound's, every other stream and the
  chapters; cuts compared frame-exact with a one-frame-off test.
- The comparisons pair frames on one clock (settb=1/rate, setpts=N): across a
  90 kHz copy and a 15360 Hz source the same seconds rounded apart and
  paired neighbours -- a lossless copy scored 29 dB. Decimation is the same
  every-m-th-frame select in the encode and the checks, chunks re-timed on
  the copy's grid; seeks are relative to the container's start (offset mp4,
  mkv, mpegts); the original's reference cut and excerpt decode from earlier.
- The original is identified by its sha256; a pointer that keeps any original
  is not compacted again; one replaced by a later persist becomes
  "former-original", which nothing drops automatically. The drop reads the
  copy back itself (fsync, page cache dropped, size, sha256, container,
  length), writes the pointer before the file goes, and finishes an
  interrupted drop.
- Every saved-video.json read-modify-write takes the pointer's lock and
  re-reads in it; a download planned on an older pointer refuses; a
  .compacting.json marker refuses persists, attaches, imports, unpersists and
  drops of the video while it is compacted; the drop refuses while a download
  or persist of it is queued or running.
- The source is hashed fresh every run; the swap compares file, bytes, dir,
  storedAt and sha256, fsyncs first, retargets the clock in the same lock;
  errors after the swap say the swap is done.
- persist-kept's "override" is no longer deliberately stored: an explicit
  persist records `explicit` on its pointer. A named video the selector would
  not pick needs "belowThreshold": true. {"select": true} is a dry run unless
  it says otherwise. Every other stream and the chapters are carried. Audio
  timing is compared in seconds; AAC in ADTS hashed through aac_adtstoasc.
- The labels: former originals, failed audio records, the UI's audio line,
  a whole-recording fetch_clip answer naming a re-encode; the review list
  and the video page give an smplayer command to watch both copies.

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

Diffstat:
MCOMMANDS.md | 12+++++++-----
MOPERATING.md | 114++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
MSETTINGS.md | 10++++++++--
Mcommon/controller/compactSavedVideos.test.ts | 701+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mcommon/controller/compactSavedVideos.ts | 694+++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------
Acommon/controller/videoBusy.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability-server.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability.ts | 4++++
Mcommon/lib/compactMedia-server.ts | 350++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/savedVideo-server.ts | 379+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mcommon/lib/savedVideo.ts | 102++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/savedVideoCompaction.test.ts | 45++++++++++++++++++++++++++++++++-------------
Mcommon/lib/savedVideoCompaction.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mcommon/lib/savedVideoOriginal.test.ts | 257++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mcommon/ytdlp/finalizeAppExtraction.ts | 4++++
Mcommon/ytdlp/savedAlternates.ts | 49++++++++++++++++++++++++++++++++++++++++++++-----
Meditor/CHANGELOG.md | 35+++++++++++++++++++++++------------
Meditor/app/api/media/fetch-window/[jobId]/route.ts | 4+++-
Meditor/app/api/ops/compact-saved-videos/route.test.ts | 12++++++++++++
Meditor/app/api/ops/compact-saved-videos/route.ts | 14+++++++++++---
Meditor/app/api/ops/review-compacted-original/route.ts | 9++++++---
Meditor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx | 20++++++++++++++++++--
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 27++++++++++-----------------
Meditor/app/jobs/jobReplayRegistry.ts | 1+
Meditor/app/saved-videos/compactActions.ts | 27+++++++++++++++++++++------
Meditor/app/saved-videos/page.tsx | 13+++++++++++--
Meditor/app/storage/lib/storeBusy.ts | 2++
Mmcp/src/fetchClip.ts | 7+++++++
Mscripts/archilyzer-ops.mjs | 60++++++++++++++++++++++++++++++++++++------------------------
Msettings.json.example | 5++++-
30 files changed, 2283 insertions(+), 886 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -156,8 +156,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, &lt;id&gt;-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/&lt;id&gt;/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` | | `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (&lt;id&gt;-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` | | `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | | -| `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, the audio copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: pinned, an explicit persist, a requested or landed container -- never a keep-latest one); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs against what is free, or why it is skipped -- and starts nothing. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true runs one whose last checks failed. One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a re-run resumes. Under dropOriginal "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not known to be on its platform (get compaction-review). | | -| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy: {"slug", "id", "note"?}. It changes nothing on disk; it is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not known to be on its platform. | | +| `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. | | | `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}'` | @@ -201,7 +201,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | -| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes, and a video not known to be on its platform needs its review recorded first. | | +| `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. | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | | `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` | | `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -&gt; {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | @@ -313,11 +313,13 @@ get saved-alternates [<slug>] lists every saved video holding two copies: (height, seconds, origin, keptAs). Once one is checked, `drop-saved-alternate` deletes it. get compaction-review [<slug>] lists every compacted saved video and what - its original waits for: "awaiting-review" (not known to be on its + 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, the original's entry, sizes, checks and the re-check. + 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 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 @@ -1136,61 +1136,93 @@ pnpm wt prune --dry-run [--json] # w ### Compact saved videos ```sh -pnpm ops compact-saved-videos --json '{"select":true,"dryRun":true}' # what the selector picks, each with its estimate +pnpm ops compact-saved-videos --json '{"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 +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}' ``` - **What it does.** A saved container is re-encoded to AV1: SVT-AV1 preset 8, crf 36, a keyframe every 5 s, the - source's height, every audio stream copied bit for bit. Kick and Twitch above 30 fps go to 30. The re-encode - becomes the active copy under its own name, `source-media.compact-av1-<stamp>.mp4`, never the original's: the - backup mirror is additive, and the same name would overwrite the backed-up original. The original stays beside it - as the alternate `"keptAs": "original"`. The pointer's `compacted` block records the source (sha256, bytes, - height, fps, codec, bitrate), the encoder and its settings, and every check's numbers. The video page, /saved-videos, - `get saved-alternates` and a playable copy (`playable.json` `"note": "re-encoded copy"`, `compactedFrom`) all say - it is a re-encode. A clip window cut from it says so in its provenance (`fromReencode`). -- **Deliberately stored videos only.** That is a pointer with `keepReason` `"pin"` (a pin, and every landed - container: an import, a live recording, attach-media), `"override"` (an explicit persist: Persist source video, - persist-videos, the whole-recording fetch), or any `origin` (a container somebody requested). A keep-latest - container with no origin is never compacted, and neither is a legacy pointer with neither. Neither is the audio - beside the record. -- **The selector** (`"select": true`, `"slugs"` narrows it) also needs the platform in `savedVideoCompaction.platforms` - (default Kick, Twitch, Rumble; YouTube is left alone), a video bitrate of at least `minVideoMbps` (3) and a height of - at least `minHeight` (720). An explicit `items` list is not held to those three. Always skipped: already compacted, - already AV1, audio-only, a channel with `excludeFromCompaction` (CHANNEL.md), and one whose last checks failed + 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's packets are scanned - once. Chunks of `chunkMinutes` (10) start on source keyframes, in `<store dir>/.compact-scratch/` on the store's - drive. Each chunk is one heavy-slot admission (1.5 GB, niced), so it waits while render mode holds the machine. - Its frame count is checked; a short or long chunk is encoded once more. A cancel stops the chunk running, a drain - waits for it, and 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 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; - - the audio packets identical (bytes and timing); - - VMAF on `qualitySamples` (12) 2-second excerpts spread through the file, mean at least `vmafMinMean` (90) and no - excerpt below `vmafMinSample` (85); SSIM where this ffmpeg has no libvmaf; - - three windows cut through the evidence cutter from both copies and compared; - - the recording clock (`clock.json`) re-measured against the re-encode, within its tolerance of the old map, - then written for the new file. -- **The original.** With `dropOriginal: "after-verify"` (the default), a separate step runs after the pointer - names the re-encode. It reads the re-encode back from disk (size, sha256, container, length), then drops the - original. A video whose availability is not public or unlisted, or unknown, is never dropped this way. It waits in - `get compaction-review` (and on /saved-videos) as "compacted, original awaiting review". Watch the compacted copy, - record the review (the video page's **Review the compacted copy**, or `review-compacted-original`), then drop the - original with `"confirmOriginal": true`. `"keep"` keeps every original until a person drops it. Nothing else - deletes an original. The prune keeps a video that holds one, unpersist brings it back as the source, and a - persist that would land on its name moves it aside first. + - 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: both copies decoded at 2 frames a second, 64 px, grey, frames paired by time; no tick + below `wholeFileSsimMin` (0.9), the mean at least `wholeFileSsimMean` (0.97), and the comparison reaching the + end. The lowest score and where it is go in the pointer; + - 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 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 diff --git a/SETTINGS.md b/SETTINGS.md @@ -647,7 +647,10 @@ Compacting a saved video (`pnpm ops compact-saved-videos`, controller/compactSav | `vmafMinSample` | `85` | The VMAF no single excerpt may fall below. Default 85. | | `ssimMinMean` | `0.95` | Without libvmaf: the SSIM the excerpts' mean must reach. Default 0.95. | | `ssimMinSample` | `0.9` | Without libvmaf: the SSIM no excerpt may fall below. Default 0.9. | -| `dropOriginal` | `"after-verify"` | "after-verify" (default, operator ruling): once every check passed and the pointer names the compacted copy, a separate step reads that copy back from disk (size, sha256, container, length) and then drops the original — except for a video gone from its platform (availability not public or unlisted, or unknown), whose original waits for a person's review (`get compaction-review`, `review-compacted-original`, then `drop-saved-alternate` with `confirmOriginal`). "keep": every original stays until a person drops it. | +| `wholeFileSsimMin` | `0.9` | THE WHOLE-FILE COMPARISON: both copies decoded at 2 frames a second, 64 px wide, grey, frames paired by their time, and compared one by one (SSIM). No frame may fall below this. Default 0.9 (a good copy scores about 0.99; a black or misplaced stretch of a test pattern 0.5–0.8). | +| `wholeFileSsimMean` | `0.97` | The whole-file comparison's mean SSIM must reach this. Default 0.97. | +| `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: @@ -673,7 +676,10 @@ Default: "vmafMinSample": 85, "ssimMinMean": 0.95, "ssimMinSample": 0.9, - "dropOriginal": "after-verify" + "wholeFileSsimMin": 0.9, + "wholeFileSsimMean": 0.97, + "availabilityMaxAgeDays": 7, + "dropOriginal": "keep" } ``` diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts @@ -1,7 +1,7 @@ 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 { 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"; @@ -12,22 +12,33 @@ import { listCompactionReview, planCompaction, type CompactDeps, + type Presence, } from "./compactSavedVideos"; -import { encodeChunkArgs, ffmpegHas, type ChunkPlan, type EncodeSettings } from "../lib/compactMedia-server"; +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 { loadSavedVideo, savedVideoPointerPath } from "../lib/savedVideo-server"; -import { compactedOriginalOf } from "../lib/savedVideo"; +import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, 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 the flow -// tests (x264 ultrafast, same frame counts and the same chunking), so they run -// without libsvtav1 and in seconds; one test runs the real SVT-AV1 encode and -// every real check, skipped where this ffmpeg has no libsvtav1. Skipped -// altogether without ffmpeg/ffprobe. +// 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( @@ -39,17 +50,24 @@ 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"; -// 6 s of 320×180 at 60 fps, a keyframe every 2 s, AAC tone. -async function makeSource(file: string, seconds = 6): Promise<void> { +type Gen = { gen?: string; seconds?: number; fps?: number; gop?: number; offset?: number; ext?: string; bf?: number }; + +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", `testsrc=size=320x180:rate=60:duration=${seconds}`, + "-f", "lavfi", "-i", `${g.gen ?? "testsrc"}=size=320x180:rate=${fps}:duration=${seconds}`, "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, - "-c:v", "libx264", "-preset", "ultrafast", "-g", "120", "-keyint_min", "120", "-sc_threshold", "0", "-pix_fmt", "yuv420p", - "-c:a", "aac", "-b:a", "64k", "-shortest", file, + "-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, ]); } @@ -65,10 +83,10 @@ type Fx = { pointerText: () => Promise<string>; }; -let cachedSource: string | null = null; +const sources = new Map<string, string>(); async function withVideo( - opts: { platform?: string; keepReason?: string; slug?: string; id?: string } = {}, + 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-")); @@ -90,19 +108,23 @@ async function withVideo( path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", platform: opts.platform ?? "kick", name: slug }), ); - if (!cachedSource) { - cachedSource = path.join(await mkdtemp(path.join(tmpdir(), "compact-src-")), ORIGINAL); - await makeSource(cachedSource); + const 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 source = path.join(storeDir, ORIGINAL); - await writeFile(source, await readFile(cachedSource)); + 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: ORIGINAL, + file, bytes, keepReason: opts.keepReason ?? "pin", format: { preset: "original", height: 180, vcodec: "avc1" }, @@ -116,8 +138,8 @@ async function withVideo( storeDir, source, sourceSha: await sha(source), - // The pointer as it was, but for the source's sha256 the run may record - // on it (what the backup step does): that one must be the file's own. + // 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)); @@ -131,32 +153,33 @@ async function withVideo( } // Chunks of 2 s (the settings' floor is a minute; the controller takes what -// it is given), three quality samples, thresholds a synthetic pattern meets. +// it is given), three spread samples, the original dropped after verify. const SETTINGS: SavedVideoCompactionSettings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, - vmafMinMean: 0, - vmafMinSample: 0, - ssimMinMean: 0, - ssimMinSample: 0, + dropOriginal: "after-verify", }; -// x264 in SVT-AV1's place: the same seek, frame count and fps filter. -async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }): Promise<void> { +// 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): Promise<void> { const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); const i = args.indexOf("libsvtav1"); - args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "30"); + args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", String(crf)); 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 { - availability: async () => "public", + presence: async () => ON, + busy: () => null, freeBytes: async () => 1e15, - encodeChunk: x264Chunk, + encodeChunk: (o) => x264Chunk(o), score: async () => 95, - cutCompare: async () => 0.99, + cutCompare: async () => ({ ssim: 0.99, earlier: 0.95, later: 0.95 }), hasVmaf: async () => true, ...extra, }; @@ -183,65 +206,207 @@ async function listTree(dir: string): Promise<string[]> { return out.sort(); } -test("the real encode: SVT-AV1, every check, swapped, re-checked, the original dropped after", { skip: NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1") }, async () => { - await withVideo({}, async ({ paths, videoDir, storeDir, sourceSha }) => { +const 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 r = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: log.onLog, - deps: { availability: async () => "public", freeBytes: async () => 1e15 }, - }); + 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(videoDir))!; + 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(storeDir, p.file))); + assert.equal(p.sha256, await sha(path.join(fx.storeDir, p.file))); const c = p.compacted!; assert.equal(c.checks.passed, true); - assert.equal(c.checks.decoded, true); // 60 -> 30 fps on Kick: 360 source frames give 180. assert.deepEqual(c.checks.frames, [360, 180, 180]); - assert.ok(Math.abs(c.checks.seconds[0] - c.checks.seconds[1]) <= c.checks.secondsTolerance); assert.equal(c.checks.audio, "identical"); assert.equal(c.checks.quality.metric, vmaf ? "vmaf" : "ssim"); - assert.equal(c.checks.quality.samples, 3); - assert.ok(c.checks.quality.mean > 0); + // 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); - for (const cut of c.checks.cuts) assert.ok(cut.ssim >= 0.9, JSON.stringify(cut)); + 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, sourceSha); - assert.equal(c.settings.crf, 36); - assert.equal(c.settings.preset, 8); + assert.equal(c.source.sha256, fx.sourceSha); assert.equal(c.chunks, 3); assert.equal(c.recheck?.ok, true); - // After-verify on a video still on its platform: dropped, after the re-check. - assert.equal(c.originalDropped?.sha256, sourceSha); + assert.equal(c.originalDropped?.sha256, fx.sourceSha); + assert.equal(c.originalDropped?.fileRemoved, true); assert.equal(compactedOriginalOf(p), null); - await assert.rejects(stat(path.join(storeDir, ORIGINAL))); - await assert.rejects(stat(path.join(storeDir, ".compact-scratch"))); - assert.equal(p.format?.vcodec, "av1"); + 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, /whole-file comparison scores/, 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 ({ paths, videoDir, storeDir, pointerText }) => { - const before = await pointerText(); + await withVideo({}, async (fx) => { + const before = await fx.pointerText(); const ac = new AbortController(); const first: number[] = []; - const r1 = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - signal: ac.signal, - deps: flowDeps({ + const r1 = await run( + fx, + flowDeps({ encodeChunk: async (o) => { first.push(o.chunk.index); if (o.chunk.index === 1) { @@ -252,169 +417,129 @@ test("a killed chunk: the run stops, and the next run resumes at the first chunk await x264Chunk(o); }, }), - }); + SETTINGS, + () => {}, + { signal: ac.signal }, + ); assert.deepEqual(r1, { status: "stopped", reason: "cancelled" }); assert.deepEqual(first, [0, 1]); - assert.equal(await pointerText(), before, "the pointer is untouched"); - const scratch = path.join(storeDir, ".compact-scratch"); + 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.mkv")); + 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 compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: log.onLog, - deps: flowDeps({ - encodeChunk: async (o) => { - second.push(o.chunk.index); - await x264Chunk(o); - }, - }), - }); + 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))); - assert.ok((await loadSavedVideo(videoDir))!.compacted); }); }); test("an encoder that dies (not a cancel) keeps the chunks done for the re-run", { skip: NO_TOOLS }, async () => { - await withVideo({}, async ({ paths, storeDir, pointerText }) => { - const before = await pointerText(); - const r = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps({ - encodeChunk: async (o) => { - if (o.chunk.index === 2) throw new Error("ffmpeg failed (exit 137)"); - await x264Chunk(o); - }, - }), - }); + 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 pointerText(), before); - const state = JSON.parse(await readFile(path.join(storeDir, ".compact-scratch", "state.json"), "utf8")); + 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 ({ paths, storeDir, pointerText }) => { - const before = await pointerText(); + await withVideo({}, async (fx) => { + const before = await fx.pointerText(); let encoded = 0; - const r = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps({ freeBytes: async () => 1000, encodeChunk: async (o) => { encoded += 1; await x264Chunk(o); } }), - }); + 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 pointerText(), before); - - // Room for the plan and the first chunk only. + assert.equal(await fx.pointerText(), before); + // Room for the plan, the start and the first chunk only. let calls = 0; - const r2 = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps({ freeBytes: async () => (++calls <= 3 ? 1e15 : 1000) }), - }); + 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(storeDir, ".compact-scratch", "state.json"), "utf8")); + 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 pointerText(), before); + 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 ({ paths, storeDir, source, sourceSha, pointerText }) => { - const before = await pointerText(); + await withVideo({}, async (fx) => { + const before = await fx.pointerText(); const log = logger(); - const r = await compactOne({ - paths, - settings: { ...SETTINGS, vmafMinMean: 90, vmafMinSample: 85 }, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: log.onLog, - deps: flowDeps({ score: async () => 42 }), - }); + 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 pointerText(), before); - assert.equal(await sha(source), sourceSha); - assert.deepEqual(await readdir(path.join(storeDir, ".compact-scratch")), ["failed.json"]); - assert.deepEqual((await readdir(storeDir)).sort(), [".compact-scratch", ORIGINAL]); + assert.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))); - - // The next plan says why; retryFailed runs it again. - const plan = await planCompaction({ paths, settings: { ...SETTINGS, vmafMinMean: 90, vmafMinSample: 85 }, items: [{ slug: "kick", id: "v1" }], deps: flowDeps() }); + 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, settings: { ...SETTINGS, vmafMinMean: 90, vmafMinSample: 85 }, items: [{ slug: "kick", id: "v1" }], retryFailed: true, deps: flowDeps() }); + 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", { skip: NO_TOOLS }, async () => { - await withVideo({}, async ({ paths, pointerText }) => { - const before = await pointerText(); +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 compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps({ - audioHash: async () => ({ data: `d${n++}`, timing: "t", firstPts: 0, packets: 10 }), - }), - }); + 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 pointerText(), before); + 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"] as const) { - await withVideo({}, async ({ paths, videoDir, storeDir }) => { + for (const availability of [null, "deleted", "needs_auth"] as const) { + await withVideo({}, async (fx) => { const log = logger(); - const r = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: log.onLog, - deps: flowDeps({ availability: async () => availability }), - }); + 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(videoDir))!; + const p = (await loadSavedVideo(fx.videoDir))!; assert.equal(compactedOriginalOf(p)?.file, ORIGINAL); - await stat(path.join(storeDir, 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, dropOriginal: "after-verify", deps: { availability: async () => availability } }); + 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"); - // And a second run does not touch it: already compacted. - const again = await planCompaction({ paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], deps: flowDeps() }); + assert.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"]); }); } @@ -422,76 +547,103 @@ test("a video gone from its platform (or unknown) is compacted but its original test("after-verify drops the original only after the swap was written and the copy re-checked from disk", { skip: NO_TOOLS }, async () => { // The re-check reads a different sha256 from disk: the original stays. - await withVideo({}, async ({ paths, videoDir, storeDir }) => { + await withVideo({}, async (fx) => { const log = logger(); - const r = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: log.onLog, - deps: flowDeps({ - sha256: async (file) => (/compact-av1/.test(path.basename(file)) ? "0".repeat(64) : sha(file)), + 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(videoDir))!; + const p = (await loadSavedVideo(fx.videoDir))!; assert.equal(p.compacted?.recheck?.ok, false); assert.match(p.compacted?.recheck?.why ?? "", /sha256/); - await stat(path.join(storeDir, ORIGINAL)); + 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: at the moment the drop step reads availability the - // pointer already names the re-encode and the original is still on disk. - await withVideo({}, async ({ paths, videoDir, storeDir }) => { + // 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 compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps({ - availability: async () => { + const r = await run( + fx, + flowDeps({ + presence: async () => { if (++calls > 1) { seen.push({ - file: (await loadSavedVideo(videoDir))!.file, - original: await stat(path.join(storeDir, ORIGINAL)).then(() => true, () => false), + file: (await loadSavedVideo(fx.videoDir))!.file, + original: await stat(path.join(fx.storeDir, ORIGINAL)).then(() => true, () => false), }); } - return "public"; + 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(videoDir))!; + const p = (await loadSavedVideo(fx.videoDir))!; assert.ok(p.compacted?.recheck?.ok); assert.ok(p.compacted!.originalDropped!.at >= p.compacted!.recheck!.at); }); }); -test('dropOriginal "keep": the original stays', { skip: NO_TOOLS }, async () => { - await withVideo({}, async ({ paths, storeDir }) => { - const r = await compactOne({ - paths, - settings: { ...SETTINGS, dropOriginal: "keep" }, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps(), - }); +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(storeDir, ORIGINAL)); + await stat(path.join(fx.storeDir, ORIGINAL)); }); }); -test("the selector picks only deliberately stored + platform + bitrate; an explicit list only refuses keep-latest", async () => { +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 = { @@ -502,16 +654,17 @@ test("the selector picks only deliberately stored + platform + bitrate; an expli ffprobeBin: "ffprobe", monorepoRoot: "", } as Paths; - const videos: [string, string, string, string, number][] = [ - // slug, platform, id, keepReason, video kbps - ["kick", "kick", "pinned-hi", "pin", 5200], - ["kick", "kick", "latest-hi", "keep-latest", 5200], - ["kick", "kick", "pinned-lo", "pin", 640], - ["tube", "youtube", "pinned-hi", "pin", 5200], - ["rumble", "rumble", "persisted-hi", "override", 3400], + const 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, keepReason, k] of videos) { + 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 }); @@ -519,22 +672,21 @@ test("the selector picks only deliberately stored + platform + bitrate; an expli await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", platform })); await writeFile(path.join(storeDir, ORIGINAL), "bytes"); kbps.set(path.join(storeDir, ORIGINAL), k); - await writeFile( - savedVideoPointerPath(videoDir), - JSON.stringify({ storedAt: "x", dir: storeDir, file: ORIGINAL, bytes: 5_000_000_000, keepReason }), - ); + await writeFile(savedVideoPointerPath(videoDir), JSON.stringify({ storedAt: "x", dir: storeDir, file: ORIGINAL, bytes: 5_000_000_000, ...facts })); } const deps: CompactDeps = { - availability: async () => "public", + 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, audioStreams: 1, bytes: 5_000_000_000, + 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", @@ -544,18 +696,16 @@ test("the selector picks only deliberately stored + platform + bitrate; an expli assert.equal(plan.willCompact, 2); const kickLine = plan.items.find((i) => i.id === "pinned-hi" && i.slug === "kick")!.line; assert.match(kickLine, /^kick\/pinned-hi: 2h00m 1080p60 h264 5\.20 Mbit\/s 4\.66 GB → est\. .* AV1 crf 36 at 30 fps .*est\. .* needs .* free \(.* free\) — would compact$/); - // Rumble keeps its 60 fps. assert.doesNotMatch(plan.items.find((i) => i.slug === "rumble")!.line, /at 30 fps/); assert.match(plan.lines.at(-1)!, /^total: 2 container\(s\)/); - // An explicit list: YouTube and the low bitrate are a person's call; keep-latest never. - const explicit = await planCompaction({ - paths, - settings: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, - items: [{ slug: "tube", id: "pinned-hi" }, { slug: "kick", id: "pinned-lo" }, { slug: "kick", id: "latest-hi" }], - deps, - }); - assert.deepEqual(explicit.items.map((i) => i.compact), [true, true, false]); - // A channel that opts out. + // 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/); @@ -565,22 +715,22 @@ test("the selector picks only deliberately stored + platform + bitrate; an expli }); test("a dry run (the plan) writes nothing", { skip: NO_TOOLS }, async () => { - await withVideo({}, async ({ root, paths }) => { - const before = await listTree(root); - const plan = await planCompaction({ paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], deps: { availability: async () => null } }); + 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(root), before); + 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 ({ paths, videoDir, pointerText }) => { - const audio = path.join(videoDir, "audio.mp3"); + await withVideo({}, async (fx) => { + const audio = path.join(fx.videoDir, "audio.mp3"); await writeFile(audio, "cue audio"); - const p = (await loadSavedVideo(videoDir))!; + const p = (await loadSavedVideo(fx.videoDir))!; const clock = { version: CLOCK_VERSION, id: "c1", @@ -595,64 +745,53 @@ test("the recording clock: re-measured against the re-encode and kept, or a move residual: { rms: 0.001 }, ok: true, }; - await writeFile(path.join(videoDir, CLOCK_FILE), JSON.stringify(clock)); - const before = await pointerText(); - const r = await compactOne({ - paths, - settings: SETTINGS, - item: { slug: "kick", id: "v1" }, - mode: "explicit", - onLog: () => {}, - deps: flowDeps({ + 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, }), - }); - const written = JSON.parse(await readFile(path.join(videoDir, CLOCK_FILE), "utf8")); + { ...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(videoDir))!; + 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); - // The same map (its id kept: windows cut through it stay current), retargeted. 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 pointerText(), before); + 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 ({ paths }) => { + await withVideo({}, async (fx) => { const drain = new AbortController(); drain.abort(); - const r = await compactSavedVideos({ - paths, - settings: SETTINGS, - items: [{ slug: "kick", id: "v1" }], - mode: "explicit", - onLog: () => {}, - drainSignal: drain.signal, - deps: flowDeps(), - }); + 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_TOOLS || (!svt && "this ffmpeg has no libsvtav1") }, async () => { - await withVideo({}, async ({ root, paths }) => { +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(root, "repo"); + const repo = path.join(fx.root, "repo"); await mkdir(path.join(repo, "scripts"), { recursive: true }); - const marker = path.join(root, "gate.jsonl"); + 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` + @@ -660,20 +799,20 @@ test("each chunk goes through the heavy slot's gate with its estimate, niced", { `const at = argv.indexOf("--");\nconst r = spawnSync(argv[at + 1], argv.slice(at + 2), { stdio: "inherit" });\nprocess.exit(r.status ?? 1);\n`, ); const r = await compactOne({ - paths: { ...paths, monorepoRoot: repo } as Paths, - settings: SETTINGS, + paths: { ...fx.paths, monorepoRoot: repo } as Paths, + settings: { ...SETTINGS, dropOriginal: "keep" }, item: { slug: "kick", id: "v1" }, mode: "explicit", + belowThreshold: true, onLog: () => {}, - // The real chunk encoder; the scoring stubbed (it would take the gate too). - deps: { availability: async () => "public", freeBytes: async () => 1e15, score: async () => 95, cutCompare: async () => 0.99 }, + 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"]); - // The full decode is admitted too. - assert.ok(runs.some((a) => a.includes("-xerror"))); + assert.ok(runs.some((a) => a.includes("-xerror")), "the full decode"); + assert.ok(runs.some((a) => a.some((x) => /wholefile-ssim/.test(x))), "the whole-file comparison"); }); }); diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts @@ -4,39 +4,47 @@ // One video at a time, each the same steps: // // 1. DECIDE. The pointer, the container, one ffprobe, the channel's opt-out -// and the selector (explicit list: deliberately stored only; selector: and -// platform, height and video bitrate). A dry run stops here and prints the -// estimate and the disk it needs. -// 2. ENCODE IN CHUNKS, in `<store dir>/.compact-scratch/` (the store's own -// drive). The source's packets are scanned once (frame count, keyframes); -// chunks of about `chunkMinutes` start on source keyframes; each is one -// heavy-slot admission (waiting while render mode holds the machine), its -// frame count checked, then recorded in `state.json` — a restart resumes -// at the first chunk not done. Cancel and drain are honoured between -// chunks; the disk floor before the first and before each one. -// 3. MUX: the chunks joined, every audio stream of the SOURCE copied. -// 4. VERIFY — every check must pass or the original stays active, untouched, +// and the 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 video's length within a frame; the -// frame count the fps change gives; the audio packets identical; VMAF (or -// SSIM) on excerpts spread through the file; a window cut from each copy -// through the evidence cutter, compared; the recording clock re-measured -// against the re-encode and within its tolerance of the old map. -// 5. SWAP, in one locked pointer write: the re-encode (its OWN name, -// `source-media.compact-av1-<stamp>.mp4`) becomes `file`; the original -// joins `alternates` as `keptAs: "original"`; `compacted` records every -// number. Only if the pointer still names the bytes that were encoded. -// 6. RECHECK, a separate step: the pointer and the re-encode read back from -// disk (size, sha256, container, length). -// 7. DROP THE ORIGINAL, another separate step, only under `dropOriginal: -// "after-verify"`, only when the recheck passed, and NEVER for a video not -// known to be on its platform: that one is left for a person's review -// (`get compaction-review`). +// `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 { hostname } from "node:os"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Availability } from "../lib/availability"; @@ -47,6 +55,7 @@ import { detectPlatform } from "../lib/platform"; import { compactedLine, compactedOriginalOf, + reviewIsCurrent, savedVideoPath, type SavedVideoAlternate, type SavedVideoCompacted, @@ -54,27 +63,30 @@ import { type SavedVideoPointer, } from "../lib/savedVideo"; import { + COMPACTING_MARKER_FILENAME, SavedAlternateRefusal, dropSavedAlternate, + fsyncFileAndDir, loadSavedVideo, + readBackCompactedCopy, savedVideoPointerPath, updateSavedVideoChecksum, + withPointerLock, } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; -import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; -import { resolveEffectiveAvailability } from "../lib/availability-server"; +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, - COMPACTION_DISK_MARGIN_BYTES, compactionFreeNeeded, decideCompaction, estimateCompaction, - isStillOnPlatform, sanitizeSavedVideoCompaction, targetFps, type CompactionEstimate, @@ -83,10 +95,15 @@ import { } from "../lib/savedVideoCompaction"; import { CHUNK_ESTIMATE_MB, + CHUNK_EXT, + WHOLE_FILE_FPS, + WHOLE_FILE_WIDTH, audioPacketsHash, compareCuts, + compareWholeFile, concatList, countVideoFrames, + cutIsOffset, encodeChunkArgs, ffmpegHas, ffmpegVersionLine, @@ -94,12 +111,15 @@ import { muxArgs, planChunks, probeCompactionSource, + sameAudioTiming, runHeavyFfmpeg, sampleTimes, scanVideoPackets, scoreExcerpt, + streamInventory, type AudioHash, type ChunkPlan, + type CutComparison, type EncodeSettings, type PacketScan, type SourceProbe, @@ -115,27 +135,36 @@ export const COMPACT_PIX_FMT = "yuv420p"; const EXCERPT_SECONDS = 2; const CUT_SECONDS = 3; const CUT_SAMPLES = 3; -// A window cut from each copy, compared on a 320-px picture: a cut landing a -// frame or more off, or a broken picture, falls well under this. +// 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>; - availability?: (videoDir: string) => Promise<Availability | null>; + // 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; videoStart: number; out: string; signal?: AbortSignal }) => Promise<void>; + 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: { compacted: string; source: string; scratchDir: string; signal?: AbortSignal }) => Promise<number[]>; hasVmaf?: () => Promise<boolean>; - score?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>; - cutCompare?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<number>; + 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>; @@ -149,11 +178,19 @@ async function sha256File(file: string, signal?: AbortSignal): Promise<string> { return h.digest("hex"); } -function resolveDeps(paths: Paths, deps: CompactDeps = {}): Required<CompactDeps> { +function resolveDeps(paths: Paths, settings: SavedVideoCompactionSettings, deps: CompactDeps = {}): Required<CompactDeps> { return { now: deps.now ?? (() => new Date()), freeBytes: deps.freeBytes ?? getFreeBytes, - availability: deps.availability ?? ((d) => resolveEffectiveAvailability(d).catch(() => null)), + 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: @@ -168,14 +205,21 @@ function resolveDeps(paths: Paths, deps: CompactDeps = {}): Required<CompactDeps mux: deps.mux ?? (async (o) => { - await runHeavyFfmpeg(paths, muxArgs(o.list, o.src, o.videoStart, o.out), { - estimateMB: 300, - nice: true, - ...(o.signal ? { signal: o.signal } : {}), - }); + 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)), + 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)), @@ -201,10 +245,12 @@ export type CompactPlanItem = { compact: boolean; reason?: string; platform: string | null; - // Availability's word: still on the platform (public / unlisted) or not - // (anything else, or unknown — counted as gone). + // 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; @@ -264,7 +310,7 @@ async function lastFailure(dir: string): Promise<{ at: string; reason: string; s } 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 }); + 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: { @@ -273,6 +319,7 @@ export async function planOne(opts: { 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; @@ -290,12 +337,11 @@ export async function planOne(opts: { const pointer = await loadSavedVideo(videoDir); if (!pointer) return skip("no saved video"); const platform = await videoPlatform(videoDir, config); - const availability = await deps.availability(videoDir); - const onPlatform = isStillOnPlatform(availability); + const 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, availability }; + const facts = { platform, onPlatform: presence.onPlatform, availability: presence.availability, presence: presence.why }; const decision = decideCompaction({ pointer, platform, @@ -304,14 +350,23 @@ export async function planOne(opts: { 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)}` : ""; - if (!decision.ok) return { ...skip(decision.reason, { ...facts, line: brief ? `${brief} —` : "" }), pointer, probe }; + 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); - const fps = targetFps(probe!.fps, platform, settings); if (failed && failed.settingsKey === settingsKeyOf(settings, fps) && !opts.retryFailed) { return { ...skip(`its last compaction failed its checks on ${failed.at.slice(0, 10)}: ${failed.reason}; "retryFailed": true runs it again`, { @@ -322,24 +377,23 @@ export async function planOne(opts: { probe, }; } - const estimate = estimateCompaction({ probe: probe!, crf: settings.crf, fps }); const freeBytes = await deps.freeBytes(pointer.dir); - const needsFreeBytes = compactionFreeNeeded(estimate.bytes[1], 0); + const needsFreeBytes = compactionFreeNeeded(estimate!.bytes[1], 0); const pct = (b: number) => Math.round((1 - b / pointer.bytes) * 100); - const gone = onPlatform - ? "" - : `; not known to be on its platform (availability ${availability ?? "unknown"}): its original waits for a review`; + const 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)` + + `${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, @@ -350,7 +404,7 @@ export async function planOne(opts: { videoMbps: mbps, }, fps, - estimate, + estimate: estimate!, needsFreeBytes, freeBytes, line, @@ -368,9 +422,10 @@ export async function planCompaction(opts: { select?: boolean; slugs?: string[]; retryFailed?: boolean; + belowThreshold?: boolean; deps?: CompactDeps; }): Promise<CompactPlan> { - const deps = resolveDeps(opts.paths, opts.deps); + const deps = resolveDeps(opts.paths, opts.settings, opts.deps); let items = opts.items ?? []; const mode: "explicit" | "select" = opts.select ? "select" : "explicit"; if (opts.select) { @@ -387,6 +442,7 @@ export async function planCompaction(opts: { mode, settings: opts.settings, retryFailed: opts.retryFailed, + belowThreshold: opts.belowThreshold, deps, }); out.push(row); @@ -413,24 +469,33 @@ export async function planCompaction(opts: { // --- the run ------------------------------------------------------------------- -type ChunkState = { index: number; from: number; to: number; sourceFrames: number; expectedFrames: number; file: string; bytes?: number; done: boolean }; +type ChunkState = ChunkPlan & { file: string; bytes?: number; done: boolean }; type CompactState = { - version: 1; + version: typeof STATE_VERSION; sourceFile: string; sourceBytes: number; + sourceSha256: string; settingsKey: string; - sourceSha256?: 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 } + | { + 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 }; @@ -453,7 +518,13 @@ async function loadState(file: string): Promise<CompactState | null> { const read = await readJsonFile(file); if (!read.ok || !read.value || typeof read.value !== "object") return null; const s = read.value as CompactState; - return s.version === 1 && Array.isArray(s.chunks) ? s : null; + 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 = { @@ -466,19 +537,48 @@ export type CompactRunOptions = { }; export async function compactOne( - opts: CompactRunOptions & { item: CompactItem; mode: "explicit" | "select"; retryFailed?: boolean }, + 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.deps); - const { settings: s, signal } = opts; - const planned = await planOne({ paths: opts.paths, item: opts.item, mode: opts.mode, settings: s, retryFailed: opts.retryFailed, deps }); - const tag = `${opts.item.slug}/${opts.item.id}`; + 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) { log(planned.line); return { status: "skipped", reason: planned.reason ?? "not a candidate" }; } - const pointer = planned.pointer; - const probe = planned.probe; + const marker = path.join(planned.pointer.dir, COMPACTING_MARKER_FILENAME); + await assertSavedVideosStoreWritable(opts.paths, planned.pointer.dir); + // THE MARKER every persist of this video reads (savedVideo-server.ts + // assertNotCompacting): written before anything else, removed at the end. + await writeJsonAtomic(marker, { pid: process.pid, host: hostname(), startedAt: deps.now().toISOString(), video: `${opts.item.slug}/${opts.item.id}` }); + try { + return await compactPlanned(opts, deps, planned, log, () => rm(marker, { force: true })); + } finally { + await rm(marker, { force: true }).catch(() => {}); + } +} + +async function compactPlanned( + opts: CompactRunOptions & { item: CompactItem }, + deps: Required<CompactDeps>, + planned: Awaited<ReturnType<typeof planOne>>, + log: (s: string) => void, + // The compaction itself is done once the swap is written: the marker goes + // then, so the drop step (which refuses while one is there) can run. + releaseMarker: () => Promise<void>, +): 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; @@ -498,37 +598,55 @@ export async function compactOne( : null; }; - await assertSavedVideosStoreWritable(opts.paths, pointer.dir); await mkdir(scratch, { recursive: true }); - let state = await loadState(stateFile); - if (state && (state.sourceFile !== pointer.file || state.sourceBytes !== pointer.bytes || state.settingsKey !== settingsKey)) { - log(`${tag}: the scratch state is for another source or other settings — discarded, starting over.`); - await rm(scratch, { recursive: true, force: true }); - await mkdir(scratch, { recursive: true }); - state = null; - } - const writeState = async () => writeJsonAtomic(stateFile, state); - + 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) { - const low = await floor(0); - if (low) return { status: "stopped", reason: low }; log(`${tag}: scanning ${pointer.file}'s packets (frame count, keyframes)…`); const scan = await deps.scan(src, signal); - const plan = planChunks(scan, s.chunkMinutes * 60, fps); + 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: 1, + 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), - chunks: plan.map((c) => ({ ...c, file: `chunk-${String(c.index).padStart(4, "0")}.mkv`, done: false })), + 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.`); @@ -536,18 +654,8 @@ export async function compactOne( const done = state.chunks.filter((c) => c.done).length; log(`${tag}: resuming — ${done}/${state.chunks.length} chunk(s) already encoded.`); } - if (!state.sourceSha256) { - if (pointer.sha256) { - state.sourceSha256 = pointer.sha256; - } else { - log(`${tag}: hashing ${pointer.file} (${formatBytes(pointer.bytes)}) — the original's sha256 is recorded with the re-encode.`); - state.sourceSha256 = await deps.sha256(src, signal); - await updateSavedVideoChecksum(videoDir, state.sourceSha256, pointer.file); - } - await writeState(); - } - // ---- 2. the chunks ---- + // ---- 3. the chunks ---- const enc: EncodeSettings = { preset: s.preset, crf: s.crf, @@ -555,6 +663,7 @@ export async function compactOne( pixFmt: COMPACT_PIX_FMT, fps, sourceFps: probe.fps ?? 30, + formatStart: probe.formatStart, }; for (const c of state.chunks) { if (c.done) { @@ -579,7 +688,8 @@ export async function compactOne( const part = `${out}.part`; await rm(part, { force: true }); log(`${tag}: chunk ${c.index + 1}/${state.chunks.length} (${c.from.toFixed(1)}–${c.to.toFixed(1)} s, ${c.expectedFrames} frames)…`); - // A chunk short or long is encoded once more; twice is a verdict. + // 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 }); @@ -602,25 +712,27 @@ export async function compactOne( await writeState(); } - // ---- 3. the mux ---- + // ---- 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 muxed = path.join(scratch, "compacted.mp4"); + 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), the source's audio copied…`); - await deps.mux({ list: listFile, src, videoStart: probe.videoStart, out: muxed, signal }); + 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 }); - // ---- 4. verify ---- + // ---- 5. verify ---- const { checks, clock: keptClock } = await verify({ ...opts, deps, tag, state, src, muxed, probe, fps, videoDir, pointer, scratch, log }); - // ---- 5. the swap ---- + // ---- 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(() => [])); + 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 = { @@ -634,7 +746,7 @@ export async function compactOne( ...(pointer.origin ? { origin: pointer.origin } : {}), ...(pointer.format?.preset ? { preset: pointer.format.preset } : {}), keptAs: "original", - sha256: state.sourceSha256!, + sha256: sourceSha, }; const compacted: SavedVideoCompacted = { at: at.toISOString(), @@ -654,7 +766,7 @@ export async function compactOne( source: { file: pointer.file, bytes: pointer.bytes, - sha256: state.sourceSha256!, + sha256: sourceSha, ...(probe.vcodec ? { vcodec: probe.vcodec } : {}), ...(probe.height ? { height: probe.height } : {}), ...(probe.fps ? { fps: probe.fps } : {}), @@ -678,76 +790,101 @@ export async function compactOne( chunks: state.chunks.length, }; const pointerFile = savedVideoPointerPath(videoDir); - const swapped = await withJsonFileLock(pointerFile, async () => { + 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; - if (!raw || raw.file !== pointer.file || raw.bytes !== pointer.bytes || raw.dir !== pointer.dir) { + // 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 || + (raw.sha256 !== undefined && raw.sha256 !== sourceSha) || + raw.compacted !== undefined + ) { return false; } - await rename(muxed, final); - raw.file = name; - raw.bytes = resultBytes; - raw.sha256 = resultSha; - raw.compacted = compacted; - raw.probed = { - ...(resultProbe?.seconds ? { seconds: resultProbe.seconds } : {}), - ...(resultProbe?.height ? { height: resultProbe.height } : {}), - }; - // `format` says what the ACTIVE copy is: the same asked-for preset, - // the re-encode's height and codec (the download's is in - // `compacted.source.format`). - if (raw.format && typeof raw.format === "object") { - raw.format = { - ...(raw.format as Record<string, unknown>), + // 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 } : {}), - vcodec: "av1", }; - } - raw.alternates = [...(Array.isArray(raw.alternates) ? raw.alternates : []), original]; - try { + // `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 - // the scratch name, never left as a file no pointer names. + // 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 (!swapped) { + 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" }; } - // THE SAME MAP, NOW ABOUT THE ACTIVE COPY: re-measured against the - // re-encode during the checks and found within its tolerance, so it is the - // old map (its id kept — every window cut through it stays on this clock) - // with the new target, and a note of the measurement that proved it. - if (checks.clock === "kept" && keptClock) { - await recordingClockSidecar.write(videoDir, { - ...keptClock, - target: { file: name, bytes: resultBytes }, - }); - } - await rm(scratch, { recursive: true, force: true }); - const swappedPointer = (await loadSavedVideo(videoDir))!; + 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), ${checks.quality.metric.toUpperCase()} ` + + `${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 }); + await releaseMarker(); - // ---- 6 and 7: the recheck, then the drop — each its own step ---- - const after = await afterSwap({ paths: opts.paths, videoDir, settings: s, deps, log, tag, signal }); - return { status: "compacted", line: `compacted ${tag}`, pointer: (await loadSavedVideo(videoDir)) ?? swappedPointer, ...after }; + // ---- 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 }); + 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. - await rm(path.join(scratch, "compacted.mp4"), { force: true }).catch(() => {}); + 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 }; @@ -768,6 +905,13 @@ export async function compactOne( } } +// 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; @@ -785,23 +929,27 @@ async function verify(o: { signal?: AbortSignal; }): Promise<{ checks: SavedVideoCompactedChecks; clock: RecordingClock | null }> { const { deps, tag, state, settings: s, log, signal } = o; - const checks: Partial<SavedVideoCompactedChecks> = { passed: false }; + 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 and frames, from both files' packets. + // 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 / (o.fps ?? o.probe.fps ?? 30); + 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 / (o.fps ?? o.probe.fps ?? 30) + 1e-3; + 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); @@ -810,31 +958,96 @@ async function verify(o: { if (Math.abs(outSeconds - srcSeconds) > frameTol) { fail(`the re-encode's video lasts ${outSeconds.toFixed(3)} s, the source's ${srcSeconds.toFixed(3)} s (more than a frame apart)`); } - if (n && Math.abs(outScan.pts[0] - state.sourceFirstPts) > frameTol / 2) { - fail(`the re-encode's first frame is at ${outScan.pts[0].toFixed(3)} s, the source's at ${state.sourceFirstPts.toFixed(3)} s`); + // 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.`); + 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.audio = "identical"; checks.audioHash = b.data; - if (a.packets !== b.packets || a.data !== b.data || a.timing !== b.timing || a.firstPts !== b.firstPts) { + 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" : ""}${a.timing !== b.timing || a.firstPts !== b.firstPts ? ", different timing" : ""})`, + `${a.data !== b.data ? ", different bytes" : ""}${!sameTiming ? ", different timing" : ""})`, ); } + checks.audio = "identical"; log(`${tag}: audio identical (${b.packets} packets).`); - // Quality on excerpts spread through the file. + // 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. + log(`${tag}: comparing the whole file at ${WHOLE_FILE_FPS} frames a second…`); + const ticks = await deps.wholeFile({ compacted: o.muxed, source: o.src, scratchDir: o.scratch, signal }); + const expectTicks = Math.floor(srcSeconds * WHOLE_FILE_FPS); + const wMean = ticks.reduce((x, y) => x + y, 0) / Math.max(1, ticks.length); + let worst = 0; + for (let i = 1; i < ticks.length; i += 1) if (ticks[i] < ticks[worst]) worst = i; + checks.wholeFile = { + fps: WHOLE_FILE_FPS, + width: WHOLE_FILE_WIDTH, + frames: ticks.length, + mean: round(wMean, 4), + min: round(ticks.length ? ticks[worst] : 0, 4), + worstAt: round(worst / WHOLE_FILE_FPS, 2), + minFloor: s.wholeFileSsimMin, + meanFloor: s.wholeFileSsimMean, + maxGapSeconds: round(gap, 4), + }; + if (ticks.length < expectTicks - 1) { + fail(`the whole-file comparison reached ${ticks.length} of the ${expectTicks} ticks the source's length gives: the copy ends early or skips`); + } + if ((ticks[worst] ?? 0) < s.wholeFileSsimMin || wMean < s.wholeFileSsimMean) { + fail( + `the whole-file comparison scores ${wMean.toFixed(3)} mean, ${(ticks[worst] ?? 0).toFixed(3)} at ${(worst / WHOLE_FILE_FPS).toFixed(1)} s ` + + `(needs ${s.wholeFileSsimMean} and no tick below ${s.wholeFileSsimMin})`, + ); + } + log(`${tag}: whole file SSIM ${wMean.toFixed(3)} mean over ${ticks.length} ticks, lowest ${ticks[worst].toFixed(3)} at ${(worst / WHOLE_FILE_FPS).toFixed(1)} s.`); + + // 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 outFps = o.fps ?? o.probe.fps ?? 30; - const times = sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps); + 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) { + 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, metric, scratchDir: o.scratch, signal })); + 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); @@ -843,18 +1056,24 @@ async function verify(o: { if (mean < minMean || min < minSample) { fail(`${metric.toUpperCase()} ${mean.toFixed(2)} mean, ${min.toFixed(2)} at its worst excerpt (needs ${minMean} and ${minSample})`); } - log(`${tag}: ${metric.toUpperCase()} ${mean.toFixed(2)} mean over ${scores.length} excerpts, worst ${min.toFixed(2)}.`); + log(`${tag}: ${metric.toUpperCase()} ${mean.toFixed(2)} mean over ${scores.length} excerpts (every join and every chunk), worst ${min.toFixed(2)}.`); - // A real window cut from each, compared. - const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps); + // 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 ssim = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, seconds: CUT_SECONDS, fps: o.fps, scratchDir: o.scratch, signal }); - checks.cuts.push({ at, ssim: round(ssim, 4) }); - if (ssim < CUT_SSIM_MIN) fail(`a window cut at ${at.toFixed(1)} s from the re-encode differs from the same cut of the original (SSIM ${ssim.toFixed(3)} < ${CUT_SSIM_MIN})`); + 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 match the original's.`); + log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter land on the original's frames.`); // The recording clock. checks.clock = "none"; @@ -874,16 +1093,17 @@ async function verify(o: { signal, }); const tol = old.params?.tolerance ?? 0.08; - const now = fresh; - const moved = okAnchors.find((t: number) => Math.abs(clockOffsetAt(old, t).offset - clockOffsetAt(now, t).offset) > tol); - if (now.ok !== old.ok || moved !== undefined) { + 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(now, moved).offset.toFixed(3)} s, against the original ${clockOffsetAt(old, moved).offset.toFixed(3)} s` - : `the recording clock's map is ${now.ok ? "ok" : "NOT ok"} against the re-encode and ${old.ok ? "ok" : "NOT ok"} against the original`, + ? `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 }, @@ -899,9 +1119,9 @@ async function verify(o: { // --- after the swap ------------------------------------------------------------ // THE SECOND CHECK (a step of its own): the pointer read back from disk, and -// the file it names — its size, its sha256 against the recorded one, the -// container opening, its length against the verified one. Recorded as -// `compacted.recheck`. Answers the verified sha256 when it held. +// 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; @@ -909,40 +1129,22 @@ export async function recheckCompactedCopy(opts: { signal?: AbortSignal; record?: boolean; }): Promise<{ ok: true; sha256: string } | { ok: false; why: string }> { - const deps = resolveDeps(opts.paths, opts.deps); const pointer = await loadSavedVideo(opts.videoDir); - const c = pointer?.compacted; - let res: { ok: true; sha256: string } | { ok: false; why: string }; - if (!pointer || !c) { - res = { ok: false, why: "the pointer names no compacted copy" }; - } else if (pointer.file !== c.result.file) { - res = { ok: false, why: `the pointer names ${pointer.file}, not the compacted ${c.result.file}` }; - } else { - const file = savedVideoPath(pointer); - const st = await stat(file).catch(() => null); - if (!st?.isFile()) res = { ok: false, why: `${file} is not there` }; - else if (st.size !== pointer.bytes || st.size !== c.result.bytes) res = { ok: false, why: `${pointer.file} is ${st.size} bytes, ${c.result.bytes} recorded` }; - else { - const sha = await deps.sha256(file, opts.signal); - const p = await deps.probe(file); - const want = c.result.seconds; - if (sha !== pointer.sha256 || sha !== c.result.sha256) res = { ok: false, why: `${pointer.file}'s sha256 is ${sha.slice(0, 12)}…, ${c.result.sha256.slice(0, 12)}… recorded` }; - else if (!p || !p.hasVideo) res = { ok: false, why: `${pointer.file} does not open as a video` }; - else if (want && p.seconds && Math.abs(p.seconds - want) > Math.max(0.05, c.checks.secondsTolerance)) { - res = { ok: false, why: `${pointer.file} lasts ${p.seconds} s, ${want} s recorded` }; - } else res = { ok: true, sha256: sha }; - } - } + 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 withJsonFileLock(pointerFile, async () => { + 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: deps.now().toISOString(), ok: res.ok, ...(res.ok ? {} : { why: res.why }) }, + recheck: { at: (opts.deps?.now?.() ?? new Date()).toISOString(), ok: res.ok, ...(res.ok ? {} : { why: res.why }) }, }; await writeJsonAtomic(pointerFile, raw); }); @@ -954,14 +1156,15 @@ export function reviewStateOf(pointer: SavedVideoPointer, onPlatform: boolean, d if (!pointer.compacted) return null; const original = compactedOriginalOf(pointer); if (!original) return "dropped"; - if (!onPlatform) return original.review ? "reviewed" : "awaiting-review"; - if (original.review) return "reviewed"; + 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; @@ -972,31 +1175,36 @@ async function afterSwap(o: { const recheck = await recheckCompactedCopy({ paths: o.paths, videoDir: o.videoDir, deps: o.deps, ...(o.signal ? { signal: o.signal } : {}) }); const pointer = (await loadSavedVideo(o.videoDir))!; const original = compactedOriginalOf(pointer); - const availability = await o.deps.availability(o.videoDir); - const onPlatform = isStillOnPlatform(availability); + 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: reviewStateOf(pointer, onPlatform, o.settings.dropOriginal) ?? "drop-pending" }; + 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: reviewStateOf(pointer, onPlatform, "keep")! }; + return { dropped: false, review: state() }; } - if (!onPlatform) { + 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 (availability ${availability ?? "unknown"}): the original ${original.file} ` + + `${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: reviewStateOf(pointer, onPlatform, o.settings.dropOriginal)! }; + return { dropped: false, review: state() }; } try { const r = await dropSavedAlternate(o.videoDir, original.file, { confirmOriginal: true, - verifiedActive: { sha256: recheck.sha256 }, by: "compact-saved-videos (after-verify)", - availability, + 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).`); @@ -1004,14 +1212,14 @@ async function afterSwap(o: { } catch (err) { if (!(err instanceof SavedAlternateRefusal)) throw err; log(`${tag}: the original ${original.file} is kept: ${err.message}`); - return { dropped: false, review: reviewStateOf(pointer, onPlatform, o.settings.dropOriginal) ?? "drop-pending" }; + return { dropped: false, review: state() }; } } // --- the job's body ------------------------------------------------------------ export type CompactSavedVideosResult = { - compacted: { slug: string; id: string; dropped: boolean; review: CompactionReviewState }[]; + 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; @@ -1019,7 +1227,7 @@ export type CompactSavedVideosResult = { // Each item in turn, one at a time. export async function compactSavedVideos( - opts: CompactRunOptions & { items: CompactItem[]; mode: "explicit" | "select"; retryFailed?: boolean }, + opts: CompactRunOptions & { items: CompactItem[]; mode: "explicit" | "select"; retryFailed?: boolean; belowThreshold?: boolean }, ): Promise<CompactSavedVideosResult> { const result: CompactSavedVideosResult = { compacted: [], skipped: [], failed: [] }; for (const item of opts.items) { @@ -1032,8 +1240,9 @@ export async function compactSavedVideos( break; } const r = await compactOne({ ...opts, item }); - if (r.status === "compacted") result.compacted.push({ ...item, dropped: r.dropped, review: r.review }); - else if (r.status === "skipped") result.skipped.push({ ...item, reason: r.reason }); + 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; @@ -1069,23 +1278,35 @@ export type CompactionReviewRow = { 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; - dropOriginal: SavedVideoCompactionSettings["dropOriginal"]; + settings: Pick<SavedVideoCompactionSettings, "dropOriginal" | "availabilityMaxAgeDays">; channelSlug?: string; notAnswering?: string[]; - deps?: Pick<CompactDeps, "availability">; + deps?: Pick<CompactDeps, "presence">; }): Promise<CompactionReviewRow[]> { - const availabilityOf = opts.deps?.availability ?? ((d: string) => resolveEffectiveAvailability(d).catch(() => null)); + 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 } : {}), @@ -1095,22 +1316,35 @@ export async function listCompactionReview(opts: { for (const e of entries) { const c = e.pointer.compacted; if (!c) continue; - const availability = await availabilityOf(e.videoDir); - const onPlatform = isStillOnPlatform(availability); + 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, onPlatform, opts.dropOriginal)!, + state: reviewStateOf(e.pointer, presence.onPlatform, opts.settings.dropOriginal)!, line: compactedLine(e.pointer) ?? "", - availability, - onPlatform, + 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; 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/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/compactMedia-server.ts b/common/lib/compactMedia-server.ts @@ -84,8 +84,18 @@ function numOr(v: unknown): number | 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 @@ -118,7 +128,19 @@ export async function probeCompactionSource(ffprobeBin: string, file: string): P // 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, @@ -207,6 +229,8 @@ export type ChunkPlan = { 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 { @@ -228,14 +252,23 @@ const EDGE = 1e-4; // Chunks of about `chunkSeconds`, each starting on a source keyframe. A chunk // is never shorter than half the asked length unless it is the only one. -export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null): ChunkPlan[] { +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) starts.push(k); + 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) { @@ -247,7 +280,12 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe from, to, sourceFrames, - expectedFrames: outFps ? framesAtFps(pts, from, to, outFps, i + 1 === starts.length) : 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; @@ -272,44 +310,97 @@ export type EncodeSettings = { // 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 (exact — a keyframe is a -// place the decoder can start), the video only, the frame count fixed, into a -// Matroska file the concat demuxer joins. +// 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 - 0.001).toFixed(6), + "-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", - ...(s.fps ? ["-vf", `fps=${s.fps}`] : []), - "-frames:v", String(chunk.expectedFrames), + // 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, - "-f", "matroska", out, + "-video_track_timescale", "90000", + "-f", "mp4", out, ]; } // The chunks joined (concat demuxer, `-c copy`), the source's video start kept, -// and EVERY AUDIO STREAM OF THE SOURCE COPIED bit for bit — never re-encoded -// (a later transcription hears the same samples, at the same seconds). -export function muxArgs(listFile: string, src: string, videoStart: number, out: string): string[] { +// 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:a?", + "-map", "0:v:0", + "-map", "1", "-map", `-1:${opts.mainVideoIndex ?? 0}`, "-c", "copy", "-map_metadata", "1", - "-movflags", "+faststart", - "-f", "mp4", out, + "-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"; } @@ -342,35 +433,76 @@ export type AudioHash = { 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. -export async function audioPacketsHash(ffmpegBin: string, file: string, signal?: AbortSignal): Promise<AudioHash> { +// 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", "-f", "framemd5", "-"], + ["-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 || line.startsWith("#")) return; + 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, duration, size, md5] = f; - const p = Number(pts); + 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},${p - (first ?? 0)},${duration}\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) => { @@ -388,11 +520,28 @@ export async function audioPacketsHash(ffmpegBin: string, file: string, signal?: else resolve(); }); }); - return { data: data.digest("hex"), timing: timing.digest("hex"), firstPts: first, packets }; + 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. @@ -404,13 +553,21 @@ export async function scoreExcerpt( at: number; seconds: number; fps: number | null; + sourceFps?: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal; }, ): Promise<number> { - const ref = `[1:v]${opts.fps ? `fps=${opts.fps},` : ""}setpts=PTS-STARTPTS[r]`; - const dist = "[0:v]setpts=PTS-STARTPTS[d]"; + // 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" @@ -419,7 +576,9 @@ export async function scoreExcerpt( const args = [ "-nostdin", "-hide_banner", "-loglevel", "info", "-ss", opts.at.toFixed(4), "-t", opts.seconds.toFixed(3), "-i", opts.compacted, - "-ss", opts.at.toFixed(4), "-t", opts.seconds.toFixed(3), "-i", opts.source, + // 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", "-", ]; @@ -464,9 +623,62 @@ export function sampleTimes(seconds: number, n: number, excerpt: number, fps: nu // A REAL WINDOW CUT FROM EACH COPY through the evidence cutter // (evidenceCutArgs: the input seek and the x264 re-encode every saved-video -// window goes through), and the two cuts compared on a downscaled picture -// (SSIM, 320 px wide, at the re-encode's frame rate): it succeeds from the -// re-encode and lands on the same frames as from the original. +// 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: { @@ -475,18 +687,19 @@ export async function compareCuts( at: number; seconds: number; fps: number | null; + sourceFps?: number | null; scratchDir: string; signal?: AbortSignal; }, -): Promise<number> { +): 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] of [ - [opts.source, a], - [opts.compacted, b], + 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, evidenceCutArgs(file, opts.at, opts.at + opts.seconds, "video", out), { + const r = await execa(paths.ffmpegBin, args, { reject: false, ...(opts.signal ? { cancelSignal: opts.signal } : {}), }); @@ -497,22 +710,67 @@ export async function compareCuts( ); } } - const fps = opts.fps ? `fps=${opts.fps},` : ""; - const r = await execa( - paths.ffmpegBin, + 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 (review H1: a bad stretch the excerpts miss). Both +// copies decoded end to end, each taken to `fps` frames a second on the same +// clock (the fps filter keeps the frame nearest each tick of the file's own +// time, so a 30 fps copy of a 60 fps source is compared at the same instants), +// scaled to `width` px, grey; the ticks paired by time and scored by SSIM one +// by one. Answers every tick's score; the caller judges the floor, the mean, +// and that the comparison reached the end. +export const WHOLE_FILE_FPS = 2; +export const WHOLE_FILE_WIDTH = 64; +export const WHOLE_FILE_ESTIMATE_MB = 1200; + +export async function compareWholeFile( + paths: GatedPaths, + opts: { compacted: string; source: string; scratchDir: string; signal?: AbortSignal }, +): Promise<number[]> { + const stats = path.join(opts.scratchDir, "wholefile-ssim.log"); + await rm(stats, { force: true }); + // The first frame in each 1/fps-second bucket of the file's own time (no + // rounding: a frame exactly on a tick opens its bucket on both sides), then + // numbered on that grid and paired by number. + const b = WHOLE_FILE_FPS; + const tick = + "setpts=PTS-STARTPTS," + + `select='isnan(prev_selected_t)+gte(floor(t*${b}+0.0001)-floor(prev_selected_t*${b}+0.0001),1)',` + + `settb=1/${b},setpts=N,scale=${WHOLE_FILE_WIDTH}:-2:flags=area,format=gray`; + try { + await runHeavyFfmpeg( + paths, [ - "-nostdin", "-hide_banner", "-loglevel", "info", - "-i", b, "-i", a, - "-lavfi", `[0:v]${fps}scale=320:-2,setpts=PTS-STARTPTS[d];[1:v]${fps}scale=320:-2,setpts=PTS-STARTPTS[r];[d][r]ssim`, + "-nostdin", "-hide_banner", "-loglevel", "error", + "-i", opts.compacted, "-i", opts.source, + "-lavfi", `[0:v]${tick}[d];[1:v]${tick}[r];[d][r]ssim=stats_file=${stats.replace(/[:\\']/g, "\\$&")}:eof_action=endall`, "-f", "null", "-", ], - { reject: false, ...(opts.signal ? { cancelSignal: opts.signal } : {}) }, + { estimateMB: WHOLE_FILE_ESTIMATE_MB, ...(opts.signal ? { signal: opts.signal } : {}) }, ); - const m = /SSIM .*All:([0-9.]+)/.exec(String(r.stderr ?? "")); - if (r.exitCode !== 0 || !m) throw new Error(`could not compare the two cuts at ${opts.at.toFixed(1)} s`); - return Number(m[1]); + const text = await readFile(stats, "utf8"); + return text + .split("\n") + .map((l) => /All:([0-9.]+|inf)/.exec(l)?.[1]) + .filter((x): x is string => x !== undefined) + .map((x) => (x === "inf" ? 1 : Number(x))); } finally { - await rm(a, { force: true }).catch(() => {}); - await rm(b, { force: true }).catch(() => {}); + await rm(stats, { force: true }).catch(() => {}); } } 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 { hostname } from "node:os"; +import { createHash } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { execa } from "execa"; import { mkdir, + open, readdir, readFile, rename, @@ -16,7 +21,9 @@ import { import { SAVED_VIDEO_POINTER_FILENAME, compactedOriginalOf, + keepsAnyOriginal, parseSavedVideoPointer, + reviewIsCurrent, savedVideoBytes, savedVideoPath, type SavedAlternateReview, @@ -27,9 +34,8 @@ import { type SavedVideoPointer, } from "./savedVideo"; import { assertSavedVideosStoreWritable } from "./savedVideoStore"; -import { resolveEffectiveAvailability } from "./availability-server"; -import type { Availability } from "./availability"; -import { isStillOnPlatform } from "./savedVideoCompaction"; +import { platformPresence } from "./availability-server"; +import { probeMedia } from "./evidenceClip-server"; import type { Paths } from "./paths"; // Filesystem side of the saved-video store. See savedVideo.ts for the layout. @@ -68,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, @@ -76,6 +84,71 @@ 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 (controller/compactSavedVideos.ts) for one video: +// `<store dir>/.compacting.json`, `{pid, host, startedAt}`, written when a +// compaction starts and removed when it ends. A persist, attach, import or +// re-download of that video refuses while it is there (its container stays in +// the data dir or its staging, and the next run picks it up). A marker whose +// process is gone (this host, a dead pid) is stale and ignored. +export const COMPACTING_MARKER_FILENAME = ".compacting.json"; + +export class CompactionInProgressError extends Error { + constructor(message: string) { + super(message); + this.name = "CompactionInProgressError"; + } +} + +export async function liveCompactingMarker(storeDir: string): Promise<{ pid: number; startedAt: string } | null> { + const read = await readJsonFile(path.join(storeDir, COMPACTING_MARKER_FILENAME)); + if (!read.ok || !read.value || typeof read.value !== "object") return null; + const m = read.value as { pid?: unknown; host?: unknown; startedAt?: unknown }; + if (typeof m.pid !== "number") return null; + if (m.host === hostname()) { + try { + process.kill(m.pid, 0); + } catch { + return null; + } + } + return { pid: m.pid, startedAt: String(m.startedAt ?? "") }; +} + +export async function assertNotCompacting(storeDir: string, what: string): Promise<void> { + const m = await liveCompactingMarker(storeDir); + if (m) { + throw new CompactionInProgressError( + `${what} refused: this video's saved copy is being compacted (since ${m.startedAt.slice(0, 16)}, pid ${m.pid}). ` + + "Run it again once the compaction is done.", + ); + } +} + // 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 @@ -85,11 +158,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 @@ -127,7 +202,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; @@ -156,10 +231,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); @@ -168,6 +253,12 @@ export async function persistSourceVideo(opts: { // files no pointer names. const before = await loadSavedVideo(opts.videoDir); 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 @@ -200,6 +291,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); @@ -231,31 +323,37 @@ export async function updateSavedVideoChecksum( } // A PERSON'S REVIEW OF A COMPACTED COPY, recorded on its original's alternate -// entry (`review`): what a video gone from its platform needs before its -// original may be dropped (dropSavedAlternate). Refused when the pointer keeps -// no `keptAs: "original"` alternate. Raw JSON, under the pointer's lock. +// 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: SavedAlternateReview, + review: Omit<SavedAlternateReview, "forSha256">, ): 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 (!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 beside a compacted copy: there is nothing to review."); + throw new SavedAlternateRefusal("This video keeps no original of its compacted copy: there is nothing to review."); } - if (pointer.compacted && !pointer.compacted.checks.passed) { + 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 } : 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 }; + return { ...original, review: full }; }); } @@ -268,13 +366,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 } : {}), + }); }); } @@ -322,8 +422,16 @@ 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 @@ -363,21 +471,24 @@ export async function unpersistSavedVideo( // 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; - const original = compactedOriginalOf(pointer); - if (original) { - throw new SavedAlternateRefusal( - `This video keeps its original ${original.file} beside a compacted copy: it is never dropped whole.`, - ); - } - 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 @@ -441,6 +552,76 @@ export function isBareStoreName(file: string): boolean { // 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 async function dropSavedAlternate( videoDir: string, file: string, @@ -448,11 +629,17 @@ export async function dropSavedAlternate( dryRun?: boolean; paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">; confirmOriginal?: boolean; - verifiedActive?: { sha256: string }; // Who drops it, for `originalDropped.by` (default "drop-saved-alternate"). by?: string; - // The availability the gone-video rule reads (default: the video dir's). - availability?: Availability | null; + // 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 read-back's hasher and prober (tests name their own). + readBack?: ReadBackDeps; } = {}, ): Promise<DropSavedAlternateResult> { if (!isBareStoreName(file)) { @@ -472,6 +659,27 @@ export async function dropSavedAlternate( } const alternate = pointer.alternates?.find((a) => a.file === file); if (!alternate) { + // AN INTERRUPTED DROP OF AN ORIGINAL: the pointer was written, the file + // was not removed. Asked again by name, with the confirm, it is finished. + const d = pointer.compacted?.originalDropped; + if (d && d.file === file && d.fileRemoved === false && opts.confirmOriginal === 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>) }; + raw.compacted = { ...(raw.compacted as Record<string, unknown>), originalDropped: { ...d, fileRemoved: true } }; + await writeJsonAtomic(pointerFile, raw); + } + return { + dryRun: opts.dryRun === true, + alternate: { file, bytes: d.bytes, storedAt: "", setAsideAt: "", keptAs: "original", sha256: d.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` + @@ -479,33 +687,48 @@ export async function dropSavedAlternate( ".", ); } - if (alternate.keptAs === "original") { + const isOriginal = alternate.keptAs === "original"; + if (isOriginal || alternate.keptAs === "former-original") { if (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.', + `${file} is ${isOriginal ? "the ORIGINAL the active copy was re-encoded from" : "the ORIGINAL of an earlier compacted copy"} ` + + `(sha256 ${alternate.sha256?.slice(0, 12) ?? "unknown"}…): it is dropped only when the drop names it — pass "confirmOriginal": true.`, ); } - if (pointer.compacted) { - if (!pointer.compacted.checks.passed) { - throw new SavedAlternateRefusal(`The compacted copy's checks did not pass: ${file}, its original, is kept.`); - } - if (!opts.dryRun && (!opts.verifiedActive || !pointer.sha256 || opts.verifiedActive.sha256 !== pointer.sha256)) { - throw new SavedAlternateRefusal( - `The compacted copy ${pointer.file} was not read back from disk and matched against its recorded sha256 ` + - `just before this drop: ${file}, its original, is kept.`, - ); - } + const busy = opts.busy ? await opts.busy() : null; + if (busy) throw new SavedAlternateRefusal(`${file} is kept: ${busy}.`); + await assertNotCompacting(pointer.dir, `Dropping ${file}`); + } + 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.`); } - const availability = - opts.availability !== undefined ? opts.availability : await resolveEffectiveAvailability(videoDir).catch(() => null); - if (!isStillOnPlatform(availability) && !alternate.review) { + 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 any more (availability: ${availability ?? "unknown"}): ` + - `the stored ${file} may be the only original there is. Review the compacted copy first ` + - "(review-compacted-original), then drop it.", + `This video is not known to be on its platform (${presence.why}): the stored ${file} may be the only original there is. ` + + "Review the compacted copy first (review-compacted-original), then drop it." + + (alternate.review ? " (Its review is for another copy than the one active now.)" : ""), ); } + 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); @@ -521,26 +744,32 @@ 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 a file the + // pointer says is going (`fileRemoved: false`), never a pointer naming a + // file that is gone. Asking again finishes it (above). 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; - if (alternate.keptAs === "original" && raw.compacted && typeof raw.compacted === "object") { - raw.compacted = { - ...(raw.compacted as Record<string, unknown>), - originalDropped: { - at: new Date().toISOString(), - by: opts.by ?? "drop-saved-alternate", - file, - bytes: st?.size ?? alternate.bytes, - sha256: alternate.sha256 ?? pointer.compacted?.source.sha256 ?? "", - }, - }; - } + const dropped = + isOriginal && raw.compacted && typeof raw.compacted === "object" + ? { + at: new Date().toISOString(), + by: opts.by ?? "drop-saved-alternate", + file, + bytes: st?.size ?? alternate.bytes, + sha256: alternate.sha256 ?? "", + } + : null; + if (dropped) raw.compacted = { ...(raw.compacted as Record<string, unknown>), originalDropped: { ...dropped, fileRemoved: false } }; await writeJsonAtomic(pointerFile, raw); + if (existed) await rm(target, { force: true }); + if (dropped) { + raw.compacted = { ...(raw.compacted as Record<string, unknown>), originalDropped: { ...dropped, fileRemoved: true } }; + await writeJsonAtomic(pointerFile, raw); + } return result; }); } 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 @@ -125,9 +132,29 @@ export type SavedVideoCompactedChecks = { 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: equal or the copy fails. - audio: "identical"; + // 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 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; @@ -161,12 +188,16 @@ export type SavedVideoCompacted = { // 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. - originalDropped?: { at: string; by: string; file: string; bytes: number; sha256: string }; + // 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). -export type SavedAlternateReview = { at: string; by: string; note?: string }; +// 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`. @@ -198,13 +229,18 @@ export type SavedVideoAlternate = { review?: SavedAlternateReview; }; -export const SAVED_ALTERNATE_KEPT_AS = ["proxy", "original"] 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 = { @@ -344,7 +380,13 @@ 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; - return { at: r.at, by: r.by, ...(typeof r.note === "string" && r.note !== "" ? { note: r.note } : {}) }; + // 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> { @@ -404,7 +446,7 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { 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: "identical", + audio: c.audio === "identical" || c.audio === "different" ? c.audio : "unknown", audioHash: strOr(c.audioHash), quality: { metric: q.metric === "ssim" ? "ssim" : "vmaf", @@ -419,6 +461,26 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { : [], 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), + }, + }; + })() + : {}), + ...(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), }; @@ -428,14 +490,31 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { } 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) }; + 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 alternate a compacted pointer keeps its original as, when it still does. +// 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 { - return pointer.alternates?.find((a) => a.keptAs === "original") ?? 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 compacted copy this pointer names now? +export function reviewIsCurrent(pointer: SavedVideoPointer, alternate: SavedVideoAlternate): boolean { + return !!alternate.review && !!pointer.compacted && alternate.review.forSha256 !== "" && alternate.review.forSha256 === pointer.compacted.result.sha256; } function codecName(vcodec: string | undefined): string { @@ -509,7 +588,7 @@ export function savedAlternatesLine(pointer: SavedVideoPointer): string { `alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file}` + `${a.keptAs ? `, ${SAVED_ALTERNATE_KEPT_AS_LABELS[a.keptAs]}` : ""}` + `${a.compactedFrom ? ", a re-encode" : ""}` + - `${a.keptAs === "original" && a.review ? `, reviewed ${day(a.review.at)} by ${a.review.by}` : ""})`, + `${a.keptAs === "original" && a.review && reviewIsCurrent(pointer, a) ? `, reviewed ${day(a.review.at)} by ${a.review.by}` : ""})`, ) .join("; ") ); @@ -562,6 +641,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; } diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts @@ -8,7 +8,7 @@ import { decideCompaction, estimateCompaction, isDeliberatelyStored, - isStillOnPlatform, + availabilitySaysPresent, sanitizeSavedVideoCompaction, targetFps, type CompactionProbe, @@ -54,7 +54,9 @@ test("the operator's rulings are the defaults", () => { assert.equal(D.maxFps, 30); assert.deepEqual(D.maxFpsPlatforms, ["kick", "twitch"]); assert.deepEqual(D.platforms, ["kick", "twitch", "rumble"]); - assert.equal(D.dropOriginal, "after-verify"); + // 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); }); @@ -71,24 +73,27 @@ test("sanitize clamps, lowercases platforms and refuses unknown values", () => { assert.equal(s.crf, D.crf); assert.equal(s.preset, D.preset); assert.equal(s.chunkMinutes, D.chunkMinutes); - assert.equal(s.dropOriginal, "after-verify"); + assert.equal(s.dropOriginal, "keep"); assert.equal(s.maxFps, 0); - assert.equal(sanitizeSavedVideoCompaction({ dropOriginal: "keep" }).dropOriginal, "keep"); + assert.equal(sanitizeSavedVideoCompaction({ dropOriginal: "after-verify" }).dropOriginal, "after-verify"); }); -test("deliberately stored: a pin, an explicit persist, a requested container — never keep-latest or a legacy pointer", () => { +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" }), 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("on its platform only when a record says public or unlisted; unknown counts as gone", () => { - assert.equal(isStillOnPlatform("public"), true); - assert.equal(isStillOnPlatform("unlisted"), true); +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(isStillOnPlatform(a), false, String(a)); + assert.equal(availabilitySaysPresent(a), false, String(a)); } }); @@ -102,9 +107,23 @@ test("the selector picks only deliberately stored AND platform AND bitrate AND h assert.deepEqual(decide({ platform: "rumble", probe: probe({ fps: 30, videoKbps: 3200, height: 720 }) }), { ok: true }); }); -test("an explicit list skips the selector's thresholds but never the deliberate rule", () => { - assert.deepEqual(decide({ mode: "explicit", platform: "youtube", probe: probe({ videoKbps: 400, height: 360 }) }), { ok: true }); - assert.equal(decide({ mode: "explicit", pointer: pointer({ keepReason: "keep-latest" }) }).ok, false); +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", () => { diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts @@ -11,6 +11,9 @@ // - 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 @@ -22,7 +25,7 @@ // Pure: no node imports (the editor's client pages read the labels). import type { FieldDocs } from "./fieldDocs"; -import type { SavedVideoPointer } from "./savedVideo"; +import { keepsAnyOriginal, type SavedVideoPointer } from "./savedVideo"; import type { Availability } from "./availability"; // --- settings ----------------------------------------------------------------- @@ -44,6 +47,9 @@ export type SavedVideoCompactionSettings = { vmafMinSample: number; ssimMinMean: number; ssimMinSample: number; + wholeFileSsimMin: number; + wholeFileSsimMean: number; + availabilityMaxAgeDays: number; dropOriginal: CompactionDropOriginal; }; @@ -64,7 +70,12 @@ export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettin // Only where this ffmpeg has no libvmaf: SSIM on the same samples. ssimMinMean: 0.95, ssimMinSample: 0.9, - dropOriginal: "after-verify", + // 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, + availabilityMaxAgeDays: 7, + dropOriginal: "keep", }; export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCompactionSettings> = { @@ -86,8 +97,13 @@ export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCom 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: both copies decoded at 2 frames a second, 64 px wide, grey, frames paired by their time, and compared one by one (SSIM). No frame may fall below this. Default 0.9 (a good copy scores about 0.99; a black or misplaced stretch of a test pattern 0.5–0.8).", + wholeFileSsimMean: "The whole-file comparison's mean SSIM must reach this. Default 0.97.", + 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: - '"after-verify" (default, operator ruling): once every check passed and the pointer names the compacted copy, a separate step reads that copy back from disk (size, sha256, container, length) and then drops the original — except for a video gone from its platform (availability not public or unlisted, or unknown), whose original waits for a person\'s review (`get compaction-review`, `review-compacted-original`, then `drop-saved-alternate` with `confirmOriginal`). "keep": every original stays until a person drops it.', + '"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 { @@ -122,6 +138,9 @@ export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompacti 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), + availabilityMaxAgeDays: clampNum(r.availabilityMaxAgeDays, d.availabilityMaxAgeDays, 0, 365), dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal) ? (r.dropOriginal as CompactionDropOriginal) : d.dropOriginal, @@ -130,27 +149,28 @@ export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompacti // --- what counts -------------------------------------------------------------- -// DELIBERATELY STORED (ruling 4): a pointer whose keepReason 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; -// keepReason "override" an explicit persist ("Persist source video", -// persist-videos, the whole-recording fetch); -// any `origin` a container somebody requested (umtool's -// `full: true`, a landed or attached file), whatever -// its keepReason. -// NOT: keepReason "keep-latest" with no origin (the automatic window), and a -// legacy pointer with neither (nobody recorded why it is kept). -export function isDeliberatelyStored(pointer: Pick<SavedVideoPointer, "keepReason" | "origin">): boolean { +// 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; - return pointer.keepReason === "pin" || pointer.keepReason === "override"; + if (pointer.explicit === true) return true; + return pointer.keepReason === "pin"; } -// STILL ON ITS PLATFORM: only a record that says so. Anything else — deleted, -// private, members-only, needs-auth, a probe that errored, or no record at -// all — is treated as gone (ruling 6: the stored bytes may be the only -// original that exists). -export function isStillOnPlatform(a: Availability | null | undefined): boolean { +// 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"; } @@ -166,7 +186,11 @@ export type CompactionProbe = { audioKbps: number | null; }; -export type CompactionDecision = { ok: true } | { ok: false; reason: string }; +// `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; @@ -177,9 +201,14 @@ export function decideCompaction(opts: { 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 { @@ -187,7 +216,9 @@ export function decideCompaction(opts: { reason: pointer.keepReason === "keep-latest" ? "an automatic keep-latest container (compaction is for deliberately stored videos only)" - : "no keep reason recorded (a legacy pointer): not known to be kept on purpose", + : 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` }; @@ -195,21 +226,23 @@ export function decideCompaction(opts: { 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" }; - if (opts.mode === "select") { - if (!opts.platform || !s.platforms.includes(opts.platform)) { - return { ok: false, reason: `platform ${opts.platform ?? "unknown"} is not selected` }; - } - if (probe.height === null || probe.height < s.minHeight) { - return { ok: false, reason: `${probe.height ?? "unknown "}p is below minHeight ${s.minHeight}` }; - } - if (probe.videoKbps === null || probe.videoKbps < s.minVideoMbps * 1000) { - return { - ok: false, - reason: `${probe.videoKbps === null ? "unknown" : (probe.videoKbps / 1000).toFixed(2)} Mbit/s video is below minVideoMbps ${s.minVideoMbps}`, - }; - } + 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 { ok: true }; + return null; } // The output frame rate: the cap when the source is above it on a capped @@ -302,11 +335,11 @@ export function compactionFreeNeeded(estimateHighBytes: number, writtenBytes: nu // 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> = []): string { +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}.mp4`; - for (let n = 2; names.has(name); n++) name = `${stem}-${n}.mp4`; + let name = `${stem}${ext}`; + for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`; return name; } diff --git a/common/lib/savedVideoOriginal.test.ts b/common/lib/savedVideoOriginal.test.ts @@ -1,7 +1,8 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { hostname, tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "./paths"; import { @@ -11,6 +12,8 @@ import { savedAlternatesLine, } from "./savedVideo"; import { + COMPACTING_MARKER_FILENAME, + CompactionInProgressError, SavedAlternateRefusal, dropSavedAlternate, dropSavedVideo, @@ -28,13 +31,20 @@ import { // 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 — with the re-check, and for a video not known -// to be on its platform, a review. +// 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 SHA_ACTIVE = "a".repeat(64); -const SHA_ORIGINAL = "b".repeat(64); +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 { @@ -43,7 +53,7 @@ function compactedBlock(extra: Record<string, unknown> = {}) { 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: 5, sha256: SHA_ACTIVE, vcodec: "av1", height: 1080, fps: 30, 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, @@ -56,6 +66,7 @@ function compactedBlock(extra: Record<string, unknown> = {}) { 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, @@ -64,10 +75,7 @@ function compactedBlock(extra: Record<string, unknown> = {}) { type Fixture = { paths: Paths; videoDir: string; storeDir: string }; -async function withCompacted( - opts: { pointer?: Record<string, unknown>; originalOnDisk?: boolean } = {}, - fn: (f: Fixture) => Promise<void>, -): Promise<void> { +async function withCompacted(fn: (f: Fixture) => Promise<void>): Promise<void> { const root = await mkdtemp(path.join(tmpdir(), "compacted-original-")); const paths = { transcriptsDir: root, @@ -78,13 +86,13 @@ async function withCompacted( const storeDir = path.join(paths.savedVideosDir, "kick", "v1"); await mkdir(videoDir, { recursive: true }); await mkdir(storeDir, { recursive: true }); - await writeFile(path.join(storeDir, ACTIVE), "av1!!"); - if (opts.originalOnDisk !== false) await writeFile(path.join(storeDir, ORIGINAL), "o".repeat(1200)); - const pointer = opts.pointer ?? { + 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: 5, + bytes: ACTIVE_BYTES.length, sha256: SHA_ACTIVE, keepReason: "pin", format: { preset: "original", height: 1080, vcodec: "av1" }, @@ -111,6 +119,10 @@ async function withCompacted( } 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) => + writeFile(path.join(storeDir, COMPACTING_MARKER_FILENAME), JSON.stringify({ pid: process.pid, host: hostname(), startedAt: "2026-11-14T00:00" })); test("a pointer without `compacted` parses exactly as before", () => { const raw = { storedAt: "x", dir: "/s", file: "source-media.mp4", bytes: 3, keepReason: "pin" }; @@ -128,7 +140,7 @@ test("the compacted block and the original parse back, and every line says re-en 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.quality.mean, 94.2); + 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\./); @@ -138,61 +150,90 @@ test("the compacted block and the original parse back, and every line says re-en assert.match(alts, /the original the active copy was re-encoded from, kept until it is dropped/); }); -test("a damaged compacted block still reads as a re-encode, its checks as not passed", () => { +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 withCompacted(async ({ videoDir, storeDir }) => { await assert.rejects( - dropSavedAlternate(videoDir, ORIGINAL, { availability: "public", verifiedActive: { sha256: SHA_ACTIVE } }), + 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("an original is not dropped unless the compacted copy was just re-checked against its sha256", async () => { - await withCompacted({}, async ({ videoDir, storeDir }) => { - for (const verifiedActive of [undefined, { sha256: "f".repeat(64) }]) { - await assert.rejects( - dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, availability: "public", ...(verifiedActive ? { verifiedActive } : {}) }), - /was not read back from disk/, - ); - } +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 the re-check. - const dry = await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, availability: "public", dryRun: true }); + // 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 is recorded", async () => { - await withCompacted({}, async ({ videoDir, storeDir }) => { - for (const availability of [null, "deleted", "error", "private"] as const) { - await assert.rejects( - dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE }, availability }), - /not known to be on its platform any more.*Review the compacted copy first/, - ); - } - // With no availability record on disk at all, the default reads it as gone. +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, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE } }), - /availability: unknown/, + dropSavedAlternate(videoDir, ORIGINAL, { ...CONFIRM, presence: GONE }), + /not known to be on its platform \(no availability record\).*Review the compacted copy 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?.by, "editor"); - const r = await dropSavedAlternate(videoDir, ORIGINAL, { - confirmOriginal: true, - verifiedActive: { sha256: SHA_ACTIVE }, - availability: null, - by: "test", - }); + 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); @@ -200,33 +241,94 @@ test("a video not known to be on its platform keeps its original until a review assert.equal(raw.compacted.originalDropped.by, "test"); assert.equal(raw.compacted.originalDropped.sha256, SHA_ORIGINAL); assert.equal(raw.compacted.originalDropped.bytes, 1200); - assert.match(compactedLine((await loadSavedVideo(videoDir))!)!, /The original was dropped on 20\d\d-\d\d-\d\d \(sha256 bbbbbbbbbbbb…, 1200 bytes\)/); + 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 video on its platform drops its original with confirm and the re-check, no review needed", async () => { - await withCompacted({}, async ({ videoDir, storeDir }) => { - await dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE }, availability: "public" }); +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 }; + await writeRaw(videoDir, raw); + await assert.rejects(dropSavedAlternate(videoDir, ORIGINAL, { presence: ON }), /not one of this video's listed alternates/); + 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 }) => { + await withCompacted(async ({ videoDir }) => { const raw = await readRaw(videoDir); raw.compacted.checks.passed = false; - await writeFile(savedVideoPointerPath(videoDir), JSON.stringify(raw)); - await assert.rejects( - dropSavedAlternate(videoDir, ORIGINAL, { confirmOriginal: true, verifiedActive: { sha256: SHA_ACTIVE }, availability: "public" }), - /checks did not pass/, - ); + 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 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)); @@ -235,15 +337,15 @@ test("dropSavedVideo (the prune's delete) refuses a video that keeps an original }); test("unpersist brings every copy back with the original as the source; refused once the original is gone", async () => { - await withCompacted({}, async ({ videoDir }) => { + await withCompacted(async ({ videoDir }) => { assert.equal(await unpersistSavedVideo(videoDir), true); - assert.equal(await readFile(path.join(videoDir, ORIGINAL), "utf8"), "o".repeat(1200)); + assert.equal(await readFile(path.join(videoDir, ORIGINAL), "utf8"), ORIGINAL_BYTES); await stat(path.join(videoDir, ACTIVE)); }); - await withCompacted({}, async ({ videoDir, storeDir }) => { + await withCompacted(async ({ videoDir, storeDir }) => { const raw = await readRaw(videoDir); delete raw.alternates; - await writeFile(savedVideoPointerPath(videoDir), JSON.stringify(raw)); + 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)); @@ -251,21 +353,44 @@ test("unpersist brings every copy back with the original as the source; refused }); }); -test("a persist landing under the original's name moves the original aside, never over it", async () => { - await withCompacted({}, async ({ videoDir, storeDir }) => { +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.keptAs === "original"); + 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); - assert.equal(await readFile(path.join(storeDir, kept.file), "utf8"), "o".repeat(1200)); + // 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 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); 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 @@ -57,10 +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"; @@ -173,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); @@ -222,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(() => [])); @@ -237,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, @@ -245,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) { diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,18 +2,29 @@ ## [Unreleased] - **A saved video can be compacted: re-encoded to AV1, verified, and said to be a re-encode everywhere.** - `pnpm ops compact-saved-videos` (`{"items": [...]}` or `{"select": true}`, `dryRun` first) re-encodes a deliberately - stored container with SVT-AV1 (settings `savedVideoCompaction`: crf 36, preset 8, a keyframe every 5 s, Kick and - Twitch above 30 fps to 30, the audio copied). It runs in resumable chunks, each through the heavy slot, as one job per - channel on the `compact` queue. The re-encode becomes the active copy only when every check passes: a full decode, - the length, the frame count, identical audio packets, VMAF on excerpts, windows cut through the evidence cutter, and - the recording clock re-measured. The original stays beside it as `"keptAs": "original"`. - - Under `dropOriginal: "after-verify"` (the default) the original is dropped in a later step, after the copy is read - back from disk. A video not known to be on its platform waits for a person's review instead - (`get compaction-review`, /saved-videos, the video page's **Review the compacted copy**). - - `drop-saved-alternate` drops an original only with `"confirmOriginal": true` and a fresh re-check of the - compacted copy. Nothing else deletes one: the prune keeps the video, unpersist brings the original back, and a - persist landing on its name moves it aside. + `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. - **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 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 @@ -66,3 +66,15 @@ test("a dry run answers the plan — a keep-latest container is skipped — and 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 @@ -5,7 +5,7 @@ import { OpsInputError, ops, opsFail, optBool, reqSlugs, reqVideoItems, type Ops export const dynamic = "force-dynamic"; // POST { items: [{ slug, id }, …] } | { select: true, slugs? }, -// dryRun?, retryFailed?, crf?, preset?, maxFps?, chunkMinutes? +// 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 }] } @@ -21,6 +21,12 @@ export const dynamic = "force-dynamic"; // `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; @@ -33,7 +39,7 @@ function optNumber(body: OpsBody, key: string, lo: number, hi: number): number | export async function POST(request: Request) { return ops( request, - ["items", "select", "slugs", "dryRun", "retryFailed", "crf", "preset", "maxFps", "chunkMinutes"], + ["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); @@ -43,8 +49,10 @@ export async function POST(request: Request) { const result = await compactSavedVideosAction({ ...(select ? { select: true } : { items: reqVideoItems(body, "items") }), ...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}), - dryRun: optBool(body, "dryRun") ?? false, + // 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 } : {}), diff --git a/editor/app/api/ops/review-compacted-original/route.ts b/editor/app/api/ops/review-compacted-original/route.ts @@ -5,9 +5,12 @@ import { ops, opsFail, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; // POST { slug, id, note? } -// -> { ok, original } +// -> { ok, original, watched } // -// A person's review of a compacted copy: "the compacted copy is proven good". +// 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 @@ -20,6 +23,6 @@ export async function POST(request: Request) { ...(optString(body, "note") ? { note: optString(body, "note") } : {}), }); if (!res.ok) return opsFail(res.error); - return NextResponse.json({ ok: true, original: res.original }); + return NextResponse.json({ ok: true, original: res.original, watched: res.watched }); }); } diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/SourceVideoSection.tsx @@ -219,7 +219,11 @@ function PersistedSourceVideo({ <dd> {savedVideo.compacted.checks.passed ? "passed" : "NOT passed"}:{" "} {savedVideo.compacted.checks.frames[1]}/{savedVideo.compacted.checks.frames[2]} frames, - audio identical, {savedVideo.compacted.checks.quality.metric.toUpperCase()}{" "} + 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 ?? "?"})`}` @@ -257,6 +261,11 @@ function PersistedSourceVideo({ videoId={videoId} alternate={a} compacted={!!savedVideo.compacted} + watch={ + savedVideo.compacted + ? `smplayer "${savedVideo.dir}/${savedVideo.file}" "${savedVideo.dir}/${a.file}"` + : undefined + } /> ))} </ul> @@ -301,11 +310,15 @@ function SavedAlternateRow({ 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); @@ -396,7 +409,10 @@ function SavedAlternateRow({ {original && compacted && !alternate.review && ( reviewArmed ? ( <> - <span>Record that the compacted copy is proven good? Nothing is deleted.</span> + <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} diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -76,8 +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 { recheckCompactedCopy } from "yt-dlp-transcript-common/controller/compactSavedVideos"; +import { videoPersistBusyReason } from "yt-dlp-transcript-common/controller/videoBusy"; import { + CompactionInProgressError, dropSavedAlternate, loadSavedVideo, SavedAlternateRefusal, @@ -1445,7 +1446,7 @@ export async function unpersistVideoAction( reversed = await unpersistSavedVideo(videoDir); } catch (e) { // A compacted copy whose original was dropped is refused (lib/savedVideo-server.ts). - if (e instanceof SavedAlternateRefusal) return { ok: false, error: e.message }; + if (e instanceof SavedAlternateRefusal || e instanceof CompactionInProgressError) return { ok: false, error: e.message }; throw e; } if (!reversed) { @@ -1466,8 +1467,8 @@ export async function unpersistVideoAction( // // AN ORIGINAL (`keptAs: "original"`, the source a compacted copy was // re-encoded from) needs `confirmOriginal`; before a real drop the compacted -// copy is read back from disk (recheckCompactedCopy: size, sha256, container, -// length) and the drop is refused unless that held. A video not known to be +// 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, @@ -1482,29 +1483,21 @@ export async function dropSavedAlternateAction( return { ok: false, error: `${file} not dropped: this channel's drive is not answering.` }; } const videoDir = videoDirOf(slug, videoId); - let verifiedActive: { sha256: string } | undefined; - if (opts.confirmOriginal && !opts.dryRun) { - const pointer = await loadSavedVideo(videoDir); - const target = pointer?.alternates?.find((a) => a.file === file); - if (pointer?.compacted && target?.keptAs === "original" && pointer.file === pointer.compacted.result.file) { - const recheck = await recheckCompactedCopy({ paths, videoDir }); - if (!recheck.ok) { - return { ok: false, error: `${file} not dropped: the compacted copy did not re-check (${recheck.why}).` }; - } - verifiedActive = { sha256: recheck.sha256 }; - } - } let result: DropSavedAlternateResult; try { result = await dropSavedAlternate(videoDir, file, { dryRun: opts.dryRun, paths, ...(opts.confirmOriginal ? { confirmOriginal: true } : {}), - ...(verifiedActive ? { verifiedActive } : {}), + // 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 @@ -633,6 +633,7 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { ...(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 @@ -59,7 +59,7 @@ function settingsFor(overrides: CompactOverrides): SavedVideoCompactionSettings export async function compactChannelVideosAction( slug: string, ids: string[], - opts: { mode: "explicit" | "select"; overrides?: CompactOverrides; retryFailed?: boolean }, + 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." }; @@ -75,7 +75,13 @@ export async function compactChannelVideosAction( spec: { kind: "compact-saved-videos", slug, - params: { ids: wanted, mode: opts.mode, ...overrides, ...(opts.retryFailed ? { retryFailed: true } : {}) }, + 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). @@ -85,6 +91,7 @@ export async function compactChannelVideosAction( items: wanted.map((id) => ({ slug, id })), mode: opts.mode, ...(opts.retryFailed ? { retryFailed: true } : {}), + ...(opts.belowThreshold ? { belowThreshold: true } : {}), onLog, signal, drainSignal: ctx.drainSignal, @@ -110,6 +117,7 @@ export async function compactSavedVideosAction(input: { slugs?: string[]; dryRun?: boolean; retryFailed?: boolean; + belowThreshold?: boolean; overrides?: CompactOverrides; }): Promise<CompactSavedVideosActionResult> { if (!input.select && !input.items?.length) { @@ -127,6 +135,7 @@ export async function compactSavedVideosAction(input: { ...(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[]>(); @@ -143,6 +152,7 @@ export async function compactSavedVideosAction(input: { 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 }); @@ -156,7 +166,12 @@ export async function compactSavedVideosAction(input: { void result.stream.cancel(); jobs.push({ slug, jobId: result.jobId }); } - if (bySlug.size > 0 && jobs.length === 0) { + 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 }; @@ -170,7 +185,7 @@ export async function compactionReviewList(opts: { slug?: string } = {}): Promis const notAnswering: string[] = []; const rows = await listCompactionReview({ paths: getPaths(), - dropOriginal: getSettings().savedVideoCompaction.dropOriginal, + settings: getSettings().savedVideoCompaction, ...(opts.slug ? { channelSlug: opts.slug } : {}), notAnswering, }); @@ -185,7 +200,7 @@ export async function reviewCompactedOriginalAction( slug: string, videoId: string, opts: { note?: string; by?: string } = {}, -): Promise<{ ok: true; original: SavedVideoAlternate } | { ok: false; error: 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}` }; @@ -199,7 +214,7 @@ export async function reviewCompactedOriginalAction( ...(opts.note?.trim() ? { note: opts.note.trim() } : {}), }); safeRevalidate([`/channels/${slug}/videos/${videoId}`, "/saved-videos"]); - return { ok: true, original }; + return { ok: true, original, watched: original.review?.forSha256 ?? "" }; } catch (e) { if (e instanceof SavedAlternateRefusal) return { ok: false, error: e.message }; throw e; diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx @@ -60,7 +60,7 @@ export default async function SavedVideosPage() { // the ones awaiting a person's review first. const compacted = await listCompactionReview({ paths, - dropOriginal: settings.savedVideoCompaction.dropOriginal, + settings: settings.savedVideoCompaction, notAnswering: [], }); const reviewOrder = ["awaiting-review", "reviewed", "drop-pending", "kept", "dropped"]; @@ -224,9 +224,18 @@ export default async function SavedVideosPage() { <span className={c.state === "awaiting-review" ? "font-medium" : "text-muted-foreground"}> {" "} — {COMPACTION_REVIEW_STATE_LABELS[c.state]} - {c.onPlatform ? "" : ` (availability ${c.availability ?? "unknown"})`}. + {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> 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/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 @@ -504,7 +504,8 @@ const ACTIONS = [ "prepare-playable", // Saved videos re-encoded to AV1, verified, made the active copy, the // original kept beside it ({items: [{slug, id}]} | {select: true, slugs?}, - // dryRun?, retryFailed?, crf?, preset?, maxFps?, chunkMinutes?); and a + // 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", @@ -1192,11 +1193,13 @@ export function usage() { " (height, seconds, origin, keptAs).", " Once one is checked, `drop-saved-alternate` deletes it.", "get compaction-review [<slug>] lists every compacted saved video and what", - ' its original waits for: "awaiting-review" (not known to be on its', + ' 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, the original's entry, sizes, checks and the re-check.", + " 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 sites lists every site: id, title, siteUrl, Pages project, audience,", " listed, search, publish policy, channels, citedChannels. (`get publish`", " is the status.)", @@ -1456,8 +1459,10 @@ export function usage() { ' answers the same and changes nothing. No undo.', ' An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs', ' "confirmOriginal": true; the compacted copy is read back from disk', - " (size, sha256, container, length) before it goes, and a video not known", - " to be on its platform needs its review recorded first.", + " (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.", "", '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', @@ -1872,26 +1877,33 @@ export function usage() { "", 'compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings', ' savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the', - " source's height, Kick and Twitch above 30 fps to 30, the audio copied),", - ' verifies the copy and makes it the active one; the original stays beside', - ' it ("keptAs": "original"): {"items": [{"slug", "id"}, ...]} names videos', - ' (deliberately stored only: pinned, an explicit persist, a requested or', - ' landed container -- never a keep-latest one); {"select": true, "slugs"?}', - " asks the selector (and platform, height and video bitrate). \"dryRun\":", - " true answers each video's line -- size, bitrate, height, fps, the", - " estimate (size, hours), the disk it needs against what is free, or why", - ' it is skipped -- and starts nothing. "crf", "preset", "maxFps",', - ' "chunkMinutes" override the settings for the run; "retryFailed": true', - " runs one whose last checks failed. One job per channel on the compact", - " queue, one video at a time, each chunk through the heavy slot; a re-run", - " resumes. Under dropOriginal \"after-verify\" the original is dropped in", - " a later step once the copy re-checks from disk -- never for a video not", - " known to be on its platform (get compaction-review).", - "", - 'review-compacted-original records a person\'s review of one compacted copy:', - ' {"slug", "id", "note"?}. It changes nothing on disk; it is what lets', + " 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 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 known to be on its platform.", + " video not freshly checked on its platform.", "", 'import-archive-org imports archive.org media into a channel, as one job on', ' archive.org\'s queue: {"slug", "item", "files": [...] | "match": "<regex>"}', diff --git a/settings.json.example b/settings.json.example @@ -167,7 +167,10 @@ "vmafMinSample": 85, "ssimMinMean": 0.95, "ssimMinSample": 0.9, - "dropOriginal": "after-verify" + "wholeFileSsimMin": 0.9, + "wholeFileSsimMean": 0.97, + "availabilityMaxAgeDays": 7, + "dropOriginal": "keep" }, "storage": { "locations": [],