Archilyzer · Source

archilyzer

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

commit 70341dc6d56e0f4f597c4437280af24cd5704cbc
parent 0b83181af876e10669d1244bb13d31c6ec1e2bc3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 12:19:28 -0500

Merge lane/compact-store (verification round): a compacted copy keeps the source's own timestamps and is proven against them -- frames are kept by one constant time rule that ffmpeg and the code agree on frame for frame, across chunk restarts and gaps in the source; a failed check keeps the encode and can be verified again without encoding; a chunk is compared with the others and a join's change of scene is told from a bad chunk; decode damage is fatal by its error lines, the audio is proven packet for packet; a check that could not run is named and stops any drop of the original; the page says what verification cannot promise

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

Diffstat:
MCOMMANDS.md | 3++-
MOPERATING.md | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
MSETTINGS.md | 6++++++
Mcommon/controller/compactSavedVideos.test.ts | 449++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/compactSavedVideos.ts | 561+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/lib/compactMedia-server.ts | 664++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/savedVideo-server.ts | 20++++++++++++++++----
Mcommon/lib/savedVideo.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoCompaction.test.ts | 321++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/savedVideoCompaction.ts | 14++++++++++++++
Meditor/CHANGELOG.md | 26++++++++++++++++++++++++--
Meditor/app/api/ops/compact-saved-videos/route.ts | 11+++++++++--
Aeditor/app/api/ops/kept-failed-encodes/route.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 1+
Meditor/app/saved-videos/compactActions.ts | 17++++++++++++++++-
Mscripts/archilyzer-ops.mjs | 14++++++++++++--
Msettings.json.example | 3+++
17 files changed, 2197 insertions(+), 171 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -156,9 +156,10 @@ 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, 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. | | +| `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 encodes again one whose last checks failed; "reverify": true checks its KEPT encode again without encoding (a chunk whose own content failed is encoded again). One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | | | `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | | `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | | +| `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | | | `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}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -1153,8 +1153,8 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} ordinary alternate. Its prune and its drop would delete the only original. `pnpm ops get kept-originals` lists every pointer that keeps one, and every drop in flight; when it is empty, a rollback is safe for these files. -- **What it does.** A saved container is re-encoded to AV1: SVT-AV1 preset 8, crf 36, a keyframe every 5 s, the - source's height. Kick and Twitch above 30 fps go to 30. Every other stream of the source is copied bit for bit: +- **What it does.** A saved container is re-encoded to AV1: SVT-AV1 preset 8, crf 36, a keyframe at the first frame + at or after every 5 s of time, the source's height. Kick and Twitch above 30 fps go to 30. Every other stream of the source is copied bit for bit: every audio track, subtitles, data, attachments, and the chapters. The re-encode becomes the active copy under its own name, `source-media.compact-av1-<stamp>.mp4` (`.mkv` when the source holds streams an mp4 cannot carry), never the original's. The original stays beside it as the alternate `"keptAs": "original"`, known by its sha256. The @@ -1162,6 +1162,31 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} 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. +- **The source's timestamps are kept.** A live Kick or Twitch recording drops frames, mid-stream as well as at the + end, so its frames are not evenly spaced. The copy keeps every frame's own presentation time: + - 60 → 30 keeps a source frame when at least `keepMinStep` has passed since the last kept frame: one copy frame + less half a source frame, less 0.25 ms (24.75 ms at 60 → 30). That is a frame by TIME, each at its source + time. A 60 fps stretch keeps every other frame, even with timestamps rounded to the millisecond (16, 17, + 17 ms). A stretch where the recording ran at 30 keeps every frame, and after a gap the next frame. It is ONE + CONSTANT RULE: the encoder's `select` is `isnan(prev_selected_t)+gte(t-prev_selected_t,<step>)`, a few + dozen characters whatever the file. A set of runs fragmented into hundreds of thousands on a recording with + millisecond timestamps and broke ffmpeg's parser and argv. Every check that pairs source and copy frames + applies the same rule in code. The scratch state saves the step. Not `framestep`: it + re-times what it keeps, and after an odd gap it wrote a frame the source does not have. Any other ratio goes + through the fps filter's constant grid, which repeats a frame across a gap, so the sync is still kept. + - A chunk starts on a kept keyframe, so each chunk's own selection is the file's. + - The join puts each chunk at its source time (the concat list's `duration`, the span to the next chunk's first + frame), not where the chunk before it happened to end. + + So a frame the recording dropped stays a gap, and the picture stays on the sound's clock after it. The sound is + the source's, packet for packet, at the source's times. SVT-AV1 takes the timestamps through (`-fps_mode + passthrough`) and is told the copy's rate (`-svtav1-params fps-num/fps-denom`). On a source with no dropped + frames the copy decodes frame for frame as the constant-rate encode before it, with the same timestamps. The + window cutter, the excerpt checks and the clock map all seek by time. The checks seek each file at that frame's + time on ITS OWN command-line timeline: ffmpeg starts an mpegts's timeline at its video and an mp4's at its + container start, and one shared time landed a frame apart. A playable copy is a lossless remux and keeps the + times. The pointer records the recording's dropped frames: `checks.sourceGaps` gives count, total, largest and + where. - **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 @@ -1173,11 +1198,12 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} 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). + AV1, audio-only, a channel with `excludeFromCompaction` (CHANNEL.md), and one whose last checks failed: its + encode is kept (below), `"reverify": true` checks it again, `"retryFailed": true` encodes it all 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. + reason, and a kept failed encode its size. A last line gives the total and what the kept failed encodes hold. + Nothing is written. - **The run.** One job per channel on the `compact` queue, one video at a time. The source is hashed fresh first; one whose bytes disagree with the sha256 on its pointer is not compacted. While it runs, `<store dir>/.compacting.json` makes every persist, attach, import, unpersist and drop of that video refuse with a @@ -1189,11 +1215,28 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} first chunk not done; a restart leaves the job for a person to retry, because the run may drop originals. The disk floor is checked before the first chunk and before each one: two outputs, less what the chunks hold, plus 2 GiB. -- **The checks.** Every one must pass, or the original stays active and untouched, the re-encode is removed, and the - reason is in the log, the result and `.compact-scratch/failed.json`: - - a full decode without an error; - - the video's length within a frame of the source's, the frame count the fps change gives, no gap between frames - the source does not have, and the picture's start against the sound's as in the source; +- **The checks.** Every one must pass, or the original stays active and untouched. EVERY CHECK RUNS and records its + own result, so one failed run lists every failure (`failed.json` `failures`); only a copy that cannot be opened + stops the list. The reasons are in the log, the result and `.compact-scratch/failed.json`. The checks: + - a full decode without an error, in two passes. Each stream keeps its own time base (`-enc_time_base demux`): + re-quantised to the copy's nominal 1001/30000, two frames around a dropped one landed on one tick and the null + muxer complained about nothing in the picture. + - The video pass decodes 0:v:0 alone. + - The audio pass then decodes every track. The audio is the source's packet for packet, so audio damage the + source's own audio shows as much of is a note; more than that fails. + + Fatal: a non-zero exit of the video pass, or a line naming damage. The patterns are error, invalid, corrupt, + conceal, missing, non-existing, overread, out of range, illegal, damaged, truncated, unavailable, failed, + mmco, desync, no frame, broken, frame num gap, could not find ref, unknown OBU, partial file, and the AAC + decoder's reserved bit, prediction, not allocated, input buffer exhausted, exceeds limit and inconsistent + channel configuration. Benign: the muxer's "non monotonically increasing dts". Any other line is a note + (`checks.decodeNotes`); + - THE TIMESTAMPS, every frame (`checks.timestamps`): each copy frame at the time its source frame had, relative to + each file's start, within `PTS_TOLERANCE_SECONDS` (1 ms: Matroska keeps milliseconds, mp4 at 90 kHz is exact). + The pointer records the worst deviation, where, and the worst in each chunk: the picture against the sound + along the file. Also checked: the frame count the fps change gives, the copy's last frame at the source's last + kept frame, no gap the source's kept frames do not have, and the picture's start against the sound's as in the + source. The length as frames ÷ rate is no check: a recording that dropped frames is not that long; - the audio packets identical (bytes, and times to the millisecond); - every other stream and the chapters present (`checks.streams`); - THE WHOLE FILE compared, EVERY FRAME. Both copies are decoded end to end, the source taken to the copy's rate @@ -1201,7 +1244,8 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} the copy. Each frame is scored whole: - no frame below `wholeFileSsimMin` (0.9); - a mean of at least `wholeFileSsimMean` (0.97); - - no frame below the file's own mean − max(`wholeFileSigmaK` (8) × its spread, `wholeFileSigmaMargin` (0.03)). + - no frame below the relative floor of the frames around it: their median − max(`wholeFileSigmaK` (8) × their + robust spread, `wholeFileSigmaMargin` (0.03)), described below. Each frame is also split into an 8×8 grid of tiles, each scored alone: a tile below `wholeFileTileMin` (0.7) for more than `wholeFileTileRunFrames` (2) frames in a row fails, so a small region changed for 3 frames at 30 @@ -1211,22 +1255,83 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} cannot see a hue shift or chroma-only noise. The relative floor is LOCAL: each frame is judged against the `wholeFileWindowSeconds` (120) around it, the lower of the floors of the half-window before and the half-window after (median − max(8 × 1.4826 × the median absolute deviation, 0.03)). So a stream that alternates a webcam - and a screen share is judged stretch by stretch, and a few bad frames cannot widen their own floor. A degraded - stretch longer than the window looks steady to that floor. It is caught instead by the absolute per-frame floor, - the tile grid, the mean floor, and the VMAF excerpts, laid at least one every window across the file. At 640×360 the - comparison costs about 5–6× a plain decode of both files; its per-frame cost is fixed (about 4 ms at 256 px), so - it adds roughly 35 minutes to a 5-hour 30 fps stream (an estimate). `"after-verify"` drops only when the pointer - records both the luma and the colour comparison; + and a screen share is judged stretch by stretch, and a few bad frames cannot widen their own floor. + + When the file keeps coming back to a lower-scoring kind of picture, a half-window that is a fifth or more that + kind takes its floor from those frames alone (the pointer's `lowerState`). So a stream switching between a share + and a webcam every 20 s passes. Only scenes count as such a kind: + - runs of at least `wholeFileLowerRunSeconds` (8) below the split, so a fault of a few seconds every GOP, or every + few seconds, never passes as one; + - at least 3 such runs, together at least a tenth of the file, scoring below the other kind's floor; + - no run beginning or ending on a chunk join. That is a bad chunk's signature, and when most runs are such, the + kind is refused (`lowerStateRefused`). + + A degraded stretch longer than the window looks steady to that floor. It is caught instead by the absolute + per-frame floor, the tile grid, the mean floor, the VMAF excerpts (at least one every window across the file), + and the per-chunk comparison below. At 640×360 the comparison costs about 5–6× a plain decode of both files. + Its per-frame cost is fixed (about 4 ms at 256 px), so it adds roughly 35 minutes to a 5-hour 30 fps stream (an + estimate); + - EVERY CHUNK AGAINST THE OTHERS (`checks.chunkMeans`): each chunk's mean, grey, U and V, must reach the other + chunks' median − max(`wholeFileChunkSigmaK` (4) × their robust spread, `wholeFileChunkMargin` (0.02)). A chunk + below it fails unless the source explains the drop: + - most of the chunk is the file's lower kind of picture, and its mean reaches what that mix predicts, less the + margin; or + - neither of its joins shows the drop: the 5 s just inside the chunk score within half the drop of the 5 s just + outside. A bad encode of a chunk changes level at its joins; a harder scene that runs across chunks (a game hour + in a talk stream) changes level where the scene changes; + - or the SOURCE itself steps to HARDER picture at every join where the copy drops. Its picture detail (the + mean of a Sobel edge map, per frame, from the decode the comparison already makes) must be 10 % or more higher + inside than outside, both over the 5 s either side and over the whole chunk against the neighbouring one. + That is a scheduled segment starting right at a join. A drift, a step to easier picture, or noise over a flat + picture explains nothing. A bad chunk that coincides exactly with a harder scene of its own length looks the + same as a good one and passes. A bad chunk of unchanged picture still fails, and its message + names the join and its time, says it may still be a segment change there, and gives the way forward: look at the + source there, or run with another `chunkMinutes`, which puts the joins elsewhere (it encodes again). + + `"after-verify"` drops only when the pointer records the luma, the colour and the per-chunk comparison; - 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; + original's better a frame off fails. A window needs 3 s whose copy frames are evenly spaced (each step within + a tenth of a copy frame), because the cutter re-encodes on its own time base. On a recording too choppy for + one, that cut is SKIPPED and named in `checks.skipped`, never counted as passed. "after-verify" never drops an + original after a skipped check; - 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. +- **A failed check keeps the encode.** The chunks, the state and the joined copy stay in `.compact-scratch/`, the + copy renamed `failed-copy.*`, never the active copy and never read by anything else. They stay until a person + clears them or a later run of that video decides: + - `"reverify": true` checks the kept encode again without encoding (after a check is fixed or a threshold moved). + A chunk whose own content failed (a frame count, the per-chunk comparison) is encoded again. + - `"retryFailed": true`, or changed encode settings, encodes it all again. + - `pnpm ops kept-failed-encodes` lists them with their size, and `{"clear": {"slug", "id"}}` removes one. A + compaction that is running is refused. It also lists, as `orphaned`, any scratch in the store whose video has + no pointer any more, and clears those the same way. + - When the pointer goes (unpersist, the prune's drop), its scratch goes with it, after the same guards. + + The disk they hold is the store's: the floor of every later run sees less free space, and a re-verify needs room + only for what it encodes again. - **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. +- **What verification does not guarantee.** It catches every planted defect we have tried, but a copy can pass and + still be slightly worse than its source in these places: + - a long, evenly softer stretch of about 90 s or more (it becomes its own neighbourhood) that does not begin or + end at a chunk join, unless it falls below the absolute or mean floor, the tile floor or a VMAF excerpt; + - a whole chunk less than `wholeFileChunkMargin` (0.02) below the others (more on a stream whose chunks vary), or a + chunk that drops 5 s or more after its join and recovers 5 s or more before the next. Most chunks equally bad + move the median with them; + - a change to less than about 0.5% of the frame for a few seconds; + - a slight defect within about 40 s of a scene change into a lower-scoring kind of picture; + - in a file that keeps returning to a lower-scoring kind of picture, a stretch of about 35 s or more, or any dip + while the two kinds switch quickly, that stays above that kind's floor. + + A harder chunk the source does not explain fails the copy. That is a chunk below the others with a level change at + its join: a scene change into a harder picture that lands within 5 s of a join, in a kind the file does not keep + returning to. The original stays active and the log names the chunk. That failure is safe; a pass would not be. + + A verified copy is a close copy, not an identical one. That is why `dropOriginal` stays `"keep"`. - **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: diff --git a/SETTINGS.md b/SETTINGS.md @@ -656,6 +656,9 @@ Compacting a saved video (`pnpm ops compact-saved-videos`, controller/compactSav | `wholeFileChromaMin` | `0.9` | THE COLOUR, every frame: the whole-file comparison also scores the U and V planes (SSIM), which the grey comparison and VMAF do not see — a hue shift, chroma-only noise. No frame's lower plane may fall below this. Default 0.9 (a good crf-36 SVT-AV1 copy of a detailed test pattern: lowest 0.991). | | `wholeFileChromaMean` | `0.97` | The colour planes' mean must reach this. Default 0.97 (good copy: 0.9986). | | `wholeFileWindowSeconds` | `120` | The NEIGHBOURHOOD the relative floor is taken over: each frame is judged against the frames in the half-window just before it and just after it (the lower of their two floors), so a stream alternating two kinds of picture (a webcam, a screen share) is judged stretch by stretch, not by the file's dominant mode. A short defect inside a steady stretch has that stretch on both sides and falls below it. A degraded stretch longer than the window looks steady to it: such a stretch is caught by the absolute per-frame floor, the tile grid, the mean floor, and the VMAF excerpts, one at least every window across the whole file. Default 120 s; 5–3600. | +| `wholeFileLowerRunSeconds` | `8` | A file that keeps coming back to a lower-scoring kind of picture (a webcam between screen shares) judges a neighbourhood that is a fifth or more that kind by those frames alone. Only SCENES count toward that kind: runs of at least this many seconds below the split, at least 3 of them, at least a tenth of the file, and none beginning or ending on a chunk join (a bad chunk's signature). Shorter runs are judged by the stretch around them, so a fault of a few seconds every GOP never passes as a kind of picture. Default 8 (longer than one 5 s GOP, with margin); 1–600. | +| `wholeFileChunkSigmaK` | `4` | EVERY CHUNK AGAINST THE OTHERS: each chunk's mean (grey, U and V) must reach the other chunks' median − max(this × their robust spread, wholeFileChunkMargin). A chunk below it fails unless the source explains it: most of it is the file's recurring lower kind of picture, or its joins show no drop (a harder scene runs across chunks; a bad chunk changes level at its joins). Default 4. | +| `wholeFileChunkMargin` | `0.02` | The least the per-chunk floor sits under the other chunks' median. Default 0.02. | | `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. | @@ -692,6 +695,9 @@ Default: "wholeFileChromaMin": 0.9, "wholeFileChromaMean": 0.97, "wholeFileWindowSeconds": 120, + "wholeFileLowerRunSeconds": 8, + "wholeFileChunkSigmaK": 4, + "wholeFileChunkMargin": 0.02, "availabilityMaxAgeDays": 7, "dropOriginal": "keep" } diff --git a/common/controller/compactSavedVideos.test.ts b/common/controller/compactSavedVideos.test.ts @@ -9,7 +9,9 @@ import type { Paths } from "../lib/paths"; import { compactOne, compactSavedVideos, + clearKeptFailedEncode, listCompactionReview, + listKeptFailedEncodes, listKeptOriginals, sweepCompactingMarkers, planCompaction, @@ -21,14 +23,28 @@ import { cutIsOffset, encodeChunkArgs, ffmpegHas, + fullDecode, + keepMinStep, + keptSourceFrames, + planChunks, + scanVideoPackets, type ChunkPlan, type EncodeSettings, } from "../lib/compactMedia-server"; import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, type SavedVideoCompactionSettings } from "../lib/savedVideoCompaction"; -import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, restoreSavedVideoProvenance, savedVideoPointerPath } from "../lib/savedVideo-server"; +import { + SavedPointerChangedError, + dropSavedVideo, + loadSavedVideo, + persistSourceVideo, + restoreSavedVideoProvenance, + savedVideoPointerPath, + unpersistSavedVideo, +} 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"; +import { decidePlayable } from "../lib/playableMedia"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compactSavedVideos.test.ts @@ -56,17 +72,46 @@ const NO_SVT = NO_TOOLS || (!svt && "this ffmpeg has no libsvtav1"); const ORIGINAL = "source-media.mp4"; -type Gen = { gen?: string; seconds?: number; fps?: number; gop?: number; offset?: number; ext?: string; bf?: number; size?: string }; +type Gen = { + gen?: string; + seconds?: number; + fps?: number | string; + gop?: number; + offset?: number; + ext?: string; + bf?: number; + size?: string; + // A LIVE RECORDING'S DROPPED FRAMES: source frames [from, to] removed, every + // other frame keeping its own timestamp (a gap, as a Kick stream has). + drop?: [number, number][]; + // …or the same as one select expression of n (dropped where true). + dropExpr?: string; + // A white frame pair at this second, and a click in the sound at the same + // second: whether picture and sound still meet after a gap. + flash?: number; +}; async function makeSource(file: string, g: Gen = {}): Promise<void> { const seconds = g.seconds ?? 6; const fps = g.fps ?? 60; + const vf = [ + ...(g.flash !== undefined ? [`drawbox=c=white:t=fill:enable='between(t,${g.flash - 0.001},${g.flash + 0.03})'`] : []), + ...(g.drop?.length ? [`select='not(${g.drop.map(([a, b]) => `between(n,${a},${b})`).join("+")})'`] : []), + ...(g.dropExpr ? [`select='not(${g.dropExpr})'`] : []), + ]; + const sound = + g.flash !== undefined + ? `aevalsrc=exprs='0.2*sin(2*PI*440*t)+if(between(t,${g.flash},${g.flash + 0.004}),0.7,0)':s=48000:d=${seconds}` + : `sine=frequency=440:duration=${seconds}`; + const [num, den] = String(fps).split("/").map(Number); + const gop = g.gop ?? Math.round(num / (den || 1)) * 2; await execa("ffmpeg", [ "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `${g.gen ?? "testsrc"}=size=${g.size ?? "320x180"}:rate=${fps}:duration=${seconds}`, - "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, + "-f", "lavfi", "-i", sound, + ...(vf.length ? ["-vf", vf.join(","), "-fps_mode", "passthrough"] : []), "-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", + "-g", String(gop), "-keyint_min", String(gop), "-sc_threshold", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "64k", "-shortest", ...(g.offset ? ["-output_ts_offset", String(g.offset)] : []), file, @@ -163,11 +208,18 @@ const SETTINGS: SavedVideoCompactionSettings = { dropOriginal: "after-verify", }; +// SVT-AV1's own parameters, dropped where x264 takes its place. +function stripSvt(args: string[]): void { + const j = args.indexOf("-svtav1-params"); + if (j >= 0) args.splice(j, 2); +} + // x264 in SVT-AV1's place: the same seek, end, frame-rate handling and clock. async function x264Chunk(o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string }, crf = 18, defect?: string): Promise<void> { const args = encodeChunkArgs(o.src, o.chunk, o.settings, o.out); const i = args.indexOf("libsvtav1"); args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", String(crf)); + stripSvt(args); if (defect) { const v = args.indexOf("-vf"); if (v >= 0) args[v + 1] = `${args[v + 1]},${defect}`; @@ -295,6 +347,7 @@ test("probe 1: a short chunk is caught by counting what the encoder wrote", { sk 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)); + stripSvt(args); await execa("ffmpeg", args); }, }), @@ -488,23 +541,92 @@ test("the source is hashed fresh: one that disagrees with its recorded sha256 is }); }); -test("a failed verification leaves the original active and untouched, the re-encode removed, the reason recorded", { skip: NO_TOOLS }, async () => { +test("a failed verification leaves the original active and untouched, KEEPS the encode, records every check; a reverify needs no encode", { skip: NO_TOOLS }, async () => { await withVideo({}, async (fx) => { const before = await fx.pointerText(); const log = logger(); - const r = await run(fx, flowDeps({ score: async () => 42 }), SETTINGS, log.onLog); + // Two checks fail (the excerpts, the window cuts): both are listed, and the + // checks after them still ran and said what they found. + const r = await run(fx, flowDeps({ score: async () => 42, cutCompare: async () => ({ ssim: 0.5, earlier: 0.4, later: 0.4 }) }), SETTINGS, log.onLog); assert.equal(r.status, "failed"); - assert.match((r as { reason: string }).reason, /verification failed: VMAF 42\.00 mean/); + assert.match((r as { reason: string }).reason, /verification failed: VMAF 42\.00 mean.*; a window cut at/); 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"]); + const scratch = path.join(fx.storeDir, ".compact-scratch"); + const kept = (await readdir(scratch)).sort(); + assert.deepEqual(kept, ["chunk-0000.mp4", "chunk-0001.mp4", "chunk-0002.mp4", "chunks.txt", "failed-copy.mp4", "failed.json", "state.json"]); assert.deepEqual((await readdir(fx.storeDir)).sort(), [".compact-scratch", ORIGINAL]); - assert.ok(log.lines.some((l) => /NOT compacted .*The original stays the active copy, untouched/.test(l))); + const failed = JSON.parse(await readFile(path.join(scratch, "failed.json"), "utf8")); + // The excerpts, and each of the three window cuts. + assert.equal(failed.failures.length, 4, JSON.stringify(failed.failures)); + assert.ok(/^VMAF/.test(failed.failures[0]) && failed.failures.slice(1).every((f: string) => /^a window cut at/.test(f)), JSON.stringify(failed.failures)); + assert.equal(failed.checks.audio, "identical", "the audio check ran and passed though another failed"); + assert.ok(failed.checks.timestamps && failed.checks.timestamps.over === 0, JSON.stringify(failed.checks.timestamps)); + assert.ok(failed.checks.wholeFile && failed.checks.chunkMeans, "the whole-file comparison ran too"); + assert.equal(failed.kept.chunks, 3); + assert.equal(failed.kept.copy, "failed-copy.mp4"); + assert.ok(log.lines.some((l) => /NOT compacted .*The original stays the active copy, untouched\. The encode is KEPT/.test(l)), log.lines.join("\n")); + // The dry run says a kept encode exists, its size, and what to ask. const plan = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], belowThreshold: true, deps: flowDeps() }); assert.equal(plan.items[0].compact, false); - assert.match(plan.items[0].reason!, /last compaction failed its checks .*retryFailed/); - const again = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], retryFailed: true, belowThreshold: true, deps: flowDeps() }); - assert.equal(again.items[0].compact, true); + assert.match(plan.items[0].reason!, /last compaction failed its checks .*a failed encode is kept \(3 chunk\(s\) and the joined copy, .*"reverify": true checks it again without encoding/); + assert.equal(plan.items[0].keptFailedEncode?.chunks, 3); + assert.match(plan.lines.at(-1)!, /1 kept failed encode\(s\) hold/); + const rows = await listKeptFailedEncodes(fx.paths); + assert.equal(rows.length, 1); + assert.equal(rows[0].kept?.chunks, 3); + // A re-verify with the checks passing: nothing encoded, compacted. + const re = await planCompaction({ paths: fx.paths, settings: SETTINGS, items: [{ slug: "kick", id: "v1" }], reverify: true, belowThreshold: true, deps: flowDeps() }); + assert.equal(re.items[0].compact, true); + assert.match(re.items[0].line, /RE-VERIFIES the kept failed encode \(3 chunk\(s\)/); + let encoded = 0; + const log2 = logger(); + const r2 = await run(fx, flowDeps({ encodeChunk: async (o) => { encoded += 1; await x264Chunk(o); } }), { ...SETTINGS, dropOriginal: "keep" }, log2.onLog, { reverify: true }); + assert.equal(r2.status, "compacted", log2.lines.join("\n")); + assert.equal(encoded, 0); + assert.ok(log2.lines.some((l) => /re-verifying the kept encode .*nothing encoded again/.test(l)), log2.lines.join("\n")); + await assert.rejects(stat(scratch), "a success removes the scratch"); + }); +}); + +test("a chunk whose own content failed is the only one a reverify encodes again; retryFailed encodes all; clear removes", { skip: NO_TOOLS }, async () => { + await withVideo({}, async (fx) => { + // Chunk 1 comes out short twice: a verdict on that chunk. + const r = await run( + fx, + flowDeps({ + encodeChunk: async (o) => { + if (o.chunk.index !== 1) return x264Chunk(o); + 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)); + stripSvt(args); + await execa("ffmpeg", args); + }, + }), + ); + assert.equal(r.status, "failed"); + const failed = JSON.parse(await readFile(path.join(fx.storeDir, ".compact-scratch", "failed.json"), "utf8")); + assert.deepEqual(failed.failedChunks, [1]); + assert.equal(failed.kept.chunks, 1); + const encoded: number[] = []; + const r2 = await run(fx, flowDeps({ encodeChunk: async (o) => { encoded.push(o.chunk.index); await x264Chunk(o); } }), { ...SETTINGS, dropOriginal: "keep" }, () => {}, { reverify: true }); + assert.equal(r2.status, "compacted"); + assert.deepEqual(encoded, [1, 2], "chunk 0 reused"); + }); + await withVideo({}, async (fx) => { + await run(fx, flowDeps({ score: async () => 42 })); + const encoded: number[] = []; + const r = await run(fx, flowDeps({ encodeChunk: async (o) => { encoded.push(o.chunk.index); await x264Chunk(o); } }), { ...SETTINGS, dropOriginal: "keep" }, () => {}, { retryFailed: true }); + assert.equal(r.status, "compacted"); + assert.deepEqual(encoded, [0, 1, 2]); + }); + await withVideo({}, async (fx) => { + await run(fx, flowDeps({ score: async () => 42 })); + const c = await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" }); + assert.equal(c.cleared, true, c.why); + await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch"))); + assert.equal((await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" })).cleared, false); }); }); @@ -872,6 +994,10 @@ test("F2: a GOOD SVT-AV1 crf-36 encode of a detailed 640x360 fixture passes ever assert.ok(w.worstTile && w.worstTile.min >= settings.wholeFileTileMin + 0.1 && w.worstTile.longestBelow === 0, JSON.stringify(w)); // The colour planes too (measured 0.991 at their lowest). assert.ok(w.chroma && w.chroma.min >= settings.wholeFileChromaMin + 0.05 && w.chroma.mean >= settings.wholeFileChromaMean + 0.02, JSON.stringify(w.chroma)); + // Every chunk against the others (review G2): recorded, none below. + const m = (await loadSavedVideo(fx.videoDir))!.compacted!.checks.chunkMeans!; + assert.ok(m && m.count >= 3 && m.worst === null && m.margin === settings.wholeFileChunkMargin, JSON.stringify(m)); + assert.equal(w.lowerRunSeconds, settings.wholeFileLowerRunSeconds); }); }); @@ -972,3 +1098,302 @@ test("E1: a degraded stretch longer than the window still fails (absolute floor, }); } }); + +// THE SOURCE'S TIMESTAMPS (review, the first real run). A live recording drops +// frames; the copy keeps them as gaps and stays on the sound's clock after. +async function ptsOf(file: string): Promise<number[]> { + const r = await execa("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time", "-of", "csv=p=0", file]); + return String(r.stdout).split("\n").map(Number).filter(Number.isFinite).sort((a, b) => a - b); +} +// The brightest frame's time (the white flash). +async function flashAt(file: string): Promise<number> { + const r = await execa("ffprobe", [ + "-v", "error", "-f", "lavfi", "-i", `movie=${file.replace(/([:,'\\])/g, "\\$1")},signalstats`, + "-show_entries", "frame=pts_time:frame_tags=lavfi.signalstats.YAVG", "-of", "csv=p=0", + ]); + let best = -1; + let at = NaN; + for (const line of String(r.stdout).split("\n")) { + const [t, y] = line.split(",").map(Number); + if (Number.isFinite(y) && y > best) { + best = y; + at = t; + } + } + return at; +} +// The click's time in the sound: the first sample above 0.5. +async function clickAt(file: string): Promise<number> { + const start = Number(String((await execa("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", file])).stdout).trim()) || 0; + const r = await execa("ffmpeg", ["-nostdin", "-v", "error", "-i", file, "-map", "0:a:0", "-ac", "1", "-ar", "48000", "-f", "f32le", "-"], { encoding: "buffer" }); + const b = Buffer.from(r.stdout as unknown as Uint8Array); + for (let i = 0; i + 4 <= b.length; i += 4) if (b.readFloatLE(i) > 0.5) return start + i / 4 / 48000; + return NaN; +} + +// 60 fps, 10 s; 31 frames (ODD: the time grid and the index grid part after +// it) dropped at 5 s; keyframes every 45 frames (some at odd indexes); a +// flash and a click at 7 s. +const GAPPED: Gen = { seconds: 10, fps: 60, gop: 45, drop: [[300, 330]], flash: 7 }; + +test("a live recording's dropped frames: the copy keeps them as gaps, every frame at its source time, the picture on the sound after the gap", { skip: NO_TOOLS }, async () => { + await withVideo({ gen: GAPPED }, 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" }, log.onLog); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const p = (await loadSavedVideo(fx.videoDir))!; + const c = p.compacted!.checks; + assert.equal(c.sourceGaps?.count, 1); + assert.ok(Math.abs(c.sourceGaps!.largest - 32 / 60) < 0.002, JSON.stringify(c.sourceGaps)); + assert.ok(c.timestamps && c.timestamps.over === 0 && c.timestamps.maxDeviation <= 0.0005, JSON.stringify(c.timestamps)); + assert.equal(c.timestamps!.perChunk.length, p.compacted!.chunks); + // Every copy frame is a source frame (every other one, by index), AT ITS TIME. + const src = await ptsOf(fx.source); + const copy = await ptsOf(path.join(fx.storeDir, p.file)); + assert.equal(copy.length, Math.ceil(src.length / 2)); + assert.ok(copy.every((t, i) => Math.abs(t - src[2 * i]) < 0.0005), "each kept frame keeps its source pts"); + assert.ok(copy.some((t, i) => i > 0 && t - copy[i - 1] > 0.5), "the gap is still a gap"); + // The flash and the click still meet, 2 s after the gap. + const [flash, click] = [await flashAt(path.join(fx.storeDir, p.file)), await clickAt(path.join(fx.storeDir, p.file))]; + assert.ok(Math.abs(flash - 7) < 1 / 60 + 0.001 && Math.abs(flash - click) < 1 / 30, `flash ${flash}, click ${click}`); + assert.equal(await clickAt(fx.source).then((t) => Math.abs(t - click) < 0.0001), true); + // Each chunk starts on a keyframe at an EVEN index of the file. + const state = log.lines.find((l) => /dropped frames in 1 place/.test(l)); + assert.ok(state, log.lines.join("\n")); + // The playable copy (prepare-playable's lossless remux) keeps the times. + const decision = decidePlayable({ formatName: "mov,mp4", ext: "mp4", vcodec: "av1", acodec: "aac" }); + assert.ok(decision.playable); + const remux = path.join(fx.root, "playable.mp4"); + await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", path.join(fx.storeDir, p.file), ...decision.args, remux]); + const rp = await ptsOf(remux); + assert.ok(rp.length === copy.length && rp.every((t, i) => Math.abs(t - copy[i]) < 0.0005), "the remux keeps every timestamp"); + }); +}); + +test("the copy made the OLD way (a constant rate after the gap) fails the timestamp check", { skip: NO_TOOLS }, async () => { + await withVideo({ gen: GAPPED }, async (fx) => { + const r = await run( + fx, + flowDeps({ + encodeChunk: async (o) => { + // The encode before this round: every other frame RE-TIMED onto 30 fps. + await execa("ffmpeg", [ + "-nostdin", "-v", "error", "-y", "-ss", Math.max(0, o.chunk.from - 0.001).toFixed(6), + ...(o.chunk.last ? [] : ["-to", (o.chunk.to - 0.25 / 60).toFixed(6)]), + "-i", o.src, "-map", "0:v:0", "-an", "-vf", "select='not(mod(n,2))',setpts=N/30/TB", "-r", "30", + "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18", "-video_track_timescale", "90000", "-f", "mp4", o.out, + ]); + }, + }), + ); + assert.equal(r.status, "failed"); + assert.match((r as { reason: string }).reason, /of the re-encode's frames are not at their source frame's time .* would not stay on its sound's clock/); + }); +}); + +test("a tail gap (the first real run's source) and a 59.94 fps source pass", { skip: NO_TOOLS }, async () => { + for (const gen of [{ seconds: 6, fps: 60, drop: [[350, 354]] }, { seconds: 6, fps: "60000/1001" }] as Gen[]) { + await withVideo({ gen }, async (fx) => { + const log = logger(); + const r = await run(fx, flowDeps(), { ...SETTINGS, dropOriginal: "keep" }, log.onLog); + assert.equal(r.status, "compacted", `${JSON.stringify(gen)}: ${log.lines.join("\n")}`); + const c = (await loadSavedVideo(fx.videoDir))!.compacted!.checks; + assert.equal(c.timestamps?.over, 0); + assert.equal(c.sourceGaps?.count, gen.drop ? 1 : 0); + }); + } +}); + +// Review G1: a correct copy of a source with a dropped frame was failed by a +// null-muxer line. On the DEFAULT checks, with the real encoder. +test("G1: a 59.94 fps source with one dropped frame ends compacted on the default checks", { skip: NO_SVT }, async () => { + await withVideo({ gen: { seconds: 8, fps: "60000/1001", drop: [[301, 301]] } }, async (fx) => { + const log = logger(); + const settings = { ...DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, chunkMinutes: 2 / 60, qualitySamples: 3, dropOriginal: "keep" 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 c = (await loadSavedVideo(fx.videoDir))!.compacted!.checks; + assert.equal(c.decoded, true); + assert.equal(c.sourceGaps?.count, 1); + assert.equal(c.timestamps?.over, 0); + }); +}); + +test("G1: the full decode keeps each stream's time base; only damage is fatal", { skip: NO_TOOLS }, async () => { + const d = await mkdtemp(path.join(tmpdir(), "compact-dec-")); + try { + // Frames half a tick off the nominal 1001/30000 grid: re-quantised to it, + // two land on one tick and the null muxer complains. + const f = path.join(d, "ticks.mp4"); + await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=30000/1001:d=3", + "-vf", "setpts='(N+if(eq(N\\,10)\\,0.5\\,0))*1001/30000/TB'", "-fps_mode", "passthrough", "-c:v", "libx264", "-video_track_timescale", "90000", f]); + const old = await execa("ffmpeg", ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", f, "-map", "0:v:0", "-f", "null", "-"], { reject: false }); + assert.match(String(old.stderr), /non monotonically increasing dts/, "the old invocation's complaint"); + const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" }; + assert.deepEqual(await fullDecode(paths, f), { ok: true }); + // A damaged file still fails. + const bad = path.join(d, "bad.mp4"); + const bytes = await readFile(f); + for (let i = Math.floor(bytes.length / 3); i < Math.floor(bytes.length / 3) + 4000; i += 1) bytes[i] = 0; + await writeFile(bad, bytes); + assert.equal((await fullDecode(paths, bad)).ok, false); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); + +// Review G3: a kept failed encode goes with its video's pointer; one left +// behind before this is listed as orphaned and can be cleared. +test("G3: unpersist and drop remove a kept failed encode; an orphaned one is listed and cleared", { skip: NO_TOOLS }, async () => { + for (const how of ["unpersist", "drop"] as const) { + await withVideo({}, async (fx) => { + await run(fx, flowDeps({ score: async () => 42 })); + const scratch = path.join(fx.storeDir, ".compact-scratch"); + await stat(scratch); + if (how === "unpersist") assert.equal(await unpersistSavedVideo(fx.videoDir), true); + else await dropSavedVideo(fx.videoDir); + await assert.rejects(stat(scratch), how); + const left = (await readdir(fx.storeDir).catch(() => [] as string[])).join(", "); + await assert.rejects(stat(fx.storeDir), `${how}: the store dir goes when empty (left: ${left})`); + }); + } + await withVideo({}, async (fx) => { + await run(fx, flowDeps({ score: async () => 42 })); + // A pointer removed by hand (as a release before this one left it). + await rm(savedVideoPointerPath(fx.videoDir)); + const rows = await listKeptFailedEncodes(fx.paths); + assert.equal(rows.length, 1); + assert.equal(rows[0].orphaned, true); + assert.ok((rows[0].bytes ?? 0) > 0); + const c = await clearKeptFailedEncode(fx.paths, { slug: "kick", id: "v1" }); + assert.equal(c.cleared, true, c.why); + assert.match(c.why, /orphaned/); + await assert.rejects(stat(path.join(fx.storeDir, ".compact-scratch"))); + assert.deepEqual(await listKeptFailedEncodes(fx.paths), []); + }); +}); + +// Review G4: a recording that ran at 30 fps for a stretch keeps 30 fps there. +test("G4: a 60 fps source with a 30 fps stretch keeps 30 fps throughout, each frame at its source time", { skip: NO_TOOLS }, async () => { + // Frames 120–359 at 30 fps (every odd one missing), and an odd gap later. + const gen: Gen = { seconds: 10, fps: 60, gop: 45, dropExpr: "between(n,121,359)*mod(n,2)+between(n,450,452)" }; + await withVideo({ gen }, 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" }, log.onLog); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const p = (await loadSavedVideo(fx.videoDir))!; + const copy = await ptsOf(path.join(fx.storeDir, p.file)); + const src = await ptsOf(fx.source); + assert.ok(copy.every((x) => src.some((y) => Math.abs(x - y) < 0.0005)), "every copy frame is a source frame at its time"); + for (let i = 1; i < copy.length; i += 1) { + const d = copy[i] - copy[i - 1]; + const acrossGap = copy[i - 1] <= 449 / 60 + 1e-6 && copy[i] >= 453 / 60 - 1e-6; + assert.ok(d > 1 / 30 - 0.001 && (acrossGap || d < 1 / 30 + 0.001), `${copy[i - 1]} -> ${copy[i]}`); + } + const stretch = src.filter((x) => x >= 2 && x < 6); + assert.equal(copy.filter((x) => x >= 2 && x < 6).length, stretch.length, "the 30 fps stretch keeps every frame"); + assert.equal(p.compacted!.checks.timestamps?.over, 0); + }); +}); + +test("G4: a constant 60 fps source decimates to the same frames and times as before", { skip: NO_TOOLS }, async () => { + const d = await mkdtemp(path.join(tmpdir(), "compact-cfr-")); + try { + const src = path.join(d, "src.mp4"); + await makeSource(src, { seconds: 4, fps: 60 }); + const scan = await scanVideoPackets("ffprobe", src); + const chunk = planChunks(scan, 60, 30, 60, { minStep: keepMinStep(30, 60) })[0]; + const s = { preset: 8, crf: 36, gopSeconds: 5, pixFmt: "yuv420p", fps: 30, sourceFps: 60, formatStart: 0 }; + const hashes: string[] = []; + for (const label of ["previous", "now"]) { + const out = path.join(d, `${label}.mp4`); + const args = encodeChunkArgs(src, label === "now" ? chunk : { ...chunk, select: undefined }, s, out); + const i = args.indexOf("libsvtav1"); + args.splice(i - 1, 6, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18"); + stripSvt(args); + if (label === "previous") assert.ok(args.includes("select='not(mod(n,2))',setpts=PTS-STARTPTS"), args.join(" ")); + await execa("ffmpeg", args); + const md = await execa("ffmpeg", ["-v", "error", "-i", out, "-map", "0:v", "-f", "framemd5", "-"]); + hashes.push(String(md.stdout).split("\n").filter((l) => l && !l.startsWith("#")).join("\n")); + } + assert.equal(hashes[1], hashes[0], "the same frames at the same times (framemd5 carries both)"); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); + +// Review H1: a source whose timestamps are rounded to the millisecond (a +// Matroska recording: steps of 16 and 17 ms) keeps exactly every other frame, +// with a 67 ms gap and with a choppy pattern too; every timing check passes. +test("H1: ms-rounded 60 fps sources (plain, a 67 ms gap, choppy) compact with every frame the rule keeps", { skip: NO_TOOLS }, async () => { + for (const gen of [ + { seconds: 8, fps: 60, ext: "mkv" }, + { seconds: 8, fps: 60, ext: "mkv", drop: [[240, 242]] }, + { seconds: 8, fps: 60, ext: "mkv", dropExpr: "eq(mod(n,7),3)*gte(n,150)+eq(mod(n,11),5)" }, + ] as Gen[]) { + await withVideo({ gen }, 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" }, log.onLog); + assert.equal(r.status, "compacted", `${JSON.stringify(gen)}: ${log.lines.join("\n")}`); + const p = (await loadSavedVideo(fx.videoDir))!; + const src = await ptsOf(fx.source); + const mask = keptSourceFrames(Float64Array.from(src), keepMinStep(30, 60)); + const want = src.filter((_, i) => mask[i]); + const copy = await ptsOf(path.join(fx.storeDir, p.file)); + assert.equal(copy.length, want.length, JSON.stringify(gen)); + assert.ok(copy.every((t, i) => Math.abs(t - want[i]) < 0.0005), `${JSON.stringify(gen)}: the copy holds the frames the rule keeps`); + if (!gen.drop && !gen.dropExpr) assert.deepEqual(want, src.filter((_, i) => i % 2 === 0), "plain: exactly every other frame"); + assert.equal(p.compacted!.checks.timestamps?.over, 0); + }); + } +}); + +// Review H3: a very choppy source (a frame dropped every 17) has no window +// without a gap: the cuts are SKIPPED and say so; a skipped check is never +// counted as passed, so the original is not dropped after it. +test("H3: on a very choppy source the window cuts are skipped and named, and after-verify does not drop", { skip: NO_TOOLS }, async () => { + await withVideo({ gen: { seconds: 10, fps: 60, dropExpr: "eq(mod(n,17),0)*gt(n,0)" } }, async (fx) => { + const log = logger(); + const r = await run(fx, flowDeps({ score: undefined, cutCompare: undefined, hasVmaf: undefined, encodeChunk: (o) => x264Chunk(o, 12) }), SETTINGS, log.onLog); + assert.equal(r.status, "compacted", log.lines.join("\n")); + const p = (await loadSavedVideo(fx.videoDir))!; + const c = p.compacted!.checks; + assert.ok(c.skipped && c.skipped.some((x) => /window cut/.test(x)), JSON.stringify(c.skipped)); + assert.ok(log.lines.some((l) => /SKIPPED/.test(l)), log.lines.join("\n")); + assert.equal((r as { dropped: boolean }).dropped, false); + assert.ok(log.lines.some((l) => /skipped .* does not drop/.test(l)), log.lines.join("\n")); + }); +}); + +// Review H4: the video pass decodes 0:v:0 alone; audio damage the copy does +// not share with its source is fatal, damage it carries over from it is not. +test("H4: the full decode — video alone, then the audio against the source's own", { skip: NO_TOOLS }, async () => { + const d = await mkdtemp(path.join(tmpdir(), "compact-aac-")); + try { + const v = path.join(d, "v.mp4"); + const a = path.join(d, "a.aac"); + await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=30:d=4", "-c:v", "libx264", "-preset", "ultrafast", v]); + await execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=4", "-c:a", "aac", "-b:a", "64k", a]); + const bytes = await readFile(a); + for (let i = Math.floor(bytes.length / 2); i < Math.floor(bytes.length / 2) + 600; i += 1) bytes[i] ^= 0x5a; + const aBad = path.join(d, "abad.aac"); + await writeFile(aBad, bytes); + const mux = async (out: string, audio: string) => execa("ffmpeg", ["-nostdin", "-v", "error", "-y", "-i", v, "-i", audio, "-map", "0:v", "-map", "1:a", "-c", "copy", out]); + const clean = path.join(d, "clean.mp4"); + const damaged = path.join(d, "damaged.mp4"); + await mux(clean, a); + await mux(damaged, aBad); + const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe", monorepoRoot: "" }; + // The copy's audio is damaged and its source's is not: fatal. + const r1 = await fullDecode(paths, damaged, undefined, clean); + assert.equal(r1.ok, false, JSON.stringify(r1)); + assert.match(r1.why!, /audio/); + // The same damage in the source (the audio is copied packet for packet): a note. + const r2 = await fullDecode(paths, damaged, undefined, damaged); + assert.equal(r2.ok, true, JSON.stringify(r2)); + assert.ok(r2.notes?.some((x) => /the source's own audio/.test(x)), JSON.stringify(r2.notes)); + assert.deepEqual(await fullDecode(paths, clean, undefined, clean), { ok: true }); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts @@ -100,8 +100,17 @@ import { audioPacketsHash, compareCuts, compareWholeFile, + cliTimelineStart, + compareCopyPts, concatList, countVideoFrames, + expectedCopyPts, + keepMinStep, + keepSelect, + nominalFps, + sourceGaps, + wholeRatio, + type SourceGaps, cutIsOffset, encodeChunkArgs, ffmpegHas, @@ -141,7 +150,14 @@ const CUT_SAMPLES = 3; // 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; +// A failed copy kept for a re-verify: in the scratch, never the active copy. +export const FAILED_COPY_BASENAME = "failed-copy"; +// The copy keeps the source's timestamps; a Matroska copy rounds them to the +// millisecond (half of one at most), an mp4 at 90 kHz keeps them exactly. +export const PTS_TOLERANCE_SECONDS = 0.001; +// 3: the source's timestamps kept (a chunk encoded before is not reused). +// 5: the kept frames by ONE constant rule (review H1); its step saved. +const STATE_VERSION = 5; export type Presence = { onPlatform: boolean; availability: Availability | null; why: string }; @@ -160,13 +176,18 @@ export type CompactDeps = { encodeChunk?: (o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string; signal?: AbortSignal }) => Promise<void>; countFrames?: (file: string) => Promise<number>; mux?: (o: { list: string; src: string; probe: SourceProbe; out: string; signal?: AbortSignal }) => Promise<void>; - fullDecode?: (file: string, signal?: AbortSignal) => Promise<{ ok: boolean; why?: string }>; + // `reference`: the source, whose own audio decode excuses audio damage the + // copy carries over packet for packet. + fullDecode?: (file: string, signal?: AbortSignal, reference?: string) => Promise<{ ok: boolean; why?: string; notes?: string[] }>; audioHash?: (file: string, signal?: AbortSignal) => Promise<AudioHash>; inventory?: (file: string, skipIndex: number) => Promise<string[]>; wholeFile?: (o: Parameters<typeof compareWholeFile>[1]) => Promise<WholeFileComparison>; hasVmaf?: () => Promise<boolean>; - score?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; sourceFps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise<number>; - cutCompare?: (o: { compacted: string; source: string; at: number; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<CutComparison>; + // `at` the copy's seek time, `sourceAt` the same frame's in the source. + score?: (o: { compacted: string; source: string; at: number; sourceAt?: number; sourceSelect?: string; 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; sourceAt?: number; sourceSelect?: string; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise<CutComparison>; + // Where ffmpeg's command line starts a file's timeline (cliTimelineStart). + timelineStart?: (file: string, firstVideoPts: number) => Promise<number>; measureClock?: (o: { videoDir: string; source: string; container: string; sourceBytes: number; targetBytes: number; transcribedAt: string | null; extra: number[]; signal?: AbortSignal }) => Promise<RecordingClock>; sha256?: (file: string, signal?: AbortSignal) => Promise<string>; encoderBanner?: () => Promise<string>; @@ -218,11 +239,12 @@ function resolveDeps(paths: Paths, settings: SavedVideoCompactionSettings, deps: { estimateMB: 300, nice: true, ...(o.signal ? { signal: o.signal } : {}) }, ); }), - fullDecode: deps.fullDecode ?? ((f, s) => fullDecode(paths, f, s)), + fullDecode: deps.fullDecode ?? ((f, s, ref) => fullDecode(paths, f, s, ref)), 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")), + timelineStart: deps.timelineStart ?? ((f, first) => cliTimelineStart(paths.ffmpegBin, f, first)), score: deps.score ?? ((o) => scoreExcerpt(paths, o)), cutCompare: deps.cutCompare ?? ((o) => compareCuts(paths, o)), measureClock: @@ -266,6 +288,8 @@ export type CompactPlanItem = { estimate?: CompactionEstimate; needsFreeBytes?: number; freeBytes?: number; + // A failed encode kept in the video's scratch (never active): its size. + keptFailedEncode?: KeptFailedEncode; line: string; }; @@ -302,12 +326,25 @@ async function videoPlatform(videoDir: string, config: ChannelConfig): Promise<s return channelPlatform(config); } -async function lastFailure(dir: string): Promise<{ at: string; reason: string; settingsKey: string } | null> { +export type KeptFailedEncode = { chunks: number; bytes: number; copy: string | null }; +export type LastFailure = { at: string; reason: string; settingsKey: string; failedChunks: number[]; kept: KeptFailedEncode | null }; + +async function lastFailure(dir: string): Promise<LastFailure | null> { const read = await readJsonFile(path.join(dir, COMPACTION_SCRATCH_DIRNAME, FAILED_FILENAME)); if (!read.ok || !read.value || typeof read.value !== "object") return null; const r = read.value as Record<string, unknown>; + const k = r.kept && typeof r.kept === "object" ? (r.kept as Record<string, unknown>) : null; return typeof r.reason === "string" - ? { at: String(r.at ?? ""), reason: r.reason, settingsKey: String(r.settingsKey ?? "") } + ? { + at: String(r.at ?? ""), + reason: r.reason, + settingsKey: String(r.settingsKey ?? ""), + failedChunks: Array.isArray(r.failedChunks) ? r.failedChunks.filter((x): x is number => typeof x === "number") : [], + kept: + k && typeof k.chunks === "number" && k.chunks > 0 + ? { chunks: k.chunks, bytes: typeof k.bytes === "number" ? k.bytes : 0, copy: typeof k.copy === "string" ? k.copy : null } + : null, + } : null; } @@ -321,6 +358,7 @@ export async function planOne(opts: { mode: "explicit" | "select"; settings: SavedVideoCompactionSettings; retryFailed?: boolean; + reverify?: boolean; belowThreshold?: boolean; deps: Required<CompactDeps>; }): Promise<CompactPlanItem & { pointer?: SavedVideoPointer; probe?: SourceProbe | null; videoDir: string }> { @@ -369,18 +407,26 @@ export async function planOne(opts: { return { ...skip(reason, { ...facts, line: brief ? `${brief} —` : "", ...(decision.belowThreshold ? { belowThreshold: decision.belowThreshold } : {}) }), pointer, probe }; } const failed = await lastFailure(pointer.dir); - if (failed && failed.settingsKey === settingsKeyOf(settings, fps) && !opts.retryFailed) { + const sameEncode = !!failed && failed.settingsKey === settingsKeyOf(settings, fps); + const keptLine = (k: KeptFailedEncode) => + `a failed encode is kept (${k.chunks} chunk(s)${k.copy ? " and the joined copy" : ""}, ${formatBytes(k.bytes)}, never active)`; + if (failed && sameEncode && !opts.retryFailed && !opts.reverify) { return { - ...skip(`its last compaction failed its checks on ${failed.at.slice(0, 10)}: ${failed.reason}; "retryFailed": true runs it again`, { - ...facts, - line: `${brief} —`, - }), + ...skip( + `its last compaction failed its checks on ${failed.at.slice(0, 10)}: ${failed.reason}; ` + + (failed.kept + ? `${keptLine(failed.kept)}: "reverify": true checks it again without encoding (${failed.failedChunks.length ? `chunk(s) ${failed.failedChunks.join(", ")} encoded again` : "nothing encoded again"}), "retryFailed": true encodes it all again, kept-failed-encodes {"clear": …} removes it` + : `"retryFailed": true runs it again`), + { ...facts, line: `${brief} —`, ...(failed.kept ? { keptFailedEncode: failed.kept } : {}) }, + ), pointer, probe, }; } + const reusing = !!(failed && sameEncode && opts.reverify && !opts.retryFailed && failed.kept); const freeBytes = await deps.freeBytes(pointer.dir); - const needsFreeBytes = compactionFreeNeeded(estimate!.bytes[1], 0); + // A re-verify reuses the kept chunks: only what it encodes again needs room. + const needsFreeBytes = compactionFreeNeeded(estimate!.bytes[1], reusing ? failed!.kept!.bytes : 0); const pct = (b: number) => Math.round((1 - b / pointer.bytes) * 100); const gone = presence.onPlatform ? "" : `; not known to be on its platform (${presence.why}): its original waits for a review`; const room = freeBytes >= needsFreeBytes; @@ -390,6 +436,8 @@ export async function planOne(opts: { `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}` : "") + + (reusing ? `; RE-VERIFIES the kept failed encode (${failed!.kept!.chunks} chunk(s), ${formatBytes(failed!.kept!.bytes)}): ${failed!.failedChunks.length ? `chunk(s) ${failed!.failedChunks.join(", ")} encoded again` : "nothing encoded again"}` : "") + + (failed && !reusing && failed.kept ? `; its ${keptLine(failed.kept)} is removed first` : "") + gone; return { ...base, @@ -409,6 +457,7 @@ export async function planOne(opts: { estimate: estimate!, needsFreeBytes, freeBytes, + ...(failed?.kept ? { keptFailedEncode: failed.kept } : {}), line, pointer, probe, @@ -424,6 +473,7 @@ export async function planCompaction(opts: { select?: boolean; slugs?: string[]; retryFailed?: boolean; + reverify?: boolean; belowThreshold?: boolean; deps?: CompactDeps; }): Promise<CompactPlan> { @@ -444,6 +494,7 @@ export async function planCompaction(opts: { mode, settings: opts.settings, retryFailed: opts.retryFailed, + reverify: opts.reverify, belowThreshold: opts.belowThreshold, deps, }); @@ -461,10 +512,13 @@ export async function planCompaction(opts: { will.reduce((n, i) => n + (i.estimate?.hours[1] ?? 0), 0), ] as [number, number], }; + const kept = out.filter((i) => i.keptFailedEncode); + const keptBytes = kept.reduce((n, i) => n + (i.keptFailedEncode?.bytes ?? 0), 0); const lines = [ ...out.map((i) => i.line), `total: ${will.length} container(s), ${formatBytes(totals.bytes)} → est. ${formatBytes(totals.estimate[0])}–${formatBytes(totals.estimate[1])}, ` + - `est. ${hoursRange(totals.hours)} of encoding; ${out.length - will.length} skipped`, + `est. ${hoursRange(totals.hours)} of encoding; ${out.length - will.length} skipped` + + (kept.length ? `; ${kept.length} kept failed encode(s) hold ${formatBytes(keptBytes)} of the store's disk (kept-failed-encodes)` : ""), ]; return { items: out, willCompact: will.length, totals, lines }; } @@ -473,6 +527,17 @@ export async function planCompaction(opts: { type ChunkState = ChunkPlan & { file: string; bytes?: number; done: boolean }; +// Each chunk's first frame in the copy: the chunks' expected frames, summed. +function chunkStartFrames(chunks: { expectedFrames: number }[]): number[] { + const out: number[] = []; + let at = 0; + for (const c of chunks) { + out.push(at); + at += c.expectedFrames; + } + return out; +} + type CompactState = { version: typeof STATE_VERSION; sourceFile: string; @@ -485,6 +550,15 @@ type CompactState = { sourceLastPts: number; sourceFrameStep: number; sourceMaxGap: number; + // The source's NOMINAL rate (1 / its median frame step): what the decimation + // and every comparison take, never the average a dropped frame moves. + sourceFps?: number | null; + // The recording's dropped frames (kept as gaps in the copy). + sourceGaps?: SourceGaps; + // Under a whole ratio: the step of the rule that decides which source + // frames the copy keeps (keepMinStep); the encoder's select and every check + // apply this one rule. + keepMinStep?: number; chunks: ChunkState[]; }; @@ -505,7 +579,10 @@ export type CompactOneResult = class VerifyFailure extends Error { constructor( message: string, - readonly checks: Partial<SavedVideoCompactedChecks> = {}, + readonly checks: Partial<SavedVideoCompactedChecks> & { failures?: string[] } = {}, + // Chunks whose OWN content failed (a frame count, the per-chunk + // comparison): a re-verify encodes these again and reuses the rest. + readonly failedChunks: number[] = [], ) { super(message); } @@ -541,7 +618,7 @@ export type CompactRunOptions = { }; export async function compactOne( - opts: CompactRunOptions & { item: CompactItem; mode: "explicit" | "select"; retryFailed?: boolean; belowThreshold?: boolean }, + opts: CompactRunOptions & { item: CompactItem; mode: "explicit" | "select"; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean }, ): Promise<CompactOneResult> { const log = (s: string) => opts.onLog(s.endsWith("\n") ? s : `${s}\n`); const deps = resolveDeps(opts.paths, opts.settings, opts.deps); @@ -551,6 +628,7 @@ export async function compactOne( mode: opts.mode, settings: opts.settings, retryFailed: opts.retryFailed, + reverify: opts.reverify, belowThreshold: opts.belowThreshold, deps, }); @@ -604,7 +682,7 @@ export async function sweepCompactingMarkers(paths: Paths, onLog?: (l: string) = } async function compactPlanned( - opts: CompactRunOptions & { item: CompactItem }, + opts: CompactRunOptions & { item: CompactItem; retryFailed?: boolean; reverify?: boolean }, deps: Required<CompactDeps>, planned: Awaited<ReturnType<typeof planOne>>, log: (s: string) => void, @@ -653,7 +731,29 @@ async function compactPlanned( } if (!pointer.sha256) await updateSavedVideoChecksum(videoDir, sourceSha, pointer.file); + // A KEPT FAILED ENCODE (its last run failed a check; the chunks stayed): + // "retryFailed" encodes everything again; "reverify" checks the kept + // chunks again, encoding only those whose own content failed. + const before = await lastFailure(pointer.dir); + let reencode: number[] = []; + if (before && (opts.retryFailed || before.settingsKey !== settingsKey)) { + log( + `${tag}: ${opts.retryFailed ? '"retryFailed"' : "the settings changed"}: the kept failed encode is removed; encoding from the start.`, + ); + await rm(scratch, { recursive: true, force: true }); + await mkdir(scratch, { recursive: true }); + } else if (before) { + reencode = before.failedChunks; + for (const f of [FAILED_FILENAME, `${FAILED_COPY_BASENAME}.mp4`, `${FAILED_COPY_BASENAME}.mkv`]) await rm(path.join(scratch, f), { force: true }); + log( + `${tag}: re-verifying the kept encode of ${before.at.slice(0, 10)} (it failed: ${before.reason})` + + (reencode.length ? `; chunk(s) ${reencode.join(", ")} encoded again.` : "; nothing encoded again."), + ); + } state = await loadState(stateFile); + if (state && reencode.length) { + for (const c of state.chunks) if (reencode.includes(c.index)) c.done = false; + } if ( state && (state.sourceFile !== pointer.file || state.sourceBytes !== pointer.bytes || state.settingsKey !== settingsKey || state.sourceSha256 !== sourceSha) @@ -667,7 +767,10 @@ async function compactPlanned( if (!state) { log(`${tag}: scanning ${pointer.file}'s packets (frame count, keyframes)…`); const scan = await deps.scan(src, signal); - const plan = planChunks(scan, s.chunkMinutes * 60, fps, probe.fps); + const nominal = nominalFps(scan.pts) ?? probe.fps; + const m = wholeRatio(nominal, fps); + const keep = m && nominal ? { minStep: keepMinStep(nominal / m, nominal) } : undefined; + const plan = planChunks(scan, s.chunkMinutes * 60, fps, nominal, keep); if (!plan.length) return { status: "failed", reason: "the source has no video packets" }; const n = scan.pts.length; state = { @@ -682,10 +785,19 @@ async function compactPlanned( sourceLastPts: scan.pts[n - 1], sourceFrameStep: n > 1 ? scan.pts[n - 1] - scan.pts[n - 2] : 1 / (probe.fps ?? 30), sourceMaxGap: maxGap(scan.pts), + sourceFps: nominal, + sourceGaps: sourceGaps(scan.pts), + ...(keep ? { keepMinStep: keep.minStep } : {}), 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.`); + const g = state.sourceGaps!; + log( + `${tag}: ${n} frames, ${plan.length} chunk(s) of about ${s.chunkMinutes} min, each starting on a source keyframe; ` + + (g.count + ? `the recording dropped frames in ${g.count} place(s) (${g.totalSeconds.toFixed(3)} s in all, the largest ${g.largest.toFixed(3)} s at ${g.largestAt.toFixed(1)} s): the copy keeps them as gaps.` + : "no dropped frames."), + ); } else { const done = state.chunks.filter((c) => c.done).length; log(`${tag}: resuming — ${done}/${state.chunks.length} chunk(s) already encoded.`); @@ -698,7 +810,7 @@ async function compactPlanned( gopSeconds: COMPACT_GOP_SECONDS, pixFmt: COMPACT_PIX_FMT, fps, - sourceFps: probe.fps ?? 30, + sourceFps: state.sourceFps ?? probe.fps ?? 30, formatStart: probe.formatStart, }; for (const c of state.chunks) { @@ -738,7 +850,7 @@ async function compactPlanned( if (frames === c.expectedFrames) break; await rm(part, { force: true }); if (attempt >= 2) { - throw new VerifyFailure(`chunk ${c.index} holds ${frames} frames, not the ${c.expectedFrames} expected (encoded twice)`); + throw new VerifyFailure(`chunk ${c.index} holds ${frames} frames, not the ${c.expectedFrames} expected (encoded twice)`, {}, [c.index]); } log(`${tag}: chunk ${c.index} holds ${frames} frames, not ${c.expectedFrames} — encoding it again.`); } @@ -751,7 +863,14 @@ async function compactPlanned( // ---- 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)))); + // Each chunk at its SOURCE time: its span to the next chunk's first frame. + await writeFile( + listFile, + concatList( + state.chunks.map((c) => path.join(scratch, c.file)), + state.chunks.slice(1).map((c, i) => c.from - state!.chunks[i].from), + ), + ); const ext = probe.container === "mp4" ? ".mp4" : ".mkv"; const muxed = path.join(scratch, `compacted${ext}`); await rm(muxed, { force: true }); @@ -771,6 +890,8 @@ async function compactPlanned( 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 ratioNow = wholeRatio(state.sourceFps ?? probe.fps, fps); + const copyRate = ratioNow ? (state.sourceFps ?? probe.fps ?? 0) / ratioNow : (fps ?? state.sourceFps ?? null); const original: SavedVideoAlternate = { file: pointer.file, bytes: pointer.bytes, @@ -817,7 +938,9 @@ async function compactPlanned( sha256: resultSha, vcodec: resultProbe?.vcodec ?? "av1", ...(resultProbe?.height ? { height: resultProbe.height } : {}), - ...(resultProbe?.fps ? { fps: resultProbe.fps } : {}), + // The copy's NOMINAL rate (the source's over the ratio): with the + // source's timestamps kept, ffprobe's average counts the dropped frames. + ...(copyRate ? { fps: round(copyRate, 3) } : resultProbe?.fps ? { fps: resultProbe.fps } : {}), ...(resultProbe?.seconds ? { seconds: resultProbe.seconds } : {}), frames: checks.frames[1], ...(resultProbe?.videoKbps ? { videoKbps: resultProbe.videoKbps } : {}), @@ -927,17 +1050,48 @@ async function compactPlanned( return { status: "failed", reason }; } const reason = `verification failed: ${err.message}`; - // A VERDICT: the original stays active and untouched; the output goes, and - // the reason stays beside the source for the next plan. - await rm(scratch, { recursive: true, force: true }).catch(() => {}); - await mkdir(scratch, { recursive: true }).catch(() => {}); + // A VERDICT: the original stays active and untouched. THE ENCODE IS KEPT + // (review, the first real run: a failed check deleted 7 hours of chunks): + // the chunks and the joined copy stay in the scratch, the copy renamed + // `failed-copy.*`, never active, until a person clears them or a later run + // decides — "reverify" checks them again (a fixed check needs no new + // encode; a chunk whose own content failed is encoded again), + // "retryFailed" or changed settings encode it all again. + let keptChunks = 0; + let keptBytes = 0; + let copy: string | null = null; + for (const c of state?.chunks ?? []) { + if (!c.done) continue; + keptChunks += 1; + keptBytes += c.bytes ?? 0; + } + for (const ext of [".mp4", ".mkv"]) { + const from = path.join(scratch, `compacted${ext}`); + const st = await stat(from).catch(() => null); + if (!st) continue; + copy = `${FAILED_COPY_BASENAME}${ext}`; + await rename(from, path.join(scratch, copy)).catch(() => { + copy = null; + }); + if (copy) keptBytes += st.size; + } await writeJsonAtomic(path.join(scratch, FAILED_FILENAME), { at: deps.now().toISOString(), reason: err.message, + failures: err.checks.failures ?? [err.message], settingsKey, checks: err.checks, + failedChunks: err.failedChunks, + kept: { chunks: keptChunks, bytes: keptBytes, copy }, }).catch(() => {}); - log(`${tag}: NOT compacted — ${reason}. The original stays the active copy, untouched; the re-encode was removed.`); + log( + `${tag}: NOT compacted — ${reason}. The original stays the active copy, untouched. ` + + (keptChunks + ? `The encode is KEPT in ${scratch} (${keptChunks} chunk(s)${copy ? " and the joined copy" : ""}, ${formatBytes(keptBytes)}, never active): ` + + `"reverify": true checks it again without encoding${err.failedChunks.length ? ` (chunk(s) ${err.failedChunks.join(", ")} encoded again)` : ""}; ` + + `kept-failed-encodes {"clear": {"slug", "id"}} removes it.` + : "Nothing was encoded to keep."), + ); return { status: "failed", reason }; } } @@ -952,12 +1106,6 @@ function sameProvenance(raw: Record<string, unknown>, pointer: SavedVideoPointer ); } -// 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; @@ -977,38 +1125,99 @@ async function verify(o: { }): Promise<{ checks: SavedVideoCompactedChecks; clock: RecordingClock | null }> { const { deps, tag, state, settings: s, log, signal } = o; const checks: Partial<SavedVideoCompactedChecks> = { passed: false, audio: "unknown" }; - const fail = (why: string): never => { - throw new VerifyFailure(why, checks); + // EVERY CHECK RUNS and reports its own result (review, the first real run: + // a failure recorded "audio unknown"): a failing one is listed and the next + // runs; only a copy that cannot be read at all stops the list. + const problems: string[] = []; + const failedChunks: number[] = []; + const fail = (why: string): void => { + problems.push(why); + }; + // A check that could not be made on this source: named on the record, + // never counted as passed. + const skip = (what: string): void => { + checks.skipped = [...(checks.skipped ?? []), what]; + }; + const fatal = (why: string): never => { + problems.push(why); + throw new VerifyFailure(problems.join("; "), { ...checks, failures: [...problems] }, failedChunks); + }; + const step = async (name: string, run: () => Promise<void>) => { + try { + await run(); + } catch (err) { + if (signal?.aborted || err instanceof VerifyFailure) throw err; + fail(`${name} could not run: ${(err as Error).message}`); + } }; let keep: RecordingClock | null = null; const outFps = o.fps ?? o.probe.fps ?? 30; + // The source's NOMINAL rate (its median frame step), as the encode took it. + const srcFps = state.sourceFps ?? o.probe.fps; log(`${tag}: verifying — a full decode first…`); - const dec = await deps.fullDecode(o.muxed, signal); + const dec = await deps.fullDecode(o.muxed, signal, o.src); checks.decoded = dec.ok; + // Lines the decode printed that are not damage (a null-muxer timestamp + // line, anything unrecognised): kept, never fatal. + if (dec.notes?.length) checks.decodeNotes = dec.notes; if (!dec.ok) fail(`the re-encode does not decode cleanly: ${dec.why ?? "errors"}`); - // Length, frames and gaps, from both files' packets. + // THE TIMESTAMPS, every frame (review, the first real run): the copy keeps + // the source's own — a frame the live recording dropped stays a gap — so + // each copy frame's pts must be the one its source frame had, relative to + // each file's start, within the containers' rounding. const outProbe = await deps.probe(o.muxed); - if (!outProbe?.hasVideo) fail("the re-encode does not open as a video"); + if (!outProbe?.hasVideo) fatal("the re-encode does not open as a video"); const op = outProbe!; - const outScan = await deps.scan(o.muxed, signal); + const [outScan, srcScan] = await Promise.all([deps.scan(o.muxed, signal), deps.scan(o.src, signal)]); const n = outScan.pts.length; - const outStep = n > 1 ? outScan.pts[n - 1] - outScan.pts[n - 2] : 1 / outFps; - const srcSeconds = state.sourceLastPts + state.sourceFrameStep - state.sourceFirstPts; - const outSeconds = n ? outScan.pts[n - 1] + outStep - outScan.pts[0] : 0; - const frameTol = 1 / outFps + 1e-3; - checks.seconds = [round(srcSeconds), round(outSeconds)]; - checks.secondsTolerance = round(frameTol, 4); + const ratio = wholeRatio(srcFps, o.fps); + const keepRule = state.keepMinStep ? { minStep: state.keepMinStep } : undefined; + const expectedPts = expectedCopyPts(srcScan.pts, state.chunks, ratio, o.fps && !ratio ? o.fps : null, keepRule); + // The kept frames' select for the source side of every comparison: the + // encoder's one constant rule (each comparison starts on a kept frame). + const keptSelect = (): string | undefined => (keepRule ? keepSelect(keepRule.minStep) : undefined); const expected = state.chunks.reduce((x, c) => x + c.expectedFrames, 0); checks.frames = [state.sourceFrames, n, expected]; if (n !== expected) fail(`the re-encode holds ${n} frames, not the ${expected} the source's ${state.sourceFrames} give${o.fps ? ` at ${o.fps} fps` : ""}`); - if (Math.abs(outSeconds - srcSeconds) > frameTol) { - fail(`the re-encode's video lasts ${outSeconds.toFixed(3)} s, the source's ${srcSeconds.toFixed(3)} s (more than a frame apart)`); + const expRel = expectedPts.map((t) => t - o.probe.formatStart); + const outRel = outScan.pts.map((t) => t - op.formatStart); + const ts = compareCopyPts(expRel, outRel, PTS_TOLERANCE_SECONDS, chunkStartFrames(state.chunks)); + checks.timestamps = { + frames: ts.frames, + expected: ts.expected, + tolerance: PTS_TOLERANCE_SECONDS, + maxDeviation: round(ts.maxDeviation, 6), + at: round(ts.at, 3), + over: ts.over, + perChunk: ts.perChunk.map((x) => round(x, 6)), + }; + if (ts.over > 0 || expectedPts.length !== expected) { + fail( + `${ts.over} of the re-encode's frames are not at their source frame's time (the worst ${ts.maxDeviation.toFixed(4)} s off at ${ts.at.toFixed(2)} s; ` + + `${PTS_TOLERANCE_SECONDS} s allowed) — its picture would not stay on its sound's clock`, + ); + } + // The recording's own dropped frames, recorded (and kept as gaps in the copy). + const gaps = sourceGaps(srcScan.pts); + checks.sourceGaps = { count: gaps.count, totalSeconds: round(gaps.totalSeconds, 4), largest: round(gaps.largest, 4), largestAt: round(gaps.largestAt - o.probe.formatStart, 3) }; + // THE END: the copy's last frame is the source's last kept frame. (The + // length as frames ÷ rate is NOT the source's pts span when the recording + // dropped frames: the old check failed a correct copy by a tail gap.) + const srcSeconds = state.sourceLastPts + state.sourceFrameStep - state.sourceFirstPts; + const outSeconds = n ? outScan.pts[n - 1] + 1 / outFps - outScan.pts[0] : 0; + checks.seconds = [round(srcSeconds), round(outSeconds)]; + checks.secondsTolerance = round(1 / outFps + PTS_TOLERANCE_SECONDS, 4); + const lastExp = expRel.length ? expRel[expRel.length - 1] : 0; + const lastOut = n ? outRel[n - 1] : 0; + if (n && Math.abs(lastOut - lastExp) > PTS_TOLERANCE_SECONDS) { + fail(`the re-encode's last frame is at ${lastOut.toFixed(3)} s, the source's last kept frame at ${lastExp.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)`); + const expGap = maxGap(expectedPts); + if (gap > Math.max(1.5 / outFps, expGap + PTS_TOLERANCE_SECONDS)) { + fail(`the re-encode has a ${gap.toFixed(3)} s gap between frames (the source's kept frames' largest is ${expGap.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). @@ -1024,38 +1233,87 @@ async function verify(o: { if (n && Math.abs(relFirst(outScan.pts[0], op) - relFirst(state.sourceFirstPts, o.probe)) > 0.5 / outFps + 1e-3) { fail(`the re-encode's first frame is ${relFirst(outScan.pts[0], op).toFixed(3)} s into it, the source's ${relFirst(state.sourceFirstPts, o.probe).toFixed(3)} s`); } - log(`${tag}: ${n}/${expected} frames, ${outSeconds.toFixed(3)} s against ${srcSeconds.toFixed(3)} s, largest gap ${gap.toFixed(3)} s.`); - - // The audio, copied: identical packets, identical timing. - const [a, b] = await Promise.all([deps.audioHash(o.src, signal), deps.audioHash(o.muxed, signal)]); - checks.audioHash = b.data; - const sameTiming = sameAudioTiming(a, b); - if (a.packets !== b.packets || a.data !== b.data || !sameTiming) { - checks.audio = "different"; - fail( - `the audio is not the source's packet for packet (${a.packets} → ${b.packets} packets` + - `${a.data !== b.data ? ", different bytes" : ""}${!sameTiming ? ", different timing" : ""})`, - ); - } - checks.audio = "identical"; - log(`${tag}: audio identical (${b.packets} packets).`); + log( + `${tag}: ${n}/${expected} frames, each at its source frame's time (worst ${ts.maxDeviation.toFixed(4)} s off); ` + + `the recording dropped frames in ${gaps.count} place(s) (${gaps.totalSeconds.toFixed(3)} s, largest ${gaps.largest.toFixed(3)} s), kept as gaps.`, + ); + // An excerpt or a cut starts ON a kept frame and holds no gap (after a + // dropped frame the two decimations would pair other frames). Each file is + // seeked a quarter source frame before THAT FRAME IN ITS OWN command-line + // timeline: ffmpeg starts an mpegts's from its video, our mp4 copy's from + // its container start, and one time for both landed a frame apart. + const [copyT0, srcT0] = n && srcScan.pts.length + ? await Promise.all([deps.timelineStart(o.muxed, outScan.pts[0]), deps.timelineStart(o.src, srcScan.pts[0])]) + : [op.formatStart, o.probe.formatStart]; + const quarter = 0.25 / (srcFps ?? outFps); + const seekPair = (rel: number) => ({ + at: Number(Math.max(0, rel + op.formatStart - copyT0 - quarter).toFixed(4)), + sourceAt: Number(Math.max(0, rel + o.probe.formatStart - srcT0 - quarter).toFixed(4)), + }); + // `regular`: no step in [start, start + seconds] off one copy frame by + // more than a tenth — a window the evidence cutter (an x264 re-encode on its + // own time base) carries frame for frame. A cut needs one (review H3); an + // excerpt does not (it is no re-encode, and both sides keep frames by the + // same rule across any gap). + const copyStep = 1 / (state.keepMinStep && srcFps ? srcFps / (ratio ?? 1) : outFps); + const irregularAt = (j: number) => Math.abs(expRel[j] - expRel[j - 1] - copyStep) > copyStep / 10; + const snap = (t: number, seconds: number, regular = false): { rel: number; regular: boolean } => { + const rel = expRel; + if (!rel.length) return { rel: t, regular: true }; + let lo = 0; + let hi = rel.length - 1; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (rel[mid] < t) lo = mid + 1; + else hi = mid; + } + let i = lo; + if (!regular) return { rel: rel[i], regular: true }; + for (let j = i + 1; j < rel.length && rel[j] <= rel[i] + seconds + copyStep; j += 1) { + if (irregularAt(j)) i = j; + } + const ok = rel[i] + seconds <= rel[rel.length - 1]; + return { rel: rel[i], regular: ok }; + }; + + // The audio, copied: identical packets AT IDENTICAL TIMES — with the + // timestamps above, the picture against the sound at every frame. + await step("the audio comparison", async () => { + const [a, b] = await Promise.all([deps.audioHash(o.src, signal), deps.audioHash(o.muxed, signal)]); + checks.audioHash = b.data; + const sameTiming = sameAudioTiming(a, b); + if (a.packets !== b.packets || a.data !== b.data || !sameTiming) { + checks.audio = "different"; + fail( + `the audio is not the source's packet for packet (${a.packets} → ${b.packets} packets` + + `${a.data !== b.data ? ", different bytes" : ""}${!sameTiming ? ", different timing" : ""})`, + ); + } else { + checks.audio = "identical"; + log(`${tag}: audio identical (${b.packets} packets, at the source's times).`); + } + }); // 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"})`); - } + await step("the stream inventory", async () => { + const srcInv = await deps.inventory(o.src, o.probe.mainVideoIndex); + const outInv = await deps.inventory(o.muxed, op.mainVideoIndex); + checks.streams = { source: srcInv, result: outInv }; + if (JSON.stringify(srcInv) !== JSON.stringify(outInv)) { + fail(`the re-encode does not carry every stream of the source (source: ${srcInv.join(", ") || "none"}; copy: ${outInv.join(", ") || "none"})`); + } + }); // THE WHOLE FILE, compared EVERY FRAME, whole and tile by tile. + await step("the whole-file comparison", async () => { log(`${tag}: comparing the whole file, every frame, at ${WHOLE_FILE_WIDTH} px in a ${WHOLE_FILE_GRID}×${WHOLE_FILE_GRID} grid…`); const cmp = await deps.wholeFile({ compacted: o.muxed, source: o.src, scratchDir: o.scratch, fps: o.fps, - sourceFps: o.probe.fps, + sourceFps: srcFps, + ...(keepRule ? { sourceSelect: keptSelect() } : {}), sourceWidth: o.probe.width, sourceHeight: o.probe.height, tileFloor: s.wholeFileTileMin, @@ -1072,6 +1330,10 @@ async function verify(o: { chromaMinFrame: s.wholeFileChromaMin, chromaMeanFloor: s.wholeFileChromaMean, windowFrames: Math.round(s.wholeFileWindowSeconds * outFps), + lowerRunFrames: Math.round(s.wholeFileLowerRunSeconds * outFps), + chunkStarts: chunkStartFrames(state.chunks), + chunkSigmaK: s.wholeFileChunkSigmaK, + chunkMargin: s.wholeFileChunkMargin, }); checks.wholeFile = { fps: outFps, @@ -1088,6 +1350,9 @@ async function verify(o: { windowSeconds: s.wholeFileWindowSeconds, worstLocalMargin: round(v.worstLocalMargin, 4), worstLocalAt: round(v.worstLocalAt / outFps, 3), + lowerRunSeconds: s.wholeFileLowerRunSeconds, + ...(v.lowerState ? { lowerState: { floor: round(v.lowerState.floor, 4), share: round(v.lowerState.share, 3), runs: v.lowerState.runs } } : {}), + ...(v.lowerStateRefused ? { lowerStateRefused: v.lowerStateRefused } : {}), relativeFloor: round(v.relativeFloor, 4), chroma: { mean: round(v.chroma.mean, 4), @@ -1112,34 +1377,57 @@ async function verify(o: { } : {}), }; + if (v.chunks) { + checks.chunkMeans = { + count: v.chunks.count, + sigmaK: v.chunks.sigmaK, + margin: v.chunks.margin, + worst: v.chunks.worst + ? { + chunk: v.chunks.worst.index, + plane: v.chunks.worst.plane, + mean: round(v.chunks.worst.mean, 4), + centre: round(v.chunks.worst.centre, 4), + floor: round(v.chunks.worst.floor, 4), + ...(v.chunks.worst.joinAt !== undefined ? { joinAt: round(v.chunks.worst.joinAt / outFps, 3) } : {}), + } + : null, + exempt: v.chunks.exempt.map((x) => ({ chunk: x.index, plane: x.plane, why: x.why })), + }; + } + if (v.chunks?.worst) failedChunks.push(v.chunks.worst.index); if (!v.ok) fail(`the whole-file comparison: ${v.why}`); log( `${tag}: whole file SSIM ${v.mean.toFixed(4)} mean over ${cmp.frames.length} frames, lowest ${v.min.toFixed(4)} at ${(v.minAt / outFps).toFixed(2)} s; ` + `colour ${v.chroma.mean.toFixed(4)} mean, lowest ${v.chroma.min.toFixed(4)} (${v.chroma.plane}); ` + `worst tile ${v.worstTile ? `${v.worstTile.col},${v.worstTile.row} at ${v.worstTile.min.toFixed(3)} (${v.worstTile.longestBelow} frame(s) below ${s.wholeFileTileMin})` : "none"}.`, ); + }); // Quality on excerpts: spread through the file, ACROSS EVERY CHUNK JOIN and // inside every chunk (the count grows with the chunks). - const metric: "vmaf" | "ssim" = (await deps.hasVmaf().catch(() => false)) ? "vmaf" : "ssim"; const relStart = state.sourceFirstPts - o.probe.formatStart; + await step("the excerpt scores", async () => { + const metric: "vmaf" | "ssim" = (await deps.hasVmaf().catch(() => false)) ? "vmaf" : "ssim"; 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))); + const times = new Set<number>(sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps).map((t) => snap(t + relStart, EXCERPT_SECONDS).rel)); // …and at least one every wholeFileWindowSeconds across the whole file: a // degraded stretch longer than the local floor's window looks steady to // that floor, and always holds one of these. - for (let t = s.wholeFileWindowSeconds / 2; t < lastAt; t += s.wholeFileWindowSeconds) times.add(onGrid(t + relStart, outFps)); + for (let t = s.wholeFileWindowSeconds / 2; t < lastAt; t += s.wholeFileWindowSeconds) times.add(snap(t + relStart, EXCERPT_SECONDS).rel); 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)); + if (c.index > 0) times.add(snap(Math.min(lastAt, Math.max(0, from - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS).rel); + times.add(snap(Math.min(lastAt, Math.max(0, (from + to) / 2 - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS).rel); } const scores: number[] = []; - for (const at of [...times].sort((x, y) => x - y)) { + for (const rel of [...times].sort((x, y) => x - y)) { + const { at, sourceAt } = seekPair(rel); + const sourceSelect = keptSelect(); if (signal?.aborted) throw new Error("cancelled"); scores.push( - await deps.score({ compacted: o.muxed, source: o.src, at, seconds: EXCERPT_SECONDS, fps: o.fps, sourceFps: o.probe.fps, metric, scratchDir: o.scratch, signal }), + await deps.score({ compacted: o.muxed, source: o.src, at, sourceAt, ...(sourceSelect ? { sourceSelect } : {}), seconds: EXCERPT_SECONDS, fps: o.fps, sourceFps: srcFps, metric, scratchDir: o.scratch, signal }), ); } const mean = scores.reduce((x, y) => x + y, 0) / Math.max(1, scores.length); @@ -1150,13 +1438,23 @@ async function verify(o: { fail(`${metric.toUpperCase()} ${mean.toFixed(2)} mean, ${min.toFixed(2)} at its worst excerpt (needs ${minMean} and ${minSample})`); } log(`${tag}: ${metric.toUpperCase()} ${mean.toFixed(2)} mean over ${scores.length} excerpts (every join and every chunk), worst ${min.toFixed(2)}.`); + }); // Real windows cut from each, compared frame by frame. - const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps).map((t) => onGrid(t + relStart, outFps)); + await step("the window cuts", async () => { + const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps).map((t) => ({ t, ...snap(t + relStart, CUT_SECONDS, true) })); checks.cuts = []; checks.cutSsimMin = CUT_SSIM_MIN; - for (const at of cutTimes) { - const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, seconds: CUT_SECONDS, fps: o.fps, sourceFps: o.probe.fps, scratchDir: o.scratch, signal }); + for (const { t, rel, regular } of cutTimes) { + // SKIPPED, AND SAID (review H3): a recording too choppy for a window the + // cutter carries frame for frame. A skipped check is named, never passed. + if (!regular) { + skip(`the window cut near ${t.toFixed(1)} s: no ${CUT_SECONDS} s from there on without a dropped or uneven frame`); + continue; + } + const { at, sourceAt } = seekPair(rel); + const sourceSelect = keptSelect(); + const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, sourceAt, ...(sourceSelect ? { sourceSelect } : {}), seconds: CUT_SECONDS, fps: o.fps, sourceFps: srcFps, 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)) { @@ -1166,10 +1464,12 @@ async function verify(o: { ); } } - log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter land on the original's frames.`); + log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter compared with the original's${checks.skipped?.length ? `; SKIPPED: ${checks.skipped.join("; ")}` : ""}.`); + }); // The recording clock. checks.clock = "none"; + await step("the recording clock", async () => { const plan = await planRecordingClock(o.videoDir).catch(() => null); if (plan?.kind === "current") { const old = plan.clock; @@ -1194,6 +1494,7 @@ async function verify(o: { : `the recording clock's map is ${fresh.ok ? "ok" : "NOT ok"} against the re-encode and ${old.ok ? "ok" : "NOT ok"} against the original`, ); } + if (fresh.ok !== old.ok || moved !== undefined) return; 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. @@ -1205,6 +1506,8 @@ async function verify(o: { } else if (plan?.kind === "measure") { checks.clock = "stale"; } + }); + if (problems.length) throw new VerifyFailure(problems.join("; "), { ...checks, failures: [...problems] }, failedChunks); checks.passed = true; return { checks: checks as SavedVideoCompactedChecks, clock: keep }; } @@ -1281,8 +1584,17 @@ async function afterSwap(o: { log(`${tag}: dropOriginal is "keep": the original ${original.file} stays until a person drops it.`); return { dropped: false, review: state() }; } - if (!pointer.compacted?.checks.wholeFile || !pointer.compacted.checks.wholeFile.chroma) { - log(`${tag}: the verification has no whole-file luma AND colour comparison: "after-verify" does not drop the original ${original.file}.`); + if (pointer.compacted?.checks.skipped?.length) { + log( + `${tag}: the verification skipped ${pointer.compacted.checks.skipped.length} check(s) (${pointer.compacted.checks.skipped.join("; ")}): ` + + `"after-verify" does not drop the original ${original.file}.`, + ); + return { dropped: false, review: state() }; + } + if (!pointer.compacted?.checks.wholeFile || !pointer.compacted.checks.wholeFile.chroma || !pointer.compacted.checks.chunkMeans) { + log( + `${tag}: the verification has no whole-file luma, colour AND per-chunk comparison: "after-verify" does not drop the original ${original.file}.`, + ); return { dropped: false, review: state() }; } if (!presence.onPlatform) { @@ -1327,7 +1639,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; belowThreshold?: boolean }, + opts: CompactRunOptions & { items: CompactItem[]; mode: "explicit" | "select"; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean }, ): Promise<CompactSavedVideosResult> { const result: CompactSavedVideosResult = { compacted: [], skipped: [], failed: [] }; // Stale markers first: none of them may block this run (or any other). @@ -1501,6 +1813,83 @@ export async function listCompactionMarkers(paths: Paths): Promise<CompactionMar return rows; } +export type KeptFailedEncodeRow = { + slug: string; + id: string; + dir: string; + at: string; + reason: string; + failedChunks: number[]; + kept: KeptFailedEncode | null; + // A scratch in the store with NO POINTER naming its dir (review G3: left + // by a removal before this release, or an interrupted one): nothing will + // ever re-verify it; clear it. + orphaned?: boolean; + bytes?: number; +}; + +async function dirBytes(dir: string): Promise<number> { + let n = 0; + for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + const p = path.join(dir, e.name); + if (e.isDirectory()) n += await dirBytes(p); + else n += await stat(p).then((st) => st.size, () => 0); + } + return n; +} + +// Every failed encode kept in the store (`<store dir>/.compact-scratch` with a +// failed.json): what failed, what is kept and its size — and every scratch in +// the store whose video has no pointer any more, as ORPHANED. +export async function listKeptFailedEncodes(paths: Paths): Promise<KeptFailedEncodeRow[]> { + const rows: KeptFailedEncodeRow[] = []; + const owned = new Set<string>(); + for (const e of await listSavedVideos({ paths })) { + owned.add(path.resolve(e.pointer.dir)); + const f = await lastFailure(e.pointer.dir).catch(() => null); + if (!f) continue; + rows.push({ slug: e.slug, id: e.videoId, dir: path.join(e.pointer.dir, COMPACTION_SCRATCH_DIRNAME), at: f.at, reason: f.reason, failedChunks: f.failedChunks, kept: f.kept }); + } + for (const slug of await readdir(paths.savedVideosDir).catch(() => [] as string[])) { + for (const id of await readdir(path.join(paths.savedVideosDir, slug)).catch(() => [] as string[])) { + const storeDir = path.resolve(paths.savedVideosDir, slug, id); + const scratch = path.join(storeDir, COMPACTION_SCRATCH_DIRNAME); + if (owned.has(storeDir) || !(await stat(scratch).then((st) => st.isDirectory(), () => false))) continue; + const f = await lastFailure(storeDir).catch(() => null); + rows.push({ + slug, + id, + dir: scratch, + at: f?.at ?? "", + reason: f?.reason ?? "no failed.json (a run that never finished)", + failedChunks: f?.failedChunks ?? [], + kept: f?.kept ?? null, + orphaned: true, + bytes: await dirBytes(scratch), + }); + } + } + return rows; +} + +// One video's kept failed encode removed (its whole scratch) — refused while +// a compaction of it runs (its marker is live). A video with no pointer: its +// ORPHANED scratch in the store, under the same refusal. +export async function clearKeptFailedEncode(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string; bytes?: number }> { + const { markerLiveness } = await import("../lib/compactingMarker-server"); + const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id)); + const storeDir = p ? p.dir : path.join(paths.savedVideosDir, item.slug, item.id); + const scratch = path.join(storeDir, COMPACTION_SCRATCH_DIRNAME); + const f = await lastFailure(storeDir).catch(() => null); + const present = await stat(scratch).then((st) => st.isDirectory(), () => false); + if (p ? !f : !present) return { cleared: false, why: p ? "no failed encode is kept for it" : "no saved video and no scratch in the store" }; + const m = await readCompactingMarker(storeDir).catch(() => null); + if (m && (await markerLiveness(m)).live) return { cleared: false, why: "a compaction of it is running" }; + const bytes = f?.kept?.bytes ?? (await dirBytes(scratch)); + await rm(scratch, { recursive: true, force: true }); + return { cleared: true, why: `removed${p ? "" : " (orphaned)"} (${formatBytes(bytes)})`, bytes }; +} + // Clear one video's marker — refused while it is live (cancel the job instead). export async function clearCompactionMarker(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string }> { const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id)); diff --git a/common/lib/compactMedia-server.ts b/common/lib/compactMedia-server.ts @@ -92,6 +92,8 @@ export type SourceProbe = CompactionProbe & { bytes: number; // The stream index of the video stream compaction replaces. mainVideoIndex: number; + // That stream's time base (seconds per tick), when ffprobe says. + timeBase?: number | null; // 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". @@ -138,6 +140,10 @@ export async function probeCompactionSource(ffprobeBin: string, file: string): P const firstAudio = audios[0]; return { mainVideoIndex: typeof v?.index === "number" ? v.index : 0, + timeBase: (() => { + const [a, b] = String(v?.time_base ?? "").split("/").map(Number); + return a > 0 && b > 0 ? a / b : null; + })(), container: mp4Ok ? "mp4" : "matroska", audioStart: firstAudio ? (numOr(firstAudio.start_time) ?? 0) : null, formatStart: numOr(doc.format?.start_time) ?? 0, @@ -229,6 +235,12 @@ export type ChunkPlan = { sourceFrames: number; // Frames the chunk must hold: the source's, or the fps filter's count. expectedFrames: number; + // Its source frames by index in the file, [fromIndex, toIndex), and — when + // the rate is reduced by a whole ratio — the constant `select` (keepSelect) + // that keeps the file's KEPT FRAMES among them. + fromIndex?: number; + toIndex?: number; + select?: string; // The last chunk runs to the end of the source. last?: boolean; }; @@ -252,18 +264,31 @@ const EDGE = 1e-4; // Chunks of about `chunkSeconds`, each starting on a source keyframe. A chunk // is never shorter than half the asked length unless it is the only one. -export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null, sourceFps?: number | null): ChunkPlan[] { +export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: number | null, sourceFps?: number | null, keep?: KeepRule): 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. + // With a frame-rate change, a chunk starts only where the copy's frames + // line up with the whole file's: + // - a WHOLE ratio m (60 → 30) keeps every m-th source frame WITH ITS OWN + // TIMESTAMP, counted from each chunk's first frame, so a chunk starts only + // on a keyframe whose INDEX in the file is a multiple of m — by index, not + // by time: a live recording drops frames, and after an odd gap the time + // grid and the index grid part; + // - any other ratio goes through the fps filter, a constant grid from the + // chunk's first frame: a keyframe ON THE COPY'S TIME GRID, else each + // chunk's rounded count would move the picture by part of a frame. + const m = wholeRatio(sourceFps, outFps); + const indexOf = (k: number) => countIn(pts, -Infinity, k - EDGE); + // With the file's kept frames (keptSourceFrames), a chunk starts only on a + // KEPT keyframe: then each chunk's own selection is the file's. + const mask = keep && m ? keptSourceFrames(pts, keep.minStep) : null; const onGrid = (k: number) => { if (!outFps) return true; + if (mask) return mask[indexOf(k)] === 1; + if (m) return indexOf(k) % m === 0; const x = (k - starts[0]) * outFps; return Math.abs(x - Math.round(x)) < 0.02; }; @@ -275,6 +300,10 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe const from = starts[i]; const to = i + 1 < starts.length ? starts[i + 1] : end; const sourceFrames = countIn(pts, from - EDGE, to - EDGE); + const a = indexOf(from); + const b = a + sourceFrames; + let keptHere = 0; + if (mask) for (let j = a; j < b; j += 1) keptHere += mask[j]; plans.push({ index: i, from, @@ -282,9 +311,14 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe sourceFrames, expectedFrames: !outFps ? sourceFrames - : wholeRatio(sourceFps, outFps) - ? Math.ceil(sourceFrames / wholeRatio(sourceFps, outFps)!) - : framesAtFps(pts, from, to, outFps, i + 1 === starts.length), + : mask + ? keptHere + : wholeRatio(sourceFps, outFps) + ? Math.ceil(sourceFrames / wholeRatio(sourceFps, outFps)!) + : framesAtFps(pts, from, to, outFps, i + 1 === starts.length), + fromIndex: a, + toIndex: b, + ...(mask ? { select: keepSelect(keep!.minStep) } : {}), ...(i + 1 === starts.length ? { last: true } : {}), }); } @@ -325,9 +359,18 @@ export type EncodeSettings = { // without rounding a frame's time to the millisecond. export const CHUNK_EXT = ".mp4"; +// The copy's real rate: the source's nominal one over a whole ratio, else the cap. +function outRate(s: EncodeSettings): number { + const m = wholeRatio(s.sourceFps, s.fps); + return m ? s.sourceFps / m : (s.fps ?? s.sourceFps); +} + 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)); + // A keyframe at the first frame at or after every gopSeconds OF TIME (the + // frames' own timestamps: a gap does not stretch a GOP); -g, twice that in + // frames, only bounds it. + const gop = Math.max(1, Math.round(2 * 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. @@ -339,16 +382,28 @@ export function encodeChunkArgs(src: string, chunk: ChunkPlan, s: EncodeSettings ...(to !== null ? ["-to", to.toFixed(6)] : []), "-i", src, "-map", "0:v:0", "-an", "-sn", "-dn", - // A whole ratio: every m-th frame, RE-TIMED on the copy's own grid from - // the chunk's first frame (n / fps) and written at that rate, so each - // chunk lasts exactly its frames — passed through, the last frame kept the - // source's 1/60 s and every later chunk landed a source frame early. - ...(s.fps - ? wholeRatio(s.sourceFps, s.fps) - ? ["-vf", `${decimateTo(s.sourceFps, s.fps)}setpts=N/${s.fps}/TB`, "-r", String(s.fps)] - : ["-vf", decimateTo(s.sourceFps, s.fps).replace(/,$/, "")] - : []), + // THE SOURCE'S TIMESTAMPS KEPT (review, the first real run): every frame + // keeps its own pts, relative to the chunk's first (the mux puts each chunk + // at its source time), so a frame the live recording dropped stays a gap + // and the picture stays on the sound's clock after it. A whole ratio keeps + // every m-th frame BY INDEX (`select`, passed through; not `framestep`, + // which re-times what it keeps — measured: after an odd gap it wrote a + // frame at 6.000 s that the source does not have); any other ratio, the + // fps filter's constant grid, which repeats a frame across a gap (sync + // kept, the gap filled). The encoder is told the copy's rate itself + // (`select` leaves the source's on the link). + ...(s.fps && !wholeRatio(s.sourceFps, s.fps) + ? ["-vf", `${decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`] + : [ + "-vf", `${chunk.select ? `select='${chunk.select}',` : decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`, "-fps_mode", "passthrough", + // …ON THE SOURCE'S OWN TIME BASE (review H1): the default, 1 / the + // frame rate, rounded a millisecond-stamped recording's times onto a + // 1/60 s grid (up to 0.67 ms off); the 90 kHz copy holds them exactly. + "-enc_time_base:v", "demux", + ]), "-c:v", "libsvtav1", "-preset", String(s.preset), "-crf", String(s.crf), + "-svtav1-params", `fps-num=${Math.round(outRate(s) * 1000)}:fps-denom=1000`, + "-force_key_frames", `expr:gte(t,n_forced*${s.gopSeconds})`, "-g", String(gop), "-pix_fmt", s.pixFmt, "-video_track_timescale", "90000", "-f", "mp4", out, @@ -401,8 +456,161 @@ export async function streamInventory(ffprobeBin: string, file: string, skipInde return out.sort(); } -export function concatList(files: string[]): string { - return files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n"; +// The concat list. With `durations` (every chunk's but the last: the next +// chunk's first source pts less its own), each chunk starts at its SOURCE time, +// not where the one before happened to end. +export function concatList(files: string[], durations?: number[]): string { + return ( + files + .map((f, i) => `file '${f.replace(/'/g, "'\\''")}'` + (durations && i < durations.length ? `\nduration ${durations[i].toFixed(6)}` : "")) + .join("\n") + "\n" + ); +} + +// --- timestamps ------------------------------------------------------------- + +// THE KEPT FRAMES (reviews G4, H1). A source capped by a whole ratio keeps a +// frame when at least `keepMinStep` has passed since the last kept frame's +// pts — by TIME, from the source's own timestamps: a 60 fps stretch keeps +// every other frame, a stretch where the recording ran at 30 keeps every +// frame, after a gap the next frame; each kept frame keeps its own pts. +// +// ONE CONSTANT RULE, the same in ffmpeg and in the code: the encoder's select +// is `keepSelect` (a few dozen characters, whatever the file — a set of runs +// fragmented into hundreds of thousands on a recording with millisecond +// timestamps, and broke ffmpeg's parser and argv), and every check that pairs +// source and copy frames derives the kept set from the same rule +// (`keptSourceFrames`). The step is one copy frame less HALF A SOURCE FRAME +// (less 0.25 ms more): between one source step and two, so a 60 fps source +// whose timestamps are rounded to the millisecond (16, 17, 17 ms) keeps +// exactly every other frame, and off every millisecond and 90 kHz tick, so a +// rounding can never put a step exactly on it. +export type KeepRule = { minStep: number }; + +export function keepMinStep(outFps: number, sourceFps: number): number { + return Number((1 / outFps - 0.5 / sourceFps - 0.00025).toFixed(6)); +} + +export function keptSourceFrames(pts: Float64Array, minStep: number): Uint8Array { + const m = new Uint8Array(pts.length); + let last = -Infinity; + for (let i = 0; i < pts.length; i += 1) { + if (i > 0 && pts[i] - last < minStep) continue; + m[i] = 1; + last = pts[i]; + } + return m; +} + +// The rule as ffmpeg's select: the first frame, then each one at least +// `minStep` after the last selected. +export function keepSelect(minStep: number): string { + return `isnan(prev_selected_t)+gte(t-prev_selected_t,${minStep.toFixed(6)})`; +} + +// The nominal frame rate of a scan: 1 / its typical frame step — the mean of +// the steps within half of the median, so a live recording's dropped frames +// (long steps) do not move it, and a container's ticks (a 30 fps mkv's 33 and +// 34 ms) average out. Within 0.05 % of a whole or an NTSC (×1000/1001) rate, +// that rate (1/60 s in 1/15360 s ticks reads 59.998). +export function nominalFps(pts: Float64Array): number | null { + if (pts.length < 2) return null; + const d = new Float64Array(pts.length - 1); + for (let i = 1; i < pts.length; i += 1) d[i - 1] = pts[i] - pts[i - 1]; + const sorted = Float64Array.from(d).sort(); + const median = sorted[sorted.length >> 1]; + if (!(median > 0)) return null; + let sum = 0; + let n = 0; + for (const x of d) { + if (Math.abs(x - median) > median / 2) continue; + sum += x; + n += 1; + } + const r = n / sum; + let best: number | null = null; + for (const c of [Math.round(r), Math.round(r * 1.001) / 1.001]) { + if (c > 0 && Math.abs(r - c) / c < 0.0005 && (best === null || Math.abs(r - c) < Math.abs(r - best))) best = c; + } + return best ?? r; +} + +export type SourceGaps = { count: number; totalSeconds: number; largest: number; largestAt: number; at: number[] }; + +// The recording's DROPPED FRAMES: every step longer than 1.5 nominal frames, +// how many, how much time they hold beyond one frame each, the largest and +// where (the first 20 places). +export function sourceGaps(pts: Float64Array): SourceGaps { + const fps = nominalFps(pts); + const out: SourceGaps = { count: 0, totalSeconds: 0, largest: 0, largestAt: 0, at: [] }; + if (!fps) return out; + const step = 1 / fps; + for (let i = 1; i < pts.length; i += 1) { + const d = pts[i] - pts[i - 1]; + if (d <= 1.5 * step) continue; + out.count += 1; + out.totalSeconds += d - step; + if (out.at.length < 20) out.at.push(pts[i - 1]); + if (d > out.largest) { + out.largest = d; + out.largestAt = pts[i - 1]; + } + } + return out; +} + +// THE COPY'S TIMESTAMPS, as the encode must have written them: for each +// chunk, its source frames' pts — every m-th from its first under a whole +// ratio m — or, through the fps filter, the constant grid from its first frame. +export function expectedCopyPts( + pts: Float64Array, + chunks: Pick<ChunkPlan, "from" | "to" | "expectedFrames">[], + ratio: number | null, + fps: number | null, + keep?: KeepRule, +): Float64Array { + const out: number[] = []; + if (keep) { + // The file's kept frames, by the rule the encode's `select` applied. + const mask = keptSourceFrames(pts, keep.minStep); + for (let i = 0; i < pts.length; i += 1) if (mask[i]) out.push(pts[i]); + return Float64Array.from(out); + } + for (const c of chunks) { + const a = countIn(pts, -Infinity, c.from - EDGE); + const b = countIn(pts, -Infinity, c.to - EDGE); + if (fps && !ratio) { + for (let k = 0; k < c.expectedFrames; k += 1) out.push(pts[a] + k / fps); + } else { + const m = ratio ?? 1; + for (let i = a; i < b; i += m) out.push(pts[i]); + } + } + return Float64Array.from(out); +} + +export type TimestampCheck = { frames: number; expected: number; maxDeviation: number; at: number; over: number; perChunk: number[] }; + +// Every frame of the copy against the timestamp it must have (both sorted, +// each relative to its own file's start), within `tolerance` (a container's +// rounding: Matroska keeps milliseconds). The worst deviation per chunk is +// the picture against the sound at that point of the file: the audio is the +// source's, packet for packet, at the source's times. +export function compareCopyPts(expected: Float64Array, actual: Float64Array, tolerance: number, chunkStarts: number[] = [0]): TimestampCheck { + const n = Math.min(expected.length, actual.length); + const out: TimestampCheck = { frames: actual.length, expected: expected.length, maxDeviation: 0, at: 0, over: 0, perChunk: chunkStarts.map(() => 0) }; + let c = 0; + for (let i = 0; i < n; i += 1) { + while (c + 1 < chunkStarts.length && i >= chunkStarts[c + 1]) c += 1; + const d = Math.abs(actual[i] - expected[i]); + if (d > out.perChunk[c]) out.perChunk[c] = d; + if (d > tolerance) out.over += 1; + if (d > out.maxDeviation) { + out.maxDeviation = d; + out.at = expected[i]; + } + } + return out; } // --- verification ----------------------------------------------------------- @@ -410,21 +618,86 @@ export function concatList(files: string[]): string { // Every frame of the video decoded, with ffmpeg told to stop at the first // error (`-xerror`) and to print any. An empty stderr and a zero exit is a // clean decode. -export async function fullDecode(paths: GatedPaths, file: string, signal?: AbortSignal): Promise<{ ok: boolean; why?: string }> { +// WHAT A FULL DECODE'S STDERR MEANS (review, before the second real run: a +// correct copy of a source with a dropped frame failed on a NULL MUXER line). +// FATAL — the decoder or demuxer reporting damage to the picture or sound: +// any line matching DECODE_FATAL. BENIGN — the null muxer's own timestamp +// bookkeeping, not the picture: DECODE_BENIGN (with `-enc_time_base demux` it +// does not happen; if it does, it is not a decode error). Anything else is a +// note, recorded and not fatal. A non-zero exit is always fatal (-xerror stops +// at the decoder's first error). +export const DECODE_FATAL: RegExp[] = [ + /error/i, /invalid/i, /corrupt/i, /conceal/i, /missing/i, /non-existing/i, /overread/i, /out of range/i, + /illegal/i, /damaged/i, /truncat/i, /unavailable/i, /failed/i, /mmco/i, /desync/i, /no frame/i, /broken/i, + // Review H4: references and bitstreams, the container, AAC. + /frame num gap/i, /could not find ref/i, /unknown obu/i, /partial file/i, + /reserved bit set/i, /prediction is not allowed/i, /is not allocated/i, /input buffer exhausted/i, + /exceeds limit/i, /inconsistent channel configuration/i, +]; +export const DECODE_BENIGN: RegExp[] = [/non[- ]monotonic(ally increasing)? dts/i, /^last message repeated/i]; + +export function classifyDecodeStderr(text: string): { fatal: string[]; benign: string[]; notes: string[] } { + const out = { fatal: [] as string[], benign: [] as string[], notes: [] as string[] }; + for (const raw of text.split("\n")) { + const l = raw.trim(); + if (!l) continue; + // Strip "[h264 @ 0x55…] " so a pattern judges the message. + const msg = l.replace(/^\[[^\]]*\]\s*/, ""); + if (DECODE_BENIGN.some((r) => r.test(msg))) out.benign.push(l); + else if (DECODE_FATAL.some((r) => r.test(msg))) out.fatal.push(l); + else out.notes.push(l); + } + return out; +} + +// Every frame decoded into the null muxer, KEEPING EACH STREAM'S OWN TIME +// BASE (`-enc_time_base demux`): re-quantised to the copy's nominal 1001/30000, +// two kept frames around a dropped one rounded to the same tick and the muxer +// complained, about nothing in the picture. +// +// TWO PASSES (review H4). The VIDEO, 0:v:0 alone, stopping at its first +// error: any fatal line fails the copy. Then the AUDIO, every track: it is the +// source's, packet for packet (checked apart), so damage in it is the +// source's — with `reference` (the source) given, fatal audio lines the +// source's own audio decode shows as many of are a note; more than the +// source's fail. +async function decodePass(paths: GatedPaths, file: string, map: string[], xerror: boolean, signal?: AbortSignal) { try { const err = await runHeavyFfmpeg( paths, - ["-nostdin", "-hide_banner", "-v", "error", "-xerror", "-i", file, "-map", "0:v:0", "-map", "0:a?", "-f", "null", "-"], + ["-nostdin", "-hide_banner", "-v", "error", ...(xerror ? ["-xerror"] : []), "-i", file, ...map, "-enc_time_base", "demux", "-f", "null", "-"], { estimateMB: DECODE_ESTIMATE_MB, ...(signal ? { signal } : {}) }, ); - const lines = err.split("\n").map((l) => l.trim()).filter(Boolean); - return lines.length ? { ok: false, why: lines.slice(-2).join(" | ") } : { ok: true }; + return { exited: true, ...classifyDecodeStderr(err) }; } catch (e) { if (signal?.aborted) throw e; - return { ok: false, why: (e as Error).message }; + return { exited: false, fatal: [(e as Error).message], benign: [] as string[], notes: [] as string[] }; } } +export async function fullDecode( + paths: GatedPaths, + file: string, + signal?: AbortSignal, + reference?: string, +): Promise<{ ok: boolean; why?: string; notes?: string[] }> { + const v = await decodePass(paths, file, ["-map", "0:v:0"], true, signal); + if (v.fatal.length) return { ok: false, why: `video: ${v.fatal.slice(-2).join(" | ")}` }; + const notes = [...v.benign, ...v.notes]; + const a = await decodePass(paths, file, ["-map", "0:a?", "-vn"], false, signal); + // No audio at all: ffmpeg has nothing to write and says so. + if (!a.exited && /does not contain any stream/i.test(a.fatal[0] ?? "")) return notes.length ? { ok: true, notes: notes.slice(0, 5) } : { ok: true }; + if (a.fatal.length) { + const ref = reference ? await decodePass(paths, reference, ["-map", "0:a?", "-vn"], false, signal) : null; + if (!ref || !a.exited || ref.fatal.length < a.fatal.length) { + return { ok: false, why: `audio: ${a.fatal.slice(-2).join(" | ")}${ref ? ` (the source's own audio: ${ref.fatal.length} such line(s))` : ""}` }; + } + notes.push(`audio: ${a.fatal.length} decode error line(s), as many as the source's own audio shows (copied packet for packet): ${a.fatal[0]}`); + } + notes.push(...a.benign, ...a.notes); + return notes.length ? { ok: true, notes: notes.slice(0, 5) } : { ok: true }; +} + export type AudioHash = { // sha256 over every audio packet's (stream, size, md5) in order. data: string; @@ -551,6 +824,12 @@ export async function scoreExcerpt( compacted: string; source: string; at: number; + // The SAME FRAME's seek time in the source, when its command-line + // timeline starts elsewhere than the copy's (cliTimelineStart); else `at`. + sourceAt?: number; + // The kept frames' `select` (keepSelect), in place of the ratio's + // decimation; the excerpt starts on a kept frame. + sourceSelect?: string; seconds: number; fps: number | null; sourceFps?: number | null; @@ -565,8 +844,10 @@ export async function scoreExcerpt( // 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 srcAt = opts.sourceAt ?? opts.at; + const pre = Math.max(0, srcAt - 10); + const dec = opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps); + const ref = `[1:v]trim=start=${(srcAt - pre).toFixed(4)},${dec}${n}[r]`; const dist = `[0:v]${n}[d]`; const log = path.join(opts.scratchDir, `vmaf-${Math.round(opts.at * 1000)}.json`); const metric = @@ -578,7 +859,7 @@ export async function scoreExcerpt( "-ss", opts.at.toFixed(4), "-t", opts.seconds.toFixed(3), "-i", opts.compacted, // The source decoded from up to 10 s earlier and trimmed to the second: // exact in any container (see referenceCutArgs). - "-ss", pre.toFixed(4), "-t", (opts.at - pre + opts.seconds).toFixed(3), "-i", opts.source, + "-ss", pre.toFixed(4), "-t", (srcAt - pre + opts.seconds).toFixed(3), "-i", opts.source, "-lavfi", `${dist};${ref};${metric}`, "-f", "null", "-", ]; @@ -685,6 +966,11 @@ export async function compareCuts( compacted: string; source: string; at: number; + // The same frame's time in the source's command-line timeline (see + // scoreExcerpt); else `at`. + sourceAt?: number; + // The kept frames' `select` (keepSelect); the cut starts on a kept frame. + sourceSelect?: string; seconds: number; fps: number | null; sourceFps?: number | null; @@ -692,11 +978,12 @@ export async function compareCuts( signal?: AbortSignal; }, ): Promise<CutComparison> { + const srcAt = opts.sourceAt ?? opts.at; const a = path.join(opts.scratchDir, `cut-src-${Math.round(opts.at * 1000)}.mp4`); const b = path.join(opts.scratchDir, `cut-out-${Math.round(opts.at * 1000)}.mp4`); try { for (const [file, out, args] of [ - [opts.source, a, referenceCutArgs(opts.source, opts.at, opts.at + opts.seconds, a)], + [opts.source, a, referenceCutArgs(opts.source, srcAt, srcAt + opts.seconds, a)], [opts.compacted, b, evidenceCutArgs(opts.compacted, opts.at, opts.at + opts.seconds, "video", b)], ] as const) { const r = await execa(paths.ffmpegBin, args, { @@ -710,7 +997,7 @@ export async function compareCuts( ); } } - const rate = decimateTo(opts.sourceFps, opts.fps); + const rate = opts.sourceSelect ? `select='${opts.sourceSelect}',` : 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); @@ -722,6 +1009,22 @@ export async function compareCuts( } } +// WHERE A FILE'S COMMAND-LINE TIMELINE STARTS (absolute seconds): an `-ss t` +// on it lands on the first frame at or after this + t. Not always the +// container's start ffprobe reports — measured: an mpegts whose audio starts at +// 2.877 s and video at 2.900 s is placed by ffmpeg from 2.900 s, our mp4 copy +// of it from its container start — so the copy and its source each get their +// own seek time for the same frame. The first video frame's time without a +// seek, against its pts. +export async function cliTimelineStart(ffmpegBin: string, file: string, firstVideoPts: number): Promise<number> { + const r = await execa(ffmpegBin, ["-nostdin", "-hide_banner", "-i", file, "-map", "0:v:0", "-an", "-sn", "-vf", "showinfo", "-frames:v", "1", "-f", "null", "-"], { + reject: false, + }); + const m = /pts_time:(-?[0-9.]+)/.exec(String(r.stderr ?? "")); + if (!m) throw new Error(`could not read where ffmpeg starts ${path.basename(file)}'s timeline`); + return firstVideoPts - Number(m[1]); +} + // 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 { @@ -764,6 +1067,9 @@ export type WholeFileComparison = { width: number; height: number; grid: number; + // The source's picture detail per paired frame (review G2): the mean of a + // Sobel edge map of the source frame, grey, at the comparison's size. + sourceDetail?: Float32Array; }; function ssimScores(text: string, plane = "All"): number[] { @@ -787,6 +1093,9 @@ export async function compareWholeFile( // The copy's frame rate when it was capped, the source's rate, its size. fps: number | null; sourceFps: number | null; + // The file's kept frames' `select` (keepSelect), in place of the + // ratio's decimation. + sourceSelect?: string; sourceWidth: number | null; sourceHeight: number | null; tileFloor: number; @@ -804,6 +1113,7 @@ export async function compareWholeFile( const n = renumber(rate); const esc = (f: string) => f.replace(/[:\\']/g, "\\$&"); const whole = path.join(opts.scratchDir, "wf-whole.log"); + const detailLog = path.join(opts.scratchDir, "wf-detail.log"); const tileLog = (k: number) => path.join(opts.scratchDir, `wf-tile-${k}.log`); const labels = (p: string) => Array.from({ length: T + 1 }, (_, k) => `[${p}${k}]`).join(""); // The whole frame keeps its colour (yuv420p: the ssim filter's stats give @@ -811,8 +1121,12 @@ export async function compareWholeFile( const chains = [ `[0:v]${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[d0][dg]`, `[dg]format=gray,split=${T}${labels("d").replace("[d0]", "")}`, - `[1:v]${decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[r0][rg]`, - `[rg]format=gray,split=${T}${labels("r").replace("[r0]", "")}`, + `[1:v]${opts.sourceSelect ? `select='${opts.sourceSelect}',` : decimateTo(opts.sourceFps, opts.fps)}${n},scale=${W}:${H}:flags=area,format=yuv420p,split=2[r0][rg]`, + // …and one more: the SOURCE's own picture detail per frame (the mean of a + // Sobel edge map, review G2), so a chunk drop at a join can be told from + // a segment of harder picture starting there. + `[rg]format=gray,split=${T + 1}${labels("r").replace("[r0]", "")}[rdet]`, + `[rdet]sobel,signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=${esc(detailLog)},nullsink`, `[d0][r0]ssim=stats_file=${esc(whole)}:eof_action=endall[out]`, ]; for (let k = 0; k < T; k += 1) { @@ -864,9 +1178,13 @@ export async function compareWholeFile( } tiles.push({ index: k, col: k % G, row: Math.floor(k / G), min, minAt, longestBelow: longest, longestBelowAt: longestAt }); } - return { frames, chromaU, chromaV, tiles, width: W, height: H, grid: G }; + const sourceDetail = Float32Array.from( + [...(await readFile(detailLog, "utf8").catch(() => "")).matchAll(/lavfi\.signalstats\.YAVG=(-?[0-9.]+)/g)].map((m) => Number(m[1])), + ); + return { frames, chromaU, chromaV, tiles, width: W, height: H, grid: G, ...(sourceDetail.length === frames.length ? { sourceDetail } : {}) }; } finally { await rm(whole, { force: true }).catch(() => {}); + await rm(detailLog, { force: true }).catch(() => {}); await rm(graphFile, { force: true }).catch(() => {}); for (let k = 0; k < T; k += 1) await rm(tileLog(k), { force: true }).catch(() => {}); } @@ -889,6 +1207,12 @@ export type WholeFileVerdict = { worstLocalMargin: number; worstLocalAt: number; windowFrames: number; + // The file's recurring lower kind of picture, when it has one (review F-a), + // and why a candidate was refused (review G1). + lowerState: LowerState | null; + lowerStateRefused?: string; + // Every chunk against the others (review G2); null without chunk starts. + chunks: ChunkVerdict | null; worstTile: TileSummary | null; chroma: { mean: number; min: number; minAt: number; plane: "U" | "V" }; }; @@ -914,18 +1238,33 @@ function floorOf(f: Float32Array, k: number, margin: number): { median: number; // after the change fit their right-hand side — while a short defect inside a // steady stretch has the steady stretch on both sides and falls below. A file // shorter than the window is one neighbourhood: the whole file. -export function localFloors(f: Float32Array, windowFrames: number, k: number, margin: number): Float32Array { +// +// FAST SWITCHING (review F-a): a half-window that is half screen share and half +// webcam has a floor that flips with whichever is the majority (and, split +// evenly, a median between the two and a floor far too low). So when the file +// has a RECURRING LOWER KIND of picture (`lowerState`), a neighbourhood holding +// at least LOWER_STATE_BLOCK_SHARE of its frames in that kind's runs takes its +// floor from THOSE frames alone: the frames in the same state. A second's dip +// inside a steady stretch is in no run and keeps the stretch's floor. +export function localFloors(f: Float32Array, windowFrames: number, k: number, margin: number, lower?: LowerState | null): Float32Array { const out = new Float32Array(f.length); const half = Math.max(8, Math.floor(windowFrames / 2)); + const lowCount = new Uint32Array(f.length + 1); + for (let i = 0; i < f.length; i += 1) lowCount[i + 1] = lowCount[i] + (lower?.mask[i] ? 1 : 0); + const blockFloor = (s: number, e: number) => { + const block = f.subarray(s, e); + if (!lower || lowCount[e] - lowCount[s] < LOWER_STATE_BLOCK_SHARE * (e - s)) return floorOf(block, k, margin).floor; + return floorOf(block.filter((_, j) => lower.mask[s + j] === 1), k, margin).floor; + }; if (f.length <= windowFrames) { - out.fill(floorOf(f, k, margin).floor); + out.fill(blockFloor(0, f.length)); return out; } const stride = Math.max(1, Math.floor(windowFrames / 8)); const starts: number[] = []; for (let s = 0; s + half <= f.length; s += stride) starts.push(s); if (starts[starts.length - 1] !== f.length - half) starts.push(f.length - half); - const floors = starts.map((s) => floorOf(f.subarray(s, s + half), k, margin).floor); + const floors = starts.map((s) => blockFloor(s, s + half)); for (let i = 0; i < f.length; i += 1) { // Left: the last block ending at or before i; right: the first starting after i. let lo = 0; @@ -948,13 +1287,115 @@ export function localFloors(f: Float32Array, windowFrames: number, k: number, ma hi = mid - 1; } else lo = mid + 1; } - const a = left >= 0 ? floors[left] : Infinity; - const b = right >= 0 ? floors[right] : Infinity; - out[i] = Math.min(a, b) === Infinity ? floors[0] : Math.min(a, b); + // At the file's ends one side is missing: the first frames have no block + // ending before them, the last none starting after them. That side is then + // the first (or last) block, which holds the frame — not nothing, or a + // webcam closing the file's last minute is judged by the share before it. + const a = floors[left >= 0 ? left : 0]; + const b = floors[right >= 0 ? right : starts.length - 1]; + out[i] = Math.min(a, b); + } + return out; +} + +// A RECURRING LOWER KIND OF PICTURE (review F-a, bounded by review G1). Only +// SCENE STRUCTURE qualifies: frames count only in RUNS of at least +// `minRunFrames` below the split (longer than one 5 s GOP, with margin, so a +// per-GOP or periodic fault of a few seconds never forms a state). The split is +// Otsu's on the scores, taken twice: the second time without the frames of the +// first split's short runs. The state then needs +// - its runs' frames at least LOWER_STATE_FILE_SHARE of the file, and the +// frames above the split at least as many; +// - at least LOWER_STATE_MIN_RUNS separate runs; +// - its frames' median below the upper frames' own floor (else the upper +// floor already admits them); +// - a run with an edge on a CHUNK JOIN (within CHUNK_EDGE_FRAMES of an +// interior join) is a bad chunk's signature, not a scene's — a scene +// change lands within two frames of a 10-minute join about 0.03% of the +// time, and a bad chunk next to a real lower stretch merges with it at one +// end only: such a run never counts, and when most runs are such, the +// state is refused. +// Its floor is its frames' median − max(k · their robust spread, margin). +export type LowerState = { threshold: number; floor: number; share: number; runs: number; mask: Uint8Array }; +export const LOWER_STATE_FILE_SHARE = 0.1; +export const LOWER_STATE_BLOCK_SHARE = 0.2; +export const LOWER_STATE_MIN_RUNS = 3; +export const CHUNK_EDGE_FRAMES = 2; + +function otsuThreshold(values: Float32Array, minSide: number): number | null { + const n = values.length; + if (n < 2 * minSide || minSide < 1) return null; + const s = Float64Array.from(values).sort(); + const sum = new Float64Array(n + 1); + for (let i = 0; i < n; i += 1) sum[i + 1] = sum[i] + s[i]; + let best = -1; + let at = minSide; + for (let j = minSide; j <= n - minSide; j += 1) { + const d = sum[j] / j - (sum[n] - sum[j]) / (n - j); + const between = j * (n - j) * d * d; + if (between > best) { + best = between; + at = j; + } + } + return (s[at - 1] + s[at]) / 2; +} + +// The runs of frames below `threshold`, [from, to). +function runsBelow(f: Float32Array, threshold: number): [number, number][] { + const out: [number, number][] = []; + let start = -1; + for (let i = 0; i <= f.length; i += 1) { + const low = i < f.length && f[i] < threshold; + if (low && start < 0) start = i; + else if (!low && start >= 0) { + out.push([start, i]); + start = -1; + } } return out; } +export function lowerState( + f: Float32Array, + k: number, + margin: number, + o: { minRunFrames: number; chunkStarts?: number[] } = { minRunFrames: 1 }, +): { state: LowerState | null; refused?: string } { + const n = f.length; + const minSide = Math.ceil(LOWER_STATE_FILE_SHARE * n); + if (n < 32) return { state: null }; + const minRun = Math.max(1, Math.round(o.minRunFrames)); + const long = (t: number) => runsBelow(f, t).filter(([a, b]) => b - a >= minRun); + const t1 = otsuThreshold(f, minSide); + if (t1 === null) return { state: null }; + const keep1 = new Uint8Array(n).fill(1); + for (const [a, b] of runsBelow(f, t1)) if (b - a < minRun) keep1.fill(0, a, b); + const t = otsuThreshold(f.filter((_, i) => keep1[i] === 1), Math.min(minSide, Math.floor(n / 4))) ?? t1; + const joins = new Set<number>((o.chunkStarts ?? []).filter((x) => x > 0 && x < n)); + const onJoin = (x: number) => { + for (let d = -CHUNK_EDGE_FRAMES; d <= CHUNK_EDGE_FRAMES; d += 1) if (joins.has(x + d)) return true; + return false; + }; + const all = long(t); + const aligned = joins.size ? all.filter(([a, b]) => onJoin(a) || onJoin(b)) : []; + const runs = all.filter((r) => !aligned.includes(r)); + if (all.length && aligned.length * 2 > all.length) { + return { state: null, refused: `${aligned.length} of its ${all.length} runs begin or end on a chunk join (a bad chunk's signature)` }; + } + const mask = new Uint8Array(n); + let count = 0; + for (const [a, b] of runs) { + mask.fill(1, a, b); + count += b - a; + } + const upper = f.filter((x) => x >= t); + if (count < minSide || upper.length < minSide || runs.length < LOWER_STATE_MIN_RUNS) return { state: null }; + const low = f.filter((_, i) => mask[i] === 1); + if (medianOf(low) >= floorOf(upper, k, margin).floor) return { state: null }; + return { state: { threshold: t, floor: floorOf(low, k, margin).floor, share: count / n, runs: runs.length, mask } }; +} + export function robustSpread(f: Float32Array): { median: number; sd: number } { const median = medianOf(f); const dev = new Float64Array(f.length); @@ -963,7 +1404,7 @@ export function robustSpread(f: Float32Array): { median: number; sd: number } { } export function judgeWholeFile( - c: Pick<WholeFileComparison, "frames" | "tiles"> & Partial<Pick<WholeFileComparison, "chromaU" | "chromaV">>, + c: Pick<WholeFileComparison, "frames" | "tiles"> & Partial<Pick<WholeFileComparison, "chromaU" | "chromaV" | "sourceDetail">>, t: { minFrame: number; meanFloor: number; @@ -976,6 +1417,15 @@ export function judgeWholeFile( chromaMeanFloor: number; // The neighbourhood's length in frames (settings wholeFileWindowSeconds × fps). windowFrames?: number; + // The shortest run below the split that counts toward a lower state, in + // frames (wholeFileLowerRunSeconds × fps). Default: 8 s. + lowerRunFrames?: number; + // Each chunk's first frame in the copy (the first is 0). With them, the + // lower state refuses runs on chunk joins and every chunk is compared with + // the others (`chunks`). + chunkStarts?: number[]; + chunkSigmaK?: number; + chunkMargin?: number; }, ): WholeFileVerdict { const f = c.frames; @@ -993,7 +1443,9 @@ export function judgeWholeFile( const { median, sd } = robustSpread(f); const relativeFloor = median - Math.max(t.sigmaK * sd, t.sigmaMinMargin); const windowFrames = Math.max(16, Math.round(t.windowFrames ?? f.length)); - const local = localFloors(f, windowFrames, t.sigmaK, t.sigmaMinMargin); + const lowerResult = lowerState(f, t.sigmaK, t.sigmaMinMargin, { minRunFrames: t.lowerRunFrames ?? 8 * t.fps, chunkStarts: t.chunkStarts }); + const lower = lowerResult.state; + const local = localFloors(f, windowFrames, t.sigmaK, t.sigmaMinMargin, lower); let worstLocalMargin = Infinity; let worstLocalAt = 0; for (let i = 0; i < f.length; i += 1) { @@ -1026,7 +1478,14 @@ export function judgeWholeFile( } const chroma = { mean: u.length ? cSum / u.length : 0, min: cMin, minAt: cMinAt, plane: cPlane }; const at = (i: number) => `${(i / t.fps).toFixed(2)} s`; - const base = { mean, median, sd, min, minAt, relativeFloor, worstLocalMargin, worstLocalAt, windowFrames, worstTile, chroma }; + const chunks = + t.chunkStarts && f.length === t.expectedFrames && u.length === f.length && v.length === f.length + ? judgeChunks({ Y: f, U: u, V: v }, t.chunkStarts, lower, { sigmaK: t.chunkSigmaK ?? 4, margin: t.chunkMargin ?? 0.02, fps: t.fps }, c.sourceDetail) + : null; + const base = { + mean, median, sd, min, minAt, relativeFloor, worstLocalMargin, worstLocalAt, windowFrames, + lowerState: lower, ...(lowerResult.refused ? { lowerStateRefused: lowerResult.refused } : {}), worstTile, chroma, chunks, + }; if (f.length !== t.expectedFrames || u.length !== t.expectedFrames || v.length !== t.expectedFrames) { return { ...base, ok: false, why: `the comparison saw ${f.length} of the copy's ${t.expectedFrames} frames (colour: ${u.length}): it ends early or skips` }; } @@ -1055,5 +1514,126 @@ export function judgeWholeFile( return { ...base, ok: false, why: `the colour (${cPlane} plane) of a frame at ${at(cMinAt)} scores ${cMin.toFixed(3)} (no frame may fall below ${t.chromaMinFrame})` }; } if (chroma.mean < t.chromaMeanFloor) return { ...base, ok: false, why: `the colour's mean is ${chroma.mean.toFixed(3)} (needs ${t.chromaMeanFloor})` }; + if (chunks && !chunks.ok) return { ...base, ok: false, why: chunks.why }; return { ...base, ok: true }; } + +// EVERY CHUNK AGAINST THE OTHERS (review G2). A stretch longer than the local +// window is its own neighbourhood, so a whole chunk evenly worse (a bad encode +// of one chunk) passed the frame floors. Each chunk's mean, on Y, U and V, is +// held to the other chunks' median − max(sigmaK × their robust spread, margin). +// A chunk below it fails UNLESS the source explains the drop: +// - most of its frames are in the file's recurring lower kind of picture +// (`lowerState`, whose runs on chunk joins never count) AND its mean +// reaches what that mix predicts — its share of each kind times that +// kind's median, less the margin — so a bad chunk flanked by the lower +// kind on both sides is not explained by it; or +// - neither of its joins shows the drop: the frames just inside the chunk +// score within half the drop of the frames just outside. A bad chunk +// changes level AT its joins; a harder scene that runs across chunks +// (a game segment in a talk stream) changes level where the scene changes; +// - or THE SOURCE ITSELF STEPS TO HARDER PICTURE at every join where the +// copy drops (reviews G2, H2: a scheduled segment that starts right at a +// join): its picture detail (`sourceDetail`) is SOURCE_CHANGE_SHARE or +// more higher inside than outside, over the 5 s either side AND over the +// whole chunk against the neighbouring one. A bad chunk of unchanged, +// drifting or easier picture still fails. +// One chunk: nothing to compare. Two: each against the other. +export type ChunkVerdict = { + ok: boolean; + why?: string; + count: number; + sigmaK: number; + margin: number; + // The lowest chunk mean relative to its floor (not exempt), on any plane. + worst: { index: number; plane: "Y" | "U" | "V"; mean: number; centre: number; floor: number; joinAt?: number } | null; + exempt: { index: number; plane: "Y" | "U" | "V"; why: "lower state" | "no step at its joins" | "the source changes at its join" }[]; +}; +export const CHUNK_JOIN_SECONDS = 5; +export const SOURCE_CHANGE_SHARE = 0.1; + +export function judgeChunks( + planes: { Y: Float32Array; U: Float32Array; V: Float32Array }, + chunkStarts: number[], + lower: LowerState | null, + o: { sigmaK: number; margin: number; fps: number }, + sourceDetail?: Float32Array, +): ChunkVerdict { + const n = planes.Y.length; + const starts = [...new Set(chunkStarts.filter((x) => x >= 0 && x < n))].sort((a, b) => a - b); + if (starts[0] !== 0) starts.unshift(0); + const spans = starts.map((a, i) => [a, i + 1 < starts.length ? starts[i + 1] : n] as const); + const out: ChunkVerdict = { ok: true, count: spans.length, sigmaK: o.sigmaK, margin: o.margin, worst: null, exempt: [] }; + if (spans.length < 2) return out; + const meanOf = (p: Float32Array, a: number, b: number) => { + let x = 0; + for (let i = a; i < b; i += 1) x += p[i]; + return b > a ? x / (b - a) : 0; + }; + for (const plane of ["Y", "U", "V"] as const) { + const p = planes[plane]; + const means = spans.map(([a, b]) => meanOf(p, a, b)); + // The two kinds' typical scores on this plane, when the file has a lower state. + const lowMedian = lower ? medianOf(p.filter((_, i) => lower.mask[i] === 1)) : 0; + const upMedian = lower ? medianOf(p.filter((_, i) => lower.mask[i] === 0)) : 0; + spans.forEach(([a, b], ci) => { + const others = Float32Array.from(means.filter((_, j) => j !== ci)); + const r = robustSpread(others); + const floor = r.median - Math.max(o.sigmaK * r.sd, o.margin); + const gap = means[ci] - floor; + if (gap >= 0) return; + let lowFrames = 0; + if (lower) for (let i = a; i < b; i += 1) lowFrames += lower.mask[i]; + const m = lowFrames / (b - a); + if (lower && m >= 0.5 && means[ci] >= m * lowMedian + (1 - m) * upMedian - o.margin) { + out.exempt.push({ index: ci, plane, why: "lower state" }); + return; + } + const drop = r.median - means[ci]; + const w = Math.max(1, Math.min(Math.round(CHUNK_JOIN_SECONDS * o.fps), Math.floor((b - a) / 4))); + const windows = (join: number): [[number, number], [number, number]] => + join === a ? [[a, Math.min(b, a + w)], [Math.max(0, a - w), a]] : [[Math.max(a, b - w), b], [b, Math.min(n, b + w)]]; + const stepAt = (join: number) => { + const [inside, outside] = windows(join); + return meanOf(p, outside[0], outside[1]) - meanOf(p, inside[0], inside[1]) >= drop / 2; + }; + // The source EXPLAINS the drop at a join (review H2) only by a step to + // HARDER picture (more detail inside the chunk), both sharp at the join + // (the 5 s either side) and SUSTAINED (the chunk's mean detail against + // the neighbouring chunk's, across that join). A drift, a step the other + // way, or noise over a flat picture explains nothing. + const sourceChangesAt = (join: number) => { + if (!sourceDetail || sourceDetail.length !== n) return false; + const [inside, outside] = windows(join); + const harder = (x: number, y: number) => x - y >= SOURCE_CHANGE_SHARE * Math.max(1e-6, y) && x > 1e-6; + if (!harder(meanOf(sourceDetail, inside[0], inside[1]), meanOf(sourceDetail, outside[0], outside[1]))) return false; + const nb = join === a ? spans[ci - 1] : spans[ci + 1]; + return !!nb && harder(meanOf(sourceDetail, a, b), meanOf(sourceDetail, nb[0], nb[1])); + }; + const stepping = [...(ci > 0 && stepAt(a) ? [a] : []), ...(ci < spans.length - 1 && stepAt(b) ? [b] : [])]; + if (!stepping.length) { + out.exempt.push({ index: ci, plane, why: "no step at its joins" }); + return; + } + if (stepping.every(sourceChangesAt)) { + out.exempt.push({ index: ci, plane, why: "the source changes at its join" }); + return; + } + if (!out.worst || gap < out.worst.mean - out.worst.floor) { + out.worst = { index: ci, plane, mean: means[ci], centre: r.median, floor, joinAt: stepping[0] }; + } + }); + } + if (out.worst) { + const wst = out.worst; + const [a, b] = spans[wst.index]; + out.ok = false; + out.why = + `chunk ${wst.index + 1} of ${spans.length} (${(a / o.fps).toFixed(1)}–${(b / o.fps).toFixed(1)} s) scores ${wst.mean.toFixed(4)} on ${wst.plane}, ` + + `below the other chunks' floor ${wst.floor.toFixed(4)} (their median ${wst.centre.toFixed(4)} − max(${o.sigmaK}·robust spread, ${o.margin})), ` + + `and the drop begins or ends at its chunk join at ${((wst.joinAt ?? a) / o.fps).toFixed(1)} s${sourceDetail ? ", where the source's own picture does not change" : ""}. ` + + "It may still be a segment of harder picture starting exactly at that join: look at the source there; a run with another " + + "chunkMinutes puts the joins elsewhere (it encodes again)"; + } + return out; +} diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts @@ -15,6 +15,7 @@ import { readFile, rename, rm, + rmdir, stat, } from "node:fs/promises"; import { @@ -35,6 +36,7 @@ import { import { assertSavedVideosStoreWritable } from "./savedVideoStore"; import { platformPresence } from "./availability-server"; import { assertNotCompacting } from "./compactingMarker-server"; +import { COMPACTION_SCRATCH_DIRNAME } from "./savedVideoCompaction"; import { probeMedia } from "./evidenceClip-server"; import type { Paths } from "./paths"; @@ -392,12 +394,20 @@ export async function recordSavedVideoProbedHeight( }); } +// A KEPT FAILED ENCODE goes with its video (review G3): when the pointer +// goes — unpersist, the prune's drop — its `.compact-scratch` (chunks and a +// failed copy, gigabytes, named by nothing else) is removed too, after the +// same guards (no compaction of the video is running). +async function removeCompactionScratch(storeDir: string): Promise<void> { + await rm(path.join(storeDir, COMPACTION_SCRATCH_DIRNAME), { recursive: true, force: true }).catch(() => {}); +} + // Best-effort removal of a now-empty store dir (and its empty <slug> parent). +// `rmdir`, which removes an EMPTY directory only: `rm` without `recursive` +// refuses every directory (EISDIR), so this never removed one before. async function pruneEmptyStoreDirs(storeDir: string): Promise<void> { - await rm(storeDir, { recursive: false, force: true }).catch(() => {}); - await rm(path.dirname(storeDir), { recursive: false, force: true }).catch( - () => {}, - ); + await rmdir(storeDir).catch(() => {}); + await rmdir(path.dirname(storeDir)).catch(() => {}); } // Reverse persistSourceVideo: move the stored container back into the data dir @@ -445,6 +455,7 @@ async function unpersistUnlocked( await moveFileCrossDevice(path.join(pointer.dir, alt.file), path.join(videoDir, alt.file)).catch(() => {}); } await rm(savedVideoPointerPath(videoDir), { force: true }); + await removeCompactionScratch(pointer.dir); await pruneEmptyStoreDirs(pointer.dir); return true; } @@ -473,6 +484,7 @@ export async function dropSavedVideo(videoDir: string): Promise<number> { await rm(path.join(pointer.dir, alt.file), { force: true }); } await rm(savedVideoPointerPath(videoDir), { force: true }); + await removeCompactionScratch(pointer.dir); await pruneEmptyStoreDirs(pointer.dir); return savedVideoBytes(pointer); }); diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts @@ -134,6 +134,13 @@ export type SavedVideoCompactedChecks = { passed: boolean; // Full decode of the re-encode, every frame, without an error. decoded: boolean; + // What the decode printed that is not damage (classifyDecodeStderr): a + // null-muxer timestamp line, an unrecognised one. Never fatal. + decodeNotes?: string[]; + // Checks this source could not have (review H3: no window regular enough + // for the evidence cutter on a very choppy recording): named, never passed. + // "after-verify" never drops an original after one. + skipped?: string[]; // [source, re-encode] video lengths in seconds, and the allowed difference. seconds: [number, number]; secondsTolerance: number; @@ -172,9 +179,38 @@ export type SavedVideoCompactedChecks = { windowSeconds?: number; worstLocalMargin?: number; worstLocalAt?: number; + // The file's recurring lower kind of picture, when it has one (review + // F-a): its floor and its share of the frames. A neighbourhood holding at + // least a fifth of its frames at that level took its floor from them alone. + lowerState?: { floor: number; share: number; runs?: number }; + // Only runs of at least this many seconds count toward it, and why a + // candidate was refused (runs on chunk joins: review G1). + lowerRunSeconds?: number; + lowerStateRefused?: string; // THE COLOUR (review D1): SSIM on the U and V planes, every frame. chroma?: { mean: number; min: number; worstAt: number; plane: string; minFloor: number; meanFloor: number }; }; + // THE TIMESTAMPS (review, the first real run): the copy keeps the source's + // own, so every frame's pts is its source frame's (relative to each file's + // start) within `tolerance` — how many are not (`over`), the worst deviation + // and where, and the worst in each chunk (the picture against the sound + // along the file: the audio is the source's, packet for packet, at its times). + timestamps?: { frames: number; expected: number; tolerance: number; maxDeviation: number; at: number; over: number; perChunk: number[] }; + // The recording's dropped frames (every step over 1.5 nominal frames): how + // many, the time they hold beyond a frame each, the largest and where. + sourceGaps?: { count: number; totalSeconds: number; largest: number; largestAt: number }; + // EVERY CHUNK AGAINST THE OTHERS (review G2): each chunk's mean on Y, U and + // V held to the other chunks' median − max(sigmaK × spread, margin); the + // worst chunk below it that the source does not explain (null: none), and + // the chunks below it the source explains and why. + chunkMeans?: { + count: number; + sigmaK: number; + margin: number; + // joinAt: the join (seconds) where the drop begins or ends. + worst: { chunk: number; plane: string; mean: number; centre: number; floor: number; joinAt?: number } | null; + exempt: { chunk: number; plane: string; why: string }[]; + }; // 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[] }; @@ -502,6 +538,17 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { ...(typeof w.windowSeconds === "number" ? { windowSeconds: w.windowSeconds } : {}), ...(typeof w.worstLocalMargin === "number" ? { worstLocalMargin: w.worstLocalMargin } : {}), ...(typeof w.worstLocalAt === "number" ? { worstLocalAt: w.worstLocalAt } : {}), + ...(w.lowerState && typeof w.lowerState === "object" && typeof obj(w.lowerState).floor === "number" && typeof obj(w.lowerState).share === "number" + ? { + lowerState: { + floor: obj(w.lowerState).floor as number, + share: obj(w.lowerState).share as number, + ...(typeof obj(w.lowerState).runs === "number" ? { runs: obj(w.lowerState).runs as number } : {}), + }, + } + : {}), + ...(typeof w.lowerRunSeconds === "number" ? { lowerRunSeconds: w.lowerRunSeconds } : {}), + ...(typeof w.lowerStateRefused === "string" ? { lowerStateRefused: w.lowerStateRefused } : {}), ...(w.chroma && typeof w.chroma === "object" ? (() => { const c = obj(w.chroma); @@ -529,6 +576,45 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null { } : {}), ...(Array.isArray(c.avOffset) ? { avOffset: pair(c.avOffset) } : {}), + ...(Array.isArray(c.decodeNotes) ? { decodeNotes: c.decodeNotes.map(String).slice(0, 5) } : {}), + ...(Array.isArray(c.skipped) ? { skipped: c.skipped.map(String) } : {}), + ...(c.timestamps && typeof c.timestamps === "object" + ? (() => { + const t = obj(c.timestamps); + return { + timestamps: { + frames: num(t.frames), expected: num(t.expected), tolerance: num(t.tolerance), maxDeviation: num(t.maxDeviation), + at: num(t.at), over: num(t.over), perChunk: Array.isArray(t.perChunk) ? t.perChunk.map((x) => num(x)) : [], + }, + }; + })() + : {}), + ...(c.sourceGaps && typeof c.sourceGaps === "object" + ? (() => { + const g = obj(c.sourceGaps); + return { sourceGaps: { count: num(g.count), totalSeconds: num(g.totalSeconds), largest: num(g.largest), largestAt: num(g.largestAt) } }; + })() + : {}), + ...(c.chunkMeans && typeof c.chunkMeans === "object" + ? (() => { + const m = obj(c.chunkMeans); + const w = m.worst && typeof m.worst === "object" ? obj(m.worst) : null; + return { + chunkMeans: { + count: num(m.count), + sigmaK: num(m.sigmaK), + margin: num(m.margin), + worst: w + ? { + chunk: num(w.chunk), plane: strOr(w.plane), mean: num(w.mean), centre: num(w.centre), floor: num(w.floor), + ...(typeof w.joinAt === "number" ? { joinAt: w.joinAt } : {}), + } + : null, + exempt: Array.isArray(m.exempt) ? m.exempt.map((x) => ({ chunk: num(obj(x).chunk), plane: strOr(obj(x).plane), why: strOr(obj(x).why) })) : [], + }, + }; + })() + : {}), }, chunks: num(r.chunks), }; diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts @@ -226,7 +226,326 @@ test("E1: a good copy with two kinds of picture passes; a short defect in either } // Five-minute stretches alternating all hour long. assert.equal(judgeWholeFile({ frames: make(0, true), tiles: [], chromaU: ones, chromaV: ones }, t).ok, true); - // The whole-file floor of the round before rejected the 20% case. + // Judged as one neighbourhood (the whole-file floor of the round before), + // the 20% case fails: one stretch is one run, not a recurring kind (G1). const whole = judgeWholeFile({ frames: make(0.2), tiles: [], chromaU: ones, chromaV: ones }, { ...t, windowFrames: n }); assert.equal(whole.ok, false); + assert.equal(whole.lowerState, null); +}); + +// F-a: fast switching. A share (0.995) and a webcam (0.96) every 20 s fill each +// half-window half and half, and its floor flipped with the majority. The file's +// recurring lower kind of picture lends its floor to a neighbourhood holding a +// fifth of its frames at that level; a second's dip in a steady stretch does not. +test("F-a: a good copy switching every 20, 60 or 90 s passes; a short dip still fails", async () => { + const { judgeWholeFile } = await import("./compactMedia-server"); + const fps = 30; + const n = 3600 * fps; + const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.0004; + const t = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, expectedFrames: n, fps, chromaMinFrame: 0.9, chromaMeanFloor: 0.97, windowFrames: 120 * fps }; + const ones = new Float32Array(n).fill(1); + const judge = (f: Float32Array) => judgeWholeFile({ frames: f, tiles: [], chromaU: ones, chromaV: ones }, t); + const alternate = (period: number) => Float32Array.from({ length: n }, (_, i) => (Math.floor(i / fps / period) % 2 ? 0.96 : 0.995) + jitter(i)); + const dip = (f: Float32Array, at: number, score: number) => (f.fill(score, at * fps, (at + 1) * fps), f); + // 60 s: a webcam closing the file's last minute (it has no block after it). + for (const period of [20, 60, 90]) { + const v = judge(alternate(period)); + assert.equal(v.ok, true, `${period} s: ${v.why}`); + assert.ok(v.lowerState && Math.abs(v.lowerState.share - 0.5) < 0.02, JSON.stringify(v.lowerState)); + // A second at 0.92 inside a webcam stretch is below the webcam's own floor. + const w = judge(dip(alternate(period), period + 2, 0.92)); + assert.equal(w.ok, false, `${period} s dip`); + assert.match(w.why!, /below its neighbourhood's floor/); + } + // A screen share with one 12-minute webcam stretch: a second at 0.95 inside the + // share keeps the share's floor (the neighbourhood is not a fifth webcam). + const once = Float32Array.from({ length: n }, (_, i) => (i >= 1000 * fps && i < 1720 * fps ? 0.96 : 0.995) + jitter(i)); + assert.equal(judge(once).ok, true); + const d = judge(dip(once, 300, 0.95)); + assert.equal(d.ok, false); + assert.match(d.why!, /below its neighbourhood's floor 0\.96/); + // A file of one kind of picture has no lower state: a 20 s stretch at 0.95 fails. + const plain = Float32Array.from({ length: n }, (_, i) => 0.995 + jitter(i)); + assert.equal(judge(plain).lowerState, null); + plain.fill(0.95, 1000 * fps, 1020 * fps); + assert.equal(judge(plain).ok, false); +}); + +// G1: only SCENE STRUCTURE makes a lower kind of picture. A periodic fault of a +// few seconds (a broken setting, a per-GOP fault) used to manufacture its own +// lower state and pass; runs under 8 s never count, and a run on a chunk join +// never counts. G2: every chunk against the others. +test("G: a periodic short fault fails, a bad chunk fails, real scene structure passes", async () => { + const { judgeWholeFile } = await import("./compactMedia-server"); + const fps = 30; + const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.0004; + const base = { minFrame: 0.9, meanFloor: 0.97, sigmaK: 8, sigmaMinMargin: 0.03, tileRunFrames: 2, fps, chromaMinFrame: 0.9, chromaMeanFloor: 0.97, windowFrames: 120 * fps }; + const CH = 300 * fps; // 5-minute chunks + const make = (seconds: number, at: (t: number) => number) => Float32Array.from({ length: seconds * fps }, (_, i) => at(i / fps) + jitter(i)); + const judge = (f: Float32Array, o: { u?: Float32Array; chunks?: boolean } = {}) => { + const ones = new Float32Array(f.length).fill(0.99); + const chunkStarts = Array.from({ length: Math.ceil(f.length / CH) }, (_, k) => k * CH); + return judgeWholeFile({ frames: f, tiles: [], chromaU: o.u ?? ones, chromaV: ones }, { ...base, expectedFrames: f.length, ...(o.chunks === false ? {} : { chunkStarts }) }); + }; + const H = 3600; + // The reviewer's periodic faults (one kind of picture): every one fails again. + for (const [on, period, lvl] of [[2, 8, 0.95], [2, 8, 0.93], [3, 10, 0.93], [2, 8, 0.91], [1, 4, 0.94]] as const) { + const v = judge(make(H, (t) => (t % period < on ? lvl : 0.995))); + assert.equal(v.ok, false, `${on}/${period} at ${lvl}`); + assert.equal(v.lowerState, null); + } + // Good copies: alternation every 10/20/60/90 s, a webcam opening or closing + // the file, a 20/30/45% webcam stretch, a game hour across several chunks. + for (const p of [10, 20, 60, 90]) { + const v = judge(make(H, (t) => (Math.floor(t / p) % 2 ? 0.96 : 0.995))); + assert.equal(v.ok, true, `alternating ${p} s: ${v.why}`); + assert.ok(v.chunks && v.chunks.worst === null); + } + assert.equal(judge(make(H, (t) => (t >= H - 50 ? 0.96 : 0.995))).ok, true); + assert.equal(judge(make(H, (t) => (t < 50 ? 0.96 : 0.995))).ok, true); + for (const share of [0.2, 0.3, 0.45]) assert.equal(judge(make(H, (t) => (t >= 1000 && t < 1000 + share * H ? 0.96 : 0.995))).ok, true, `${share}`); + const game = judge(make(4 * H, (t) => (t >= 4410 && t < 8010 ? 0.975 : 0.995))); + assert.equal(game.ok, true, game.why); + assert.ok(game.chunks!.exempt.some((x) => x.why === "no step at its joins")); + // 1 s dips still fail. + assert.equal(judge(make(H, (t) => (t >= 300 && t < 301 ? 0.95 : 0.995))).ok, false); + assert.equal(judge(make(H, (t) => (t >= 1022 && t < 1023 ? 0.92 : Math.floor(t / 20) % 2 ? 0.96 : 0.995))).ok, false); + // Bad chunks (20 chunks, one kind of picture): 1, 2, 4, 6 at 0.96/0.94/0.92 fail on the chunk check. + for (const lvl of [0.96, 0.94, 0.92]) { + for (const bad of [1, 2, 4, 6]) { + const at = new Set(Array.from({ length: bad }, (_, k) => 2 + k * 3)); + const v = judge(make(20 * 300, (t) => (at.has(Math.floor(t / 300)) ? lvl : 0.995))); + assert.equal(v.ok, false, `${bad} at ${lvl}`); + assert.match(v.why!, /^chunk (3|6|9|12|15|18) of 20 .* on Y, below the other chunks' floor/); + // Without the chunk joins (the round before): a stretch longer than the window passed. + if (lvl !== 0.92) assert.equal(judge(make(20 * 300, (t) => (at.has(Math.floor(t / 300)) ? lvl : 0.995)), { chunks: false }).ok, true); + } + } + // Six bad chunks would be a tenth of the file in 3+ runs — a lower state of + // their own — but their runs sit on chunk joins: refused. + const six = judge(make(20 * 300, (t) => ([2, 5, 8, 11, 14, 17].includes(Math.floor(t / 300)) ? 0.96 : 0.995))); + assert.match(six.lowerStateRefused ?? "", /chunk join/); + // A chunk worse only in colour fails on that plane. + const f = make(20 * 300, () => 0.995); + const u = Float32Array.from({ length: f.length }, (_, i) => (Math.floor(i / CH) === 7 ? 0.965 : 0.99)); + const c = judge(f, { u }); + assert.equal(c.ok, false); + assert.match(c.why!, /^chunk 8 of 20 .* on U/); + // Bad chunks inside fast switching: the bad run merges with a webcam run at + // one end and sits on the join at the other — not a scene; it fails. + const alt = judge(make(20 * 300, (t) => (Math.floor(t / 300) === 6 ? 0.93 : Math.floor(t / 20) % 2 ? 0.96 : 0.995))); + assert.equal(alt.ok, false); + assert.match(alt.why!, /^chunk 7 of 20/); +}); + +// THE SOURCE'S TIMESTAMPS (review, the first real run): the helpers. +test("timestamps: dropped frames found, chunk starts on even indexes, the copy's times derived and compared", async () => { + const { planChunks, expectedCopyPts, compareCopyPts, sourceGaps, nominalFps, concatList } = await import("./compactMedia-server"); + // 60 fps, 20 s; 31 frames dropped at 5 s (odd) and 5 at the very end. + const all: number[] = []; + for (let i = 0; i < 1200; i += 1) if (!(i >= 300 && i <= 330) && !(i >= 1190 && i <= 1194)) all.push(i / 60); + const pts = Float64Array.from(all); + assert.ok(Math.abs(nominalFps(pts)! - 60) < 1e-9); + // A container's ticks: a 30 fps mkv (ms), 60 fps in 1/15360 s, and a true 59.94. + const ticks = (rate: number, tick: number) => Float64Array.from({ length: 600 }, (_, i) => Math.round(i / rate / tick) * tick); + assert.equal(nominalFps(ticks(30, 0.001)), 30); + assert.equal(nominalFps(ticks(60, 1 / 15360)), 60); + assert.ok(Math.abs(nominalFps(ticks(60000 / 1001, 1 / 90000))! - 60000 / 1001) < 1e-9); + const g = sourceGaps(pts); + assert.equal(g.count, 2); + assert.ok(Math.abs(g.largest - 32 / 60) < 1e-9 && Math.abs(g.largestAt - 299 / 60) < 1e-9, JSON.stringify(g)); + assert.ok(Math.abs(g.totalSeconds - (31 + 5) / 60) < 1e-9); + // Keyframes every 45 FRAMES of the file (so some fall on odd indexes). + const keyframes = all.filter((_, i) => i % 45 === 0); + const plan = planChunks({ pts, keyframes }, 4, 30, 60); + const indexOf = (t: number) => all.findIndex((x) => Math.abs(x - t) < 1e-9); + assert.ok(plan.length >= 3); + for (const c of plan) assert.equal(indexOf(c.from) % 2, 0, `chunk at ${c.from}`); + // The time grid would have taken a keyframe at an ODD index after the gap. + const oddOnTimeGrid = keyframes.find((k) => k > 6 && Math.abs(k * 30 - Math.round(k * 30)) < 0.02 && indexOf(k) % 2 === 1); + assert.ok(oddOnTimeGrid !== undefined, "the case the index rule exists for"); + // The copy's expected times: every other source frame, chunk by chunk. + const exp = expectedCopyPts(pts, plan, 2, null); + assert.equal(exp.length, plan.reduce((n, c) => n + c.expectedFrames, 0)); + assert.ok(exp.every((t, i) => t === pts[2 * i])); + // A copy at those times passes; one re-timed to 30 fps fails from the gap on. + assert.equal(compareCopyPts(exp, Float64Array.from(exp), 0.001).over, 0); + const cfr = exp.map((_, i) => i / 30); + const bad = compareCopyPts(exp, cfr, 0.001, [0, 100]); + // Off by both gaps at the end (the error only grows). + assert.ok(bad.over > 0 && Math.abs(bad.maxDeviation - 36 / 60) < 1 / 30, JSON.stringify({ ...bad, perChunk: undefined })); + assert.ok(bad.perChunk[0] < 0.001 && bad.perChunk[1] > 0.5); + // The concat list: each chunk's span to the next, so each starts at its time. + assert.equal(concatList(["/a/x.mp4", "/a/y.mp4"], [4.25]), "file '/a/x.mp4'\nduration 4.250000\nfile '/a/y.mp4'\n"); +}); + +// Review G2: a harder segment starting AT a chunk join is the source's doing +// when the source's own picture changes there; a bad chunk's source does not. +test("G2: a segment starting at a join is exempt when the source changes there; a bad chunk is not", async () => { + const { judgeChunks } = await import("./compactMedia-server"); + const fps = 30; + const CH = 300 * fps; + const N = 20; + const starts = Array.from({ length: N }, (_, i) => i * CH); + const jitter = (i: number) => (((i * 7919) % 11) - 5) * 0.0002; + const at = (seg: (i: number) => boolean, hard: number, easy = 0.995) => Float32Array.from({ length: N * CH }, (_, i) => (seg(i) ? hard : easy) + jitter(i)); + const ones = new Float32Array(N * CH).fill(0.99); + const o = { sigmaK: 4, margin: 0.02, fps }; + for (const offset of [0, 1, 2]) { + // A 25-minute game segment from chunk 7's join (+offset s): its picture detail is twice the talk's. + const seg = (i: number) => i >= 7 * CH + offset * fps && i < 7 * CH + offset * fps + 1500 * fps; + const y = at(seg, 0.965); + const detail = at(seg, 20, 10); + const without = judgeChunks({ Y: y, U: ones, V: ones }, starts, null, o); + assert.equal(without.ok, false, `offset ${offset}: without the source's detail it fails as before`); + const v = judgeChunks({ Y: y, U: ones, V: ones }, starts, null, o, detail); + assert.equal(v.ok, true, `offset ${offset}: ${v.why}`); + assert.ok(v.exempt.some((e) => e.why === "the source changes at its join"), JSON.stringify(v.exempt)); + } + // A bad chunk: the copy drops at its joins, the source's picture does not change. + const bad = (i: number) => i >= 7 * CH && i < 8 * CH; + const v = judgeChunks({ Y: at(bad, 0.96), U: ones, V: ones }, starts, null, o, Float32Array.from({ length: N * CH }, () => 10)); + assert.equal(v.ok, false); + assert.match(v.why!, /^chunk 8 of 20 \(2100\.0–2400\.0 s\).*join at 2100\.0 s, where the source's own picture does not change\. It may still be a segment .* another chunkMinutes puts the joins elsewhere/); + assert.equal(v.worst?.joinAt, 7 * CH); +}); + +// Review G4, then H1: the kept frames by TIME, by ONE constant rule — a frame +// when at least keepMinStep has passed since the last kept one. The rule is +// the same in ffmpeg's select (constant size, whatever the file) and in the +// code that pairs frames, and holds on millisecond-rounded timestamps. +test("H1: kept frames by a constant rule, exact on ms-rounded 60 fps, a gap, a choppy pattern and a 30 fps stretch", async () => { + const { keepMinStep, keptSourceFrames, keepSelect, planChunks, expectedCopyPts } = await import("./compactMedia-server"); + const min = keepMinStep(30, 60); + // Off any millisecond and any 90 kHz tick, between one 60 fps step and two. + assert.ok(min > 0.017 && min < 0.0333 && Math.abs(min * 1000 - Math.round(min * 1000)) > 0.1, String(min)); + const ms = (x: number) => Math.round(x * 1000) / 1000; + const keptOf = (t: number[]) => { + const mask = keptSourceFrames(Float64Array.from(t), min); + return t.filter((_, i) => mask[i]); + }; + // 60 fps rounded to the millisecond: steps 16, 17, 17 — exactly every other frame. + const t60 = Array.from({ length: 1200 }, (_, i) => ms(i / 60)); + assert.deepEqual(keptOf(t60), t60.filter((_, i) => i % 2 === 0)); + // One 67 ms gap (frames 600–602 missing): every other before, the next frame after, every other from there. + const gap = t60.filter((_, i) => i < 600 || i > 602); + const kg = keptOf(gap); + assert.ok(kg.includes(ms(603 / 60)), "the first frame after the gap"); + assert.deepEqual(kg.filter((x) => x > 10.04), gap.filter((x) => x >= ms(603 / 60)).filter((_, k) => k % 2 === 0)); + // A truly choppy pattern: no two kept closer than the rule, none skipped that it allows. + let seed = 7; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + const choppy: number[] = []; + for (let x = 0; x < 60; x += 0.006 + rnd() * 0.045) choppy.push(ms(x)); + const unique = [...new Set(choppy)]; + const kc = new Set(keptOf(unique)); + let last = -Infinity; + for (const x of unique) { + if (kc.has(x)) { + assert.ok(x - last >= min - 1e-9, `${last} -> ${x}`); + last = x; + } else assert.ok(x - last < min, `${x} could be kept`); + } + // A 30 fps stretch in a 60 fps file keeps every frame of it. + const mixed = t60.filter((_, i) => !(i >= 300 && i < 600 && i % 2 === 1)); + const km = keptOf(mixed); + assert.deepEqual(km.filter((x) => x >= 5 && x < 10), mixed.filter((x) => x >= 5 && x < 10)); + // ffmpeg's select is one constant expression, the same for every chunk and every file. + const sel = keepSelect(min); + assert.match(sel, /^isnan\(prev_selected_t\)\+gte\(t-prev_selected_t,0\.0\d+\)$/); + // A 5.8-hour ms-rounded 60 fps scan with one gap: the plan is cheap and every select is that expression. + const n = 1_254_927; + const big = new Float64Array(n); + for (let i = 0; i < n; i += 1) big[i] = ms(0.016 + (i < n - 2 ? i : i + 3) / 60); + const keyframes: number[] = []; + for (let i = 0; i < n; i += 120) keyframes.push(big[i]); + const plan = planChunks({ pts: big, keyframes }, 600, 30, 60, { minStep: min }); + const mask = keptSourceFrames(big, min); + let total = 0; + for (const c of plan) { + assert.equal(c.select, sel); + assert.equal(mask[c.fromIndex!], 1, `chunk ${c.index} starts on a kept frame`); + total += c.expectedFrames; + } + assert.equal(total, mask.reduce((x, y) => x + y, 0)); + assert.ok(Math.abs(total - Math.ceil(n / 2)) <= 1, String(total)); + const exp = expectedCopyPts(big, plan, 2, null, { minStep: min }); + assert.equal(exp.length, total); +}); + +test("G1: what a decode's stderr means", async () => { + const { classifyDecodeStderr } = await import("./compactMedia-server"); + const c = classifyDecodeStderr( + [ + "[null @ 0x55dabfdf1140] Application provided invalid, non monotonically increasing dts to muxer in stream 0: 600 >= 600", + "[h264 @ 0x5] error while decoding MB 12 7, bytestream -5", + "[h264 @ 0x5] concealing 120 DC, 120 AC, 120 MV errors in P frame", + "[dav1d @ 0x6] Error parsing OBU data", + "Something ffmpeg says that is neither", + ].join("\n"), + ); + assert.equal(c.benign.length, 1); + assert.equal(c.fatal.length, 3); + assert.deepEqual(c.notes, ["Something ffmpeg says that is neither"]); +}); + +// Review H2: the source excuses a chunk's drop only with a SUSTAINED step +// against its neighbour, toward harder picture; a drift excuses nothing. +test("H2: only a sustained step to harder source picture at the join excuses a chunk", async () => { + const { judgeChunks } = await import("./compactMedia-server"); + const FPS = 30; + const CH = 600 * FPS; + const N = 35; + const starts = Array.from({ length: N }, (_, i) => i * CH); + let seed = 9; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + const mk = (fn: (i: number) => number, noise: number) => Float32Array.from({ length: N * CH }, (_, i) => fn(i) + (rnd() - 0.5) * noise); + const chunkOf = (i: number) => Math.floor(i / CH); + const g = new Float32Array(N * CH).fill(0.99); + const judge = (y: Float32Array, det: Float32Array) => judgeChunks({ Y: y, U: g, V: g }, starts, null, { sigmaK: 4, margin: 0.02, fps: FPS }, det); + const bad = mk((i) => (chunkOf(i) === 17 ? 0.95 : 0.995), 0.004); + // Fails: constant detail; a change at only one of its two joins; a static + // source; a near-flat noisy one; a dark one drifting 15 % every 10 s; one + // that gets EASIER (less detail) in the chunk. + for (const [label, det] of [ + ["constant", mk(() => 20, 0.4)], + ["one join", mk((i) => (i >= 17 * CH ? 26 : 20), 0.4)], + ["static", new Float32Array(N * CH)], + ["near-flat noisy", mk(() => 0.3, 0.3)], + ["drifting", mk((i) => 2 * (1 + 0.15 * Math.sin(((i / FPS) * 2 * Math.PI) / 20)), 0.6)], + ["easier", mk((i) => (chunkOf(i) === 17 ? 14 : 20), 0.4)], + ] as const) { + const v = judge(bad, det); + assert.equal(v.ok, false, label); + assert.ok(!v.exempt.some((e) => e.why === "the source changes at its join"), `${label}: ${JSON.stringify(v.exempt)}`); + } + // Passes: a harder segment from a join where the source's picture steps up and stays up. + const good = judge(mk((i) => (i >= 17 * CH && i < 20 * CH ? 0.965 : 0.995), 0.004), mk((i) => (i >= 17 * CH && i < 20 * CH ? 30 : 20), 0.4)); + assert.equal(good.ok, true, good.why); + assert.ok(good.exempt.some((e) => e.why === "the source changes at its join")); +}); + +// Review H4: more decoder damage is fatal. +test("H4: frame-num gaps, missing refs, unknown OBUs, partial files and AAC damage are fatal", async () => { + const { classifyDecodeStderr } = await import("./compactMedia-server"); + const fatal = [ + "[h264 @ 0x55] Frame num gap 3 1", + "[hevc @ 0x55] Could not find ref with POC 12", + "[av1 @ 0x55] Unknown OBU type 9", + "[mov,mp4,m4a,3gp,3g2,mj2 @ 0x55] stream 0, offset 0x1234: partial file", + "[aac @ 0x55] Reserved bit set.", + "[aac @ 0x55] Prediction is not allowed in AAC-LC.", + "[aac @ 0x55] channel element 1.0 is not allocated", + "[aac @ 0x55] Input buffer exhausted before END element found", + "[aac @ 0x55] Number of bands (20) exceeds limit (14).", + "[aac @ 0x55] Inconsistent channel configuration", + "[h264 @ 0x55] co located POCs unavailable", + "[h264 @ 0x55] reference picture missing during reorder", + ]; + const notes = ["[av1 @ 0x55] Your platform doesn't support hardware accelerated AV1 decoding.", "[h264 @ 0x55] Increasing reorder buffer to 1"]; + const benign = ["[av1 @ 0x55] Non-monotonic DTS in output stream; previous: 5, current: 5"]; + const c = classifyDecodeStderr([...fatal, ...notes, ...benign].join("\n")); + assert.deepEqual(c.fatal, fatal); + assert.deepEqual(c.notes, notes); + assert.deepEqual(c.benign, benign); }); diff --git a/common/lib/savedVideoCompaction.ts b/common/lib/savedVideoCompaction.ts @@ -56,6 +56,9 @@ export type SavedVideoCompactionSettings = { wholeFileChromaMin: number; wholeFileChromaMean: number; wholeFileWindowSeconds: number; + wholeFileLowerRunSeconds: number; + wholeFileChunkSigmaK: number; + wholeFileChunkMargin: number; availabilityMaxAgeDays: number; dropOriginal: CompactionDropOriginal; }; @@ -88,6 +91,9 @@ export const DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS: SavedVideoCompactionSettin wholeFileChromaMin: 0.9, wholeFileChromaMean: 0.97, wholeFileWindowSeconds: 120, + wholeFileLowerRunSeconds: 8, + wholeFileChunkSigmaK: 4, + wholeFileChunkMargin: 0.02, availabilityMaxAgeDays: 7, dropOriginal: "keep", }; @@ -125,6 +131,11 @@ export const SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS: FieldDocs<SavedVideoCom wholeFileChromaMean: "The colour planes' mean must reach this. Default 0.97 (good copy: 0.9986).", wholeFileWindowSeconds: "The NEIGHBOURHOOD the relative floor is taken over: each frame is judged against the frames in the half-window just before it and just after it (the lower of their two floors), so a stream alternating two kinds of picture (a webcam, a screen share) is judged stretch by stretch, not by the file's dominant mode. A short defect inside a steady stretch has that stretch on both sides and falls below it. A degraded stretch longer than the window looks steady to it: such a stretch is caught by the absolute per-frame floor, the tile grid, the mean floor, and the VMAF excerpts, one at least every window across the whole file. Default 120 s; 5–3600.", + wholeFileLowerRunSeconds: + "A file that keeps coming back to a lower-scoring kind of picture (a webcam between screen shares) judges a neighbourhood that is a fifth or more that kind by those frames alone. Only SCENES count toward that kind: runs of at least this many seconds below the split, at least 3 of them, at least a tenth of the file, and none beginning or ending on a chunk join (a bad chunk's signature). Shorter runs are judged by the stretch around them, so a fault of a few seconds every GOP never passes as a kind of picture. Default 8 (longer than one 5 s GOP, with margin); 1–600.", + wholeFileChunkSigmaK: + "EVERY CHUNK AGAINST THE OTHERS: each chunk's mean (grey, U and V) must reach the other chunks' median − max(this × their robust spread, wholeFileChunkMargin). A chunk below it fails unless the source explains it: most of it is the file's recurring lower kind of picture, or its joins show no drop (a harder scene runs across chunks; a bad chunk changes level at its joins). Default 4.", + wholeFileChunkMargin: "The least the per-chunk floor sits under the other chunks' median. Default 0.02.", 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: @@ -172,6 +183,9 @@ export function sanitizeSavedVideoCompaction(value: unknown): SavedVideoCompacti wholeFileChromaMin: clampNum(r.wholeFileChromaMin, d.wholeFileChromaMin, 0, 1), wholeFileChromaMean: clampNum(r.wholeFileChromaMean, d.wholeFileChromaMean, 0, 1), wholeFileWindowSeconds: clampNum(r.wholeFileWindowSeconds, d.wholeFileWindowSeconds, 1, 3600), + wholeFileLowerRunSeconds: clampNum(r.wholeFileLowerRunSeconds, d.wholeFileLowerRunSeconds, 1, 600), + wholeFileChunkSigmaK: clampNum(r.wholeFileChunkSigmaK, d.wholeFileChunkSigmaK, 1, 100), + wholeFileChunkMargin: clampNum(r.wholeFileChunkMargin, d.wholeFileChunkMargin, 0, 1), availabilityMaxAgeDays: clampNum(r.availabilityMaxAgeDays, d.availabilityMaxAgeDays, 0, 365), dropOriginal: (COMPACTION_DROP_ORIGINAL as readonly unknown[]).includes(r.dropOriginal) ? (r.dropOriginal as CompactionDropOriginal) diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -169,8 +169,30 @@ - The whole-file comparison scores the colour (U and V planes) every frame too: a hue shift or chroma-only noise fails it, and "after-verify" needs both the luma and the colour record. Its relative floor uses the median and a robust spread over each frame's own two-minute neighbourhood (`wholeFileWindowSeconds`), so a stream alternating - two kinds of picture passes; a VMAF excerpt is laid at least every window. A negative plane score is read as - one. Clearing a marker never removes one written after the check. + two kinds of picture passes; a VMAF excerpt is laid at least every window. A file that keeps coming back to a + lower-scoring kind of picture (`lowerState` in the pointer) judges a neighbourhood that is a fifth or more that + kind by those frames alone, so switching every 20 s passes too; only scenes count as such a kind (runs of 8 s + or more, `wholeFileLowerRunSeconds`, at least 3, none on a chunk join), so a fault of a few seconds every GOP + still fails. Every chunk is compared with the others (grey, U, V; `checks.chunkMeans`): a chunk evenly worse + than the rest fails unless the source explains it, and "after-verify" needs that record too. A frame closing + the file is judged by the last window. A negative plane score is read as one. Clearing a marker never removes + one written after the check. + - The copy KEEPS THE SOURCE'S TIMESTAMPS. A live recording's dropped frames stay gaps: 60 → 30 keeps every other + frame at its own time, chunks start on even frame indexes and join at their source times, and keyframes fall + every 5 s of time. The check is every frame's time against its source frame's (`checks.timestamps`, 1 ms), + not frames ÷ rate, which failed the first real run's correct copy by a tail gap. The recording's dropped frames + are recorded (`checks.sourceGaps`). A source with none decodes frame for frame as before. The frames kept are + decided by TIME, by one constant rule (`select` of a few dozen characters; the same rule in the checks), so a + stretch where the recording ran at 30 fps keeps 30 fps and millisecond-rounded 60 fps keeps exactly every + other frame. The full decode keeps each stream's time base, decodes the video alone and then the audio + against the source's own, and fails only on damage. A chunk that drops at a join where the source's own + picture steps to harder and stays harder (a segment starting there) is exempt, and the failure message names + the join and what to do. On a recording too choppy for an even window, the window cuts are skipped and named + (`checks.skipped`); "after-verify" never drops after a skipped check. + - A failed check KEEPS THE ENCODE (chunks and the joined copy, never active): `"reverify": true` checks it again + without encoding (a chunk whose own content failed is encoded again), and `kept-failed-encodes` lists and + clears them, orphaned ones included. Unpersist and the prune remove a video's scratch with its pointer. The dry run says when one exists and how big it is. Every check runs and is recorded even after + one fails (`failed.json` `failures`). - **ROLLBACK: do not roll the editor back past this release while `pnpm ops get kept-originals` lists anything.** An older editor does not know `"keptAs": "original"` / `"former-original"`, would treat them as ordinary alternates, and could prune or drop the only original. 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?, belowThreshold?, crf?, preset?, maxFps?, chunkMinutes? +// dryRun?, retryFailed?, reverify?, 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 }] } @@ -27,6 +27,12 @@ export const dynamic = "force-dynamic"; // 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. +// +// A video whose last run FAILED A CHECK keeps its encode (the chunks and the +// joined copy, in its scratch, never active): `"reverify": true` checks it +// again without encoding (a chunk whose own content failed is encoded again), +// `"retryFailed": true` encodes it all again; `kept-failed-encodes` lists and +// clears them. function optNumber(body: OpsBody, key: string, lo: number, hi: number): number | undefined { const v = body[key]; if (v === undefined) return undefined; @@ -39,7 +45,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", "belowThreshold", "crf", "preset", "maxFps", "chunkMinutes"], + ["items", "select", "slugs", "dryRun", "retryFailed", "reverify", "belowThreshold", "crf", "preset", "maxFps", "chunkMinutes"], async (body) => { const select = optBool(body, "select") === true; const crf = optNumber(body, "crf", 20, 55); @@ -52,6 +58,7 @@ export async function POST(request: Request) { // 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, + reverify: optBool(body, "reverify") ?? false, belowThreshold: optBool(body, "belowThreshold") ?? false, overrides: { ...(crf !== undefined ? { crf } : {}), diff --git a/editor/app/api/ops/kept-failed-encodes/route.ts b/editor/app/api/ops/kept-failed-encodes/route.ts @@ -0,0 +1,31 @@ +import { NextResponse } from "next/server"; +import { keptFailedEncodesAction } from "../../../saved-videos/compactActions"; +import { ops, reqSlug, reqVideoId, type OpsBody, OpsInputError } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST {} | { clear: { slug, id } } +// -> { ok, rows: [{ slug, id, dir, at, reason, failedChunks, kept }], bytes, cleared? } +// +// The encodes kept after a compaction FAILED A CHECK +// (controller/compactSavedVideos.ts): each video's `.compact-scratch` holds +// the chunks and the joined copy (`failed-copy.*`, never the active copy) and +// a failed.json saying what failed. `compact-saved-videos` with +// `"reverify": true` checks one again without encoding; `clear` removes one +// video's (refused while its compaction runs). +function optClear(body: OpsBody): { slug: string; id: string } | undefined { + if (body.clear === undefined) return undefined; + if (!body.clear || typeof body.clear !== "object" || Array.isArray(body.clear)) { + throw new OpsInputError('"clear" must be { "slug", "id" }'); + } + const c = body.clear as OpsBody; + return { slug: reqSlug(c, "slug"), id: reqVideoId(c, "id") }; +} + +export async function POST(request: Request) { + return ops(request, ["clear"], async (body) => { + const clear = optClear(body); + const res = await keptFailedEncodesAction(clear ? { clear } : {}); + return NextResponse.json({ ok: true, ...res }); + }); +} 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.reverify === true ? { reverify: true } : {}), ...(p.belowThreshold === true ? { belowThreshold: true } : {}), }); }, diff --git a/editor/app/saved-videos/compactActions.ts b/editor/app/saved-videos/compactActions.ts @@ -7,9 +7,11 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { clearCompactionMarker, + clearKeptFailedEncode, compactSavedVideos, effectiveCompactionSettings, listCompactionMarkers, + listKeptFailedEncodes, listKeptOriginals, listCompactionReview, planCompaction, @@ -62,7 +64,7 @@ function settingsFor(overrides: CompactOverrides): SavedVideoCompactionSettings export async function compactChannelVideosAction( slug: string, ids: string[], - opts: { mode: "explicit" | "select"; overrides?: CompactOverrides; retryFailed?: boolean; belowThreshold?: boolean }, + opts: { mode: "explicit" | "select"; overrides?: CompactOverrides; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean }, ): Promise<StreamActionResult> { const wanted = [...new Set(ids)]; if (wanted.length === 0) return { ok: false, error: "No video ids to compact." }; @@ -83,6 +85,7 @@ export async function compactChannelVideosAction( mode: opts.mode, ...overrides, ...(opts.retryFailed ? { retryFailed: true } : {}), + ...(opts.reverify ? { reverify: true } : {}), ...(opts.belowThreshold ? { belowThreshold: true } : {}), }, }, @@ -95,6 +98,7 @@ export async function compactChannelVideosAction( items: wanted.map((id) => ({ slug, id })), mode: opts.mode, ...(opts.retryFailed ? { retryFailed: true } : {}), + ...(opts.reverify ? { reverify: true } : {}), ...(opts.belowThreshold ? { belowThreshold: true } : {}), onLog, signal, @@ -121,6 +125,7 @@ export async function compactSavedVideosAction(input: { slugs?: string[]; dryRun?: boolean; retryFailed?: boolean; + reverify?: boolean; belowThreshold?: boolean; overrides?: CompactOverrides; }): Promise<CompactSavedVideosActionResult> { @@ -139,6 +144,7 @@ export async function compactSavedVideosAction(input: { ...(input.select ? { select: true } : {}), ...(input.slugs?.length ? { slugs: input.slugs } : {}), ...(input.retryFailed ? { retryFailed: true } : {}), + ...(input.reverify ? { reverify: true } : {}), ...(input.belowThreshold ? { belowThreshold: true } : {}), }); if (input.dryRun) return { ok: true, dryRun: true, plan }; @@ -156,6 +162,7 @@ export async function compactSavedVideosAction(input: { mode: input.select ? "select" : "explicit", ...(input.overrides ? { overrides: input.overrides } : {}), ...(input.retryFailed ? { retryFailed: true } : {}), + ...(input.reverify ? { reverify: true } : {}), ...(input.belowThreshold ? { belowThreshold: true } : {}), }); } catch (e) { @@ -233,6 +240,14 @@ export async function keptOriginalsList(opts: { slug?: string } = {}) { return { rows, notAnswering: notAnswering.sort() }; } +// The failed encodes kept in the store (never active), and clearing one. +export async function keptFailedEncodesAction(opts: { clear?: CompactItem } = {}) { + const paths = getPaths(); + const cleared = opts.clear ? { ...opts.clear, ...(await clearKeptFailedEncode(paths, opts.clear)) } : null; + const rows = await listKeptFailedEncodes(paths); + return { rows, bytes: rows.reduce((n, r) => n + (r.kept?.bytes ?? 0), 0), ...(cleared ? { cleared } : {}) }; +} + // The `.compacting.json` markers, and clearing a stale one. export async function compactionMarkersAction(opts: { clear?: CompactItem } = {}) { const paths = getPaths(); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -509,7 +509,7 @@ 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? (select: a dry run by default), retryFailed?, belowThreshold?, + // dryRun? (select: a dry run by default), retryFailed?, reverify?, belowThreshold?, // crf?, preset?, maxFps?, chunkMinutes?); and a // person's review of one, which lets a gone video's original be dropped // ({slug, id, note?}). @@ -518,6 +518,8 @@ const ACTIONS = [ // The "being compacted" markers, live or stale, and clearing a stale one // ({} | {clear: {slug, id}}). "compaction-markers", + // The failed encodes kept for a re-verify, and clearing one ({} | {clear: {slug, id}}). + "kept-failed-encodes", // Write transcript.cues.json from each video's raw transcript ({slug, ids?, // force?}) — what a reader with no index build wants. "build-cues", @@ -1906,7 +1908,9 @@ export function usage() { " \"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', + ' "retryFailed": true encodes again one whose last checks failed;', + ' "reverify": true checks its KEPT encode again without encoding (a chunk', + ' whose own content failed is encoded again). 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", @@ -1915,6 +1919,12 @@ export function usage() { " checked on its platform (get compaction-review). There is no backup of", " the store: after a drop the compacted copy is the only copy.", "", + 'kept-failed-encodes lists the encodes kept after a failed check (in each', + " video's .compact-scratch, never active: chunks and the joined copy, their", + ' size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused', + ' while its compaction runs). compact-saved-videos "reverify": true re-checks', + " one without encoding.", + "", 'compaction-markers lists the "being compacted" markers (.compacting.json),', ' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale', " one; a live one is refused (cancel its job). Stale ones are also swept at", diff --git a/settings.json.example b/settings.json.example @@ -176,6 +176,9 @@ "wholeFileChromaMin": 0.9, "wholeFileChromaMean": 0.97, "wholeFileWindowSeconds": 120, + "wholeFileLowerRunSeconds": 8, + "wholeFileChunkSigmaK": 4, + "wholeFileChunkMargin": 0.02, "availabilityMaxAgeDays": 7, "dropOriginal": "keep" },