commit e9a0665a1b06a34e0414cfbdeae0e0f7eb7f9cc0
parent 9e69d6247fb55c91902ecc718394f14ec4911186
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 14 Nov 2026 09:46:38 -0500
compact-saved-videos: the copy keeps the source's timestamps, a failed check keeps the encode, and every check reports
The first real run (a 5 h 49 min Kick 1080p60 stream) failed a correct
copy: "the re-encode's video lasts 20915.467 s, the source's 20915.550 s",
with the frame count right. Live recordings drop frames (here 83 ms at the
tail), so frames / 30 is not the source's span. Worse, the encode re-timed
every kept frame onto a constant 30 fps grid, so a frame dropped MID-stream
would have put the picture early against the (untouched) sound from there
on, and nothing but the start was checked.
The encode now keeps every frame's own timestamp:
- 60 -> 30 keeps every other frame by index (select, -fps_mode
passthrough), each at its source time; SVT-AV1 is told the copy's rate
(-svtav1-params fps-num/fps-denom). framestep was tried and refused: it
re-times what it keeps and, after an odd gap, wrote a frame at 6.000 s the
source does not have. Other ratios keep the fps filter's grid, which
repeats a frame across a gap (sync kept).
- a chunk starts on a keyframe whose INDEX in the file is a multiple of the
ratio (after an odd gap the time grid and the index grid part);
- the join puts each chunk at its source time (concat duration = the span to
the next chunk's first frame);
- keyframes fall every 5 s of TIME (-force_key_frames), -g bounding it.
On a source with no dropped frames the copy decodes frame for frame as
before, with the same timestamps.
Verification compares timestamps: every copy frame's pts against its source
frame's, relative to each file's start, within 1 ms (checks.timestamps: the
worst, where, and the worst per chunk - the picture against the sound along
the file, the audio being the source's packet for packet at its times); the
last frame at the source's last kept frame; no gap the kept frames lack. The
recording's dropped frames are recorded (checks.sourceGaps). Each excerpt and
cut starts on a kept frame, away from a gap, and each file is seeked at that
frame's time on ITS OWN command-line timeline: ffmpeg starts an mpegts's
timeline at its video (2.900 s) and the mp4 copy's at its container start
(2.877 s here), and one shared time landed a frame apart. The source's
nominal rate is its typical step (gaps excluded, ticks averaged).
A failed verification no longer deletes the encode: the chunks, state and
the joined copy (failed-copy.*, never active) stay in .compact-scratch.
"reverify": true checks them again without encoding (a chunk whose own
content failed is encoded again); "retryFailed": true or changed settings
encode it all again; kept-failed-encodes lists them with their size and
clears one. The dry run says when one exists and the total held. Every check
now runs and records its result even after one fails (failed.json
"failures"); only a copy that cannot be opened stops the list.
Tests: a 60 fps source with 31 frames dropped at 5 s and a flash and a click
at 7 s compacts with the gap kept, every frame at its source pts, the flash
and the click together after the gap, and a lossless playable remux keeping
the times; the same source encoded the old way fails the timestamp check; a
tail gap (the real run's shape) and a 59.94 source pass; reverify encodes
nothing, or only the failed chunk; retryFailed encodes all; clear removes.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
13 files changed, 932 insertions(+), 127 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, <id>-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/<id>/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` |
| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (<id>-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
-| `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, every other stream and the chapters copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: a pin, an explicit persist, a requested or landed container -- never keep-latest, never persist-kept's override); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate) and is a DRY RUN unless "dryRun": false. A named video the selector would not pick is refused unless "belowThreshold": true (the refusal says how little it saves). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs, or why it is skipped. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true runs one whose last checks failed. One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | |
+| `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": "<file>" reviews the active copy that replaced a former original instead. | |
| `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | |
+| `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,25 @@ 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 every other source frame by index (`select`), each at its source time. 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 keyframe whose index in the file is a multiple of that ratio. After an odd gap the time grid
+ and the index grid part.
+ - 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 +1192,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 +1209,16 @@ 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`:
+- **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;
- - 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 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
@@ -1245,6 +1270,17 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"}
original's better a frame off fails;
- the recording clock (`clock.json`) re-measured against the re-encode and within its tolerance of the old map.
The map is then retargeted (its id kept, so windows cut through it stay current) in the swap's own lock.
+- **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.
+
+ 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.
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,
@@ -29,6 +31,7 @@ import { SavedPointerChangedError, loadSavedVideo, persistSourceVideo, restoreSa
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 +59,43 @@ 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][];
+ // 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("+")})'`] : []),
+ ];
+ 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 +192,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 +331,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 +525,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);
});
});
@@ -976,3 +1082,108 @@ 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);
+ });
+ }
+});
diff --git a/common/controller/compactSavedVideos.ts b/common/controller/compactSavedVideos.ts
@@ -100,8 +100,15 @@ import {
audioPacketsHash,
compareCuts,
compareWholeFile,
+ cliTimelineStart,
+ compareCopyPts,
concatList,
countVideoFrames,
+ expectedCopyPts,
+ nominalFps,
+ sourceGaps,
+ wholeRatio,
+ type SourceGaps,
cutIsOffset,
encodeChunkArgs,
ffmpegHas,
@@ -141,7 +148,13 @@ 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).
+const STATE_VERSION = 3;
export type Presence = { onPlatform: boolean; availability: Availability | null; why: string };
@@ -165,8 +178,11 @@ export type CompactDeps = {
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; 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; 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>;
@@ -223,6 +239,7 @@ function resolveDeps(paths: Paths, settings: SavedVideoCompactionSettings, deps:
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 +283,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 +321,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 +353,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 +402,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 +431,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 +452,7 @@ export async function planOne(opts: {
estimate: estimate!,
needsFreeBytes,
freeBytes,
+ ...(failed?.kept ? { keptFailedEncode: failed.kept } : {}),
line,
pointer,
probe,
@@ -424,6 +468,7 @@ export async function planCompaction(opts: {
select?: boolean;
slugs?: string[];
retryFailed?: boolean;
+ reverify?: boolean;
belowThreshold?: boolean;
deps?: CompactDeps;
}): Promise<CompactPlan> {
@@ -444,6 +489,7 @@ export async function planCompaction(opts: {
mode,
settings: opts.settings,
retryFailed: opts.retryFailed,
+ reverify: opts.reverify,
belowThreshold: opts.belowThreshold,
deps,
});
@@ -461,10 +507,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 };
}
@@ -496,6 +545,11 @@ 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;
chunks: ChunkState[];
};
@@ -516,7 +570,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);
}
@@ -552,7 +609,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);
@@ -562,6 +619,7 @@ export async function compactOne(
mode: opts.mode,
settings: opts.settings,
retryFailed: opts.retryFailed,
+ reverify: opts.reverify,
belowThreshold: opts.belowThreshold,
deps,
});
@@ -615,7 +673,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,
@@ -664,7 +722,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)
@@ -678,7 +758,8 @@ 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 plan = planChunks(scan, s.chunkMinutes * 60, fps, nominal);
if (!plan.length) return { status: "failed", reason: "the source has no video packets" };
const n = scan.pts.length;
state = {
@@ -693,10 +774,18 @@ 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),
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.`);
@@ -709,7 +798,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) {
@@ -749,7 +838,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.`);
}
@@ -762,7 +851,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 });
@@ -782,6 +878,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,
@@ -828,7 +926,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 } : {}),
@@ -938,17 +1038,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 };
}
}
@@ -963,12 +1094,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;
@@ -988,38 +1113,87 @@ 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);
+ };
+ 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);
checks.decoded = dec.ok;
if (!dec.ok) fail(`the re-encode does not decode cleanly: ${dec.why ?? "errors"}`);
- // Length, frames and gaps, from both files' packets.
+ // 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 expectedPts = expectedCopyPts(srcScan.pts, state.chunks, ratio, o.fps && !ratio ? o.fps : null);
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).
@@ -1035,38 +1209,78 @@ 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)),
+ });
+ const snap = (t: number, seconds: number): number => {
+ const rel = expRel;
+ if (!rel.length) return t;
+ 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;
+ const step = 1.5 / outFps;
+ for (let j = i + 1; j < rel.length && rel[j] <= rel[i] + seconds + 1 / outFps; j += 1) {
+ if (rel[j] - rel[j - 1] > step) i = j;
+ }
+ return rel[i];
+ };
+
+ // 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,
sourceWidth: o.probe.width,
sourceHeight: o.probe.height,
tileFloor: s.wholeFileTileMin,
@@ -1141,34 +1355,38 @@ async function verify(o: {
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)));
// …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));
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));
+ times.add(snap(Math.min(lastAt, Math.max(0, (from + to) / 2 - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS));
}
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);
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, 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);
@@ -1179,13 +1397,16 @@ 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) => snap(t + relStart, CUT_SECONDS));
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 rel of cutTimes) {
+ const { at, sourceAt } = seekPair(rel);
+ const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, sourceAt, 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)) {
@@ -1195,10 +1416,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.`);
+ });
// 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;
@@ -1223,6 +1446,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.
@@ -1234,6 +1458,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 };
}
@@ -1358,7 +1584,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).
@@ -1532,6 +1758,42 @@ 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;
+};
+
+// Every failed encode kept in the store (`<store dir>/.compact-scratch` with a
+// failed.json): what failed, what is kept and its size.
+export async function listKeptFailedEncodes(paths: Paths): Promise<KeptFailedEncodeRow[]> {
+ const rows: KeptFailedEncodeRow[] = [];
+ for (const e of await listSavedVideos({ paths })) {
+ 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 });
+ }
+ return rows;
+}
+
+// One video's kept failed encode removed (its whole scratch) — refused while
+// a compaction of it runs (its marker is live).
+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));
+ if (!p) return { cleared: false, why: "no saved video" };
+ const f = await lastFailure(p.dir);
+ if (!f) return { cleared: false, why: "no failed encode is kept for it" };
+ const m = await readCompactingMarker(p.dir).catch(() => null);
+ if (m && (await markerLiveness(m)).live) return { cleared: false, why: "a compaction of it is running" };
+ await rm(path.join(p.dir, COMPACTION_SCRATCH_DIRNAME), { recursive: true, force: true });
+ return { cleared: true, why: `removed (${f.kept ? formatBytes(f.kept.bytes) : "no chunks"})`, ...(f.kept ? { bytes: f.kept.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
@@ -258,12 +258,21 @@ export function planChunks(scan: PacketScan, chunkSeconds: number, outFps: numbe
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);
const onGrid = (k: number) => {
if (!outFps) return true;
+ if (m) return indexOf(k) % m === 0;
const x = (k - starts[0]) * outFps;
return Math.abs(x - Math.round(x)) < 0.02;
};
@@ -325,9 +334,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 +357,22 @@ 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", `${decimateTo(s.sourceFps, s.fps)}setpts=PTS-STARTPTS`, "-fps_mode", "passthrough"]),
"-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 +425,115 @@ 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 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,
+): Float64Array {
+ const out: number[] = [];
+ 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 -----------------------------------------------------------
@@ -551,6 +682,9 @@ 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;
seconds: number;
fps: number | null;
sourceFps?: number | null;
@@ -565,8 +699,9 @@ 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 ref = `[1:v]trim=start=${(srcAt - pre).toFixed(4)},${decimateTo(opts.sourceFps, opts.fps)}${n}[r]`;
const dist = `[0:v]${n}[d]`;
const log = path.join(opts.scratchDir, `vmaf-${Math.round(opts.at * 1000)}.json`);
const metric =
@@ -578,7 +713,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 +820,9 @@ 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;
seconds: number;
fps: number | null;
sourceFps?: number | null;
@@ -692,11 +830,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, {
@@ -722,6 +861,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 {
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -183,6 +183,15 @@ export type SavedVideoCompactedChecks = {
// 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
@@ -559,6 +568,23 @@ function parseCompacted(raw: unknown): SavedVideoCompacted | null {
}
: {}),
...(Array.isArray(c.avOffset) ? { avOffset: pair(c.avOffset) } : {}),
+ ...(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);
diff --git a/common/lib/savedVideoCompaction.test.ts b/common/lib/savedVideoCompaction.test.ts
@@ -337,3 +337,44 @@ test("G: a periodic short fault fails, a bad chunk fails, real scene structure p
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");
+});
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -43,6 +43,15 @@
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.
+ - 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. 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",