// COMPACT A SAVED VIDEO (the `compact-saved-videos` job; the pure half is // lib/savedVideoCompaction.ts, the ffmpeg half lib/compactMedia-server.ts). // // One video at a time, each the same steps: // // 1. DECIDE. The pointer, the container, one ffprobe, the channel's opt-out // and the selector (deliberately stored always; an explicit item the // selector would not pick only with `belowThreshold`). A dry run stops // here and prints the estimate and the disk it needs. // 2. HASH THE SOURCE, fresh, every run (never the pointer's word): a stored // sha256 that disagrees stops the run. // 3. ENCODE IN CHUNKS, in `/.compact-scratch/` (the store's own // drive), with `/.compacting.json` saying so to every persist // of the video. Chunks start on source keyframes (on the copy's frame // grid); each is one heavy-slot admission; what the encoder WROTE is // counted against what the chunk must hold; the state is recorded so a // Retry resumes. Cancel and drain between chunks; the disk floor before // the first and before each one. // 4. MUX: the chunks joined; every other stream of the source (audio, // subtitles, data, attachments) and its chapters copied. // 5. VERIFY — every check must pass or the original stays active, untouched, // and the output is removed (the reason in the log, the result and // `failed.json`): a full decode; the length within a frame; the frame // count; no gap between frames the source does not have; the picture's // start against the sound's; the audio packets identical; every other // stream and the chapters there; THE WHOLE FILE compared at 2 frames a // second; VMAF (or SSIM) on excerpts across every chunk join, inside // every chunk and spread through the file; windows cut from both copies // through the evidence cutter, frame-exact; the recording clock. // 6. SWAP, fsynced first, in one locked pointer write that compares the // pointer's file, bytes, dir, storedAt and sha256 with what was encoded: // the re-encode (its OWN name) becomes `file`; the original joins // `alternates` as `keptAs: "original"`, identified by its sha256; // `compacted` records every number; the clock map is retargeted in the // same lock. // 7. RECHECK, a separate step: the re-encode read back from disk. // 8. DROP THE ORIGINAL, another separate step, only under `dropOriginal: // "after-verify"`, only after a whole-file comparison, only while nothing // is downloading the video, and NEVER for a video not freshly checked on // its platform (that one waits for a person's review). The drop runs // dropSavedAlternate, which reads the copy back again itself. import path from "node:path"; import { createReadStream } from "node:fs"; import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Availability } from "../lib/availability"; import { readChannelConfig } from "./channels"; import { listSavedVideos } from "./savedVideoInventory"; import { channelPlatform } from "../ytdlp/channelArgs"; import { detectPlatform } from "../lib/platform"; import { compactedLine, compactedOriginalOf, parseSavedVideoPointer, reviewIsCurrent, savedVideoPath, type SavedVideoAlternate, type SavedVideoCompacted, type SavedVideoCompactedChecks, type SavedVideoPointer, } from "../lib/savedVideo"; import { SavedAlternateRefusal, dropSavedAlternate, fsyncFileAndDir, loadSavedVideo, readBackCompactedCopy, savedVideoPointerPath, updateSavedVideoChecksum, withPointerLock, } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { platformPresence } from "../lib/availability-server"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; import { COMPACTION_DISK_MARGIN_BYTES, COMPACTION_SCRATCH_DIRNAME, COMPACTION_STATE_FILENAME, COMPACTION_TOOL, compactedFileName, compactionFreeNeeded, decideCompaction, estimateCompaction, sanitizeSavedVideoCompaction, targetFps, type CompactionEstimate, type CompactionReviewState, type SavedVideoCompactionSettings, } from "../lib/savedVideoCompaction"; import { CHUNK_ESTIMATE_MB, CHUNK_EXT, WHOLE_FILE_GRID, WHOLE_FILE_WIDTH, audioPacketsHash, compareCuts, compareWholeFile, cliTimelineStart, compareCopyPts, concatList, countVideoFrames, expectedCopyPts, keepMinStep, keepSelect, nominalFps, sourceGaps, wholeRatio, type SourceGaps, cutIsOffset, encodeChunkArgs, ffmpegHas, ffmpegVersionLine, fullDecode, muxArgs, planChunks, probeCompactionSource, sameAudioTiming, runHeavyFfmpeg, sampleTimes, scanVideoPackets, scoreExcerpt, streamInventory, type AudioHash, type ChunkPlan, type CutComparison, type EncodeSettings, type PacketScan, type SourceProbe, type WholeFileComparison, judgeWholeFile, } from "../lib/compactMedia-server"; import { clearCompactingMarker, readCompactingMarker, writeCompactingMarker } from "../lib/compactingMarker-server"; import { planRecordingClock, measureRecordingClock, recordingClockSidecar } from "../lib/recordingClock-server"; import { clockOffsetAt, type RecordingClock } from "../lib/recordingClock.mjs"; import "../lib/childKillGuard"; export type CompactItem = { slug: string; id: string }; export const COMPACT_GOP_SECONDS = 5; export const COMPACT_PIX_FMT = "yuv420p"; const EXCERPT_SECONDS = 2; const CUT_SECONDS = 3; const CUT_SAMPLES = 3; // A window cut from each copy, compared frame by frame: below this the copy's // cut is another picture; better a frame off than as cut, it lands elsewhere. export const CUT_SSIM_MIN = 0.9; export const FAILED_FILENAME = "failed.json"; // A failed copy kept for a re-verify: in the scratch, never the active copy. export const FAILED_COPY_BASENAME = "failed-copy"; // The copy keeps the source's timestamps; a Matroska copy rounds them to the // millisecond (half of one at most), an mp4 at 90 kHz keeps them exactly. export const PTS_TOLERANCE_SECONDS = 0.001; // 3: the source's timestamps kept (a chunk encoded before is not reused). // 5: the kept frames by ONE constant rule (review H1); its step saved. const STATE_VERSION = 5; export type Presence = { onPlatform: boolean; availability: Availability | null; why: string }; // --- deps (a test replaces what it judges) ---------------------------------- export type CompactDeps = { now?: () => Date; freeBytes?: (dir: string) => Promise; // Still on its platform, freshly and first-hand (availability-server's // platformPresence with settings.availabilityMaxAgeDays). presence?: (videoDir: string) => Promise; // A download or persist of the video queued or running (controller/videoBusy.ts). busy?: (slug: string, id: string) => string | null | Promise; probe?: (file: string) => Promise; scan?: (file: string, signal?: AbortSignal) => Promise; encodeChunk?: (o: { src: string; chunk: ChunkPlan; settings: EncodeSettings; out: string; signal?: AbortSignal }) => Promise; countFrames?: (file: string) => Promise; mux?: (o: { list: string; src: string; probe: SourceProbe; out: string; signal?: AbortSignal }) => Promise; // `reference`: the source, whose own audio decode excuses audio damage the // copy carries over packet for packet. fullDecode?: (file: string, signal?: AbortSignal, reference?: string) => Promise<{ ok: boolean; why?: string; notes?: string[] }>; audioHash?: (file: string, signal?: AbortSignal) => Promise; inventory?: (file: string, skipIndex: number) => Promise; wholeFile?: (o: Parameters[1]) => Promise; hasVmaf?: () => Promise; // `at` the copy's seek time, `sourceAt` the same frame's in the source. score?: (o: { compacted: string; source: string; at: number; sourceAt?: number; sourceSelect?: string; seconds: number; fps: number | null; sourceFps: number | null; metric: "vmaf" | "ssim"; scratchDir: string; signal?: AbortSignal }) => Promise; cutCompare?: (o: { compacted: string; source: string; at: number; sourceAt?: number; sourceSelect?: string; seconds: number; fps: number | null; sourceFps: number | null; scratchDir: string; signal?: AbortSignal }) => Promise; // Where ffmpeg's command line starts a file's timeline (cliTimelineStart). timelineStart?: (file: string, firstVideoPts: number) => Promise; measureClock?: (o: { videoDir: string; source: string; container: string; sourceBytes: number; targetBytes: number; transcribedAt: string | null; extra: number[]; signal?: AbortSignal }) => Promise; sha256?: (file: string, signal?: AbortSignal) => Promise; encoderBanner?: () => Promise; }; async function sha256File(file: string, signal?: AbortSignal): Promise { const h = createHash("sha256"); for await (const chunk of createReadStream(file, { highWaterMark: 1 << 20, ...(signal ? { signal } : {}) })) { h.update(chunk as Buffer); } return h.digest("hex"); } function resolveDeps(paths: Paths, settings: SavedVideoCompactionSettings, deps: CompactDeps = {}): Required { return { now: deps.now ?? (() => new Date()), freeBytes: deps.freeBytes ?? getFreeBytes, presence: deps.presence ?? ((d) => platformPresence(d, { maxAgeDays: settings.availabilityMaxAgeDays }).catch(() => ({ onPlatform: false, availability: null, why: "its availability could not be read", }))), busy: deps.busy ?? (async (slug, id) => (await import("./videoBusy")).videoPersistBusyReason(slug, id)), probe: deps.probe ?? ((f) => probeCompactionSource(paths.ffprobeBin, f)), scan: deps.scan ?? ((f, s) => scanVideoPackets(paths.ffprobeBin, f, s)), encodeChunk: deps.encodeChunk ?? (async (o) => { await runHeavyFfmpeg(paths, encodeChunkArgs(o.src, o.chunk, o.settings, o.out), { estimateMB: CHUNK_ESTIMATE_MB, ...(o.signal ? { signal: o.signal } : {}), }); }), countFrames: deps.countFrames ?? ((f) => countVideoFrames(paths.ffprobeBin, f)), mux: deps.mux ?? (async (o) => { await runHeavyFfmpeg( paths, // The video's start RELATIVE to the file's (ffmpeg moves every input // to start at 0, the copied streams of the source with it). muxArgs(o.list, o.src, Math.max(0, o.probe.videoStart - o.probe.formatStart), o.out, { mainVideoIndex: o.probe.mainVideoIndex, container: o.probe.container, }), { estimateMB: 300, nice: true, ...(o.signal ? { signal: o.signal } : {}) }, ); }), fullDecode: deps.fullDecode ?? ((f, s, ref) => fullDecode(paths, f, s, ref)), audioHash: deps.audioHash ?? ((f, s) => audioPacketsHash(paths.ffmpegBin, f, s, paths.ffprobeBin)), inventory: deps.inventory ?? ((f, skip) => streamInventory(paths.ffprobeBin, f, skip)), wholeFile: deps.wholeFile ?? ((o) => compareWholeFile(paths, o)), hasVmaf: deps.hasVmaf ?? (() => ffmpegHas(paths.ffmpegBin, "filters", "libvmaf")), timelineStart: deps.timelineStart ?? ((f, first) => cliTimelineStart(paths.ffmpegBin, f, first)), score: deps.score ?? ((o) => scoreExcerpt(paths, o)), cutCompare: deps.cutCompare ?? ((o) => compareCuts(paths, o)), measureClock: deps.measureClock ?? ((o) => measureRecordingClock({ ffmpegBin: paths.ffmpegBin, ffprobeBin: paths.ffprobeBin, ...o, write: false, })), sha256: deps.sha256 ?? sha256File, encoderBanner: deps.encoderBanner ?? (() => ffmpegVersionLine(paths.ffmpegBin)), }; } // --- the plan (and the dry run) ---------------------------------------------- export type CompactPlanItem = { slug: string; id: string; compact: boolean; reason?: string; platform: string | null; // Still on its platform, freshly and first-hand; else counted as gone. onPlatform: boolean; availability: Availability | null; presence?: string; // An explicit item the selector would not pick: why (ruling 9). belowThreshold?: string; source?: { file: string; bytes: number; vcodec: string | null; height: number | null; fps: number | null; seconds: number | null; videoMbps: number | null; }; fps?: number | null; estimate?: CompactionEstimate; needsFreeBytes?: number; freeBytes?: number; // A failed encode kept in the video's scratch (never active): its size. keptFailedEncode?: KeptFailedEncode; line: string; }; export type CompactPlan = { items: CompactPlanItem[]; willCompact: number; totals: { bytes: number; estimate: [number, number]; hours: [number, number] }; lines: string[]; }; function hms(seconds: number | null | undefined): string { if (!seconds) return "?"; const h = Math.floor(seconds / 3600); const m = Math.round((seconds % 3600) / 60); return h ? `${h}h${String(m).padStart(2, "0")}m` : `${m}m`; } function hoursRange([a, b]: [number, number]): string { const f = (x: number) => (x < 1 ? `${Math.max(1, Math.round(x * 60))} min` : `${x.toFixed(x < 10 ? 1 : 0)} h`); return `${f(a)}–${f(b)}`; } // The video's platform: its own URL's when its record names one (a channel // may hold another platform's videos), else the channel's. async function videoPlatform(videoDir: string, config: ChannelConfig): Promise { const read = await readJsonFile(path.join(videoDir, "metadata.info.json")); if (read.ok && read.value && typeof read.value === "object") { const url = (read.value as { webpage_url?: unknown }).webpage_url; if (typeof url === "string") { const p = detectPlatform(url); if (p) return p; } } return channelPlatform(config); } 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 { 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; const k = r.kept && typeof r.kept === "object" ? (r.kept as Record) : null; return typeof r.reason === "string" ? { 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; } export function settingsKeyOf(s: SavedVideoCompactionSettings, fps: number | null): string { return JSON.stringify({ crf: s.crf, preset: s.preset, fps, chunkMinutes: s.chunkMinutes, gop: COMPACT_GOP_SECONDS, pix: COMPACT_PIX_FMT, v: STATE_VERSION }); } export async function planOne(opts: { paths: Paths; item: CompactItem; mode: "explicit" | "select"; settings: SavedVideoCompactionSettings; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean; deps: Required; }): Promise { const { item, settings, deps } = opts; const videoDir = path.join(opts.paths.channelsDir, item.slug, "data", item.id); const base = { slug: item.slug, id: item.id, platform: null, onPlatform: false, availability: null, videoDir }; const skip = (reason: string, extra: Partial = {}) => ({ ...base, ...extra, compact: false, reason, line: `${item.slug}/${item.id}: ${extra.line ?? ""}${extra.line ? " " : ""}skipped (${reason})`, }); const config = await readChannelConfig(opts.paths, item.slug); if (!config) return skip(`no channel "${item.slug}"`); const pointer = await loadSavedVideo(videoDir); if (!pointer) return skip("no saved video"); const platform = await videoPlatform(videoDir, config); const presence = await deps.presence(videoDir); const container = savedVideoPath(pointer); const present = await stat(container).then((s) => s.isFile(), () => false); const probe = present && !pointer.compacted ? await deps.probe(container) : null; const facts = { platform, onPlatform: presence.onPlatform, availability: presence.availability, presence: presence.why }; const decision = decideCompaction({ pointer, platform, channelExcluded: config.excludeFromCompaction === true, mode: opts.mode, containerPresent: present, probe, settings, ...(opts.belowThreshold ? { belowThreshold: true } : {}), }); const mbps = probe?.videoKbps != null ? probe.videoKbps / 1000 : null; const brief = probe ? `${hms(probe.seconds)} ${probe.height ?? "?"}p${probe.fps ? Math.round(probe.fps) : ""} ${probe.vcodec ?? "?"} ${mbps !== null ? `${mbps.toFixed(2)} Mbit/s` : "? Mbit/s"} ${formatBytes(pointer.bytes)}` : ""; const fps = probe ? targetFps(probe.fps, platform, settings) : null; const estimate = probe?.hasVideo && probe.seconds ? estimateCompaction({ probe, crf: settings.crf, fps }) : null; // HOW LITTLE IT WOULD SAVE (ruling 9), said wherever a below-threshold item is. const saves = estimate ? `it would save about ${formatBytes(Math.max(0, pointer.bytes - estimate.bytes[1]))}–${formatBytes(Math.max(0, pointer.bytes - estimate.bytes[0]))} of ${formatBytes(pointer.bytes)}` : ""; if (!decision.ok) { const reason = decision.belowThreshold && saves ? `${decision.reason} (${saves})` : decision.reason; return { ...skip(reason, { ...facts, line: brief ? `${brief} —` : "", ...(decision.belowThreshold ? { belowThreshold: decision.belowThreshold } : {}) }), pointer, probe }; } const failed = await lastFailure(pointer.dir); 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}; ` + (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); // 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; const line = `${item.slug}/${item.id}: ${brief} → est. ${formatBytes(estimate!.bytes[0])}–${formatBytes(estimate!.bytes[1])} ` + `AV1 crf ${settings.crf}${fps ? ` at ${fps} fps` : ""} (−${pct(estimate!.bytes[1])}…${pct(estimate!.bytes[0])}%), ` + `est. ${hoursRange(estimate!.hours)}, needs ${formatBytes(needsFreeBytes)} free (${formatBytes(freeBytes)} free)` + (room ? " — would compact" : " — NOT ENOUGH FREE SPACE: would stop before it") + (decision.belowThreshold ? `; below the selector's thresholds (${decision.belowThreshold}): ${saves}` : "") + (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, ...facts, compact: true, ...(decision.belowThreshold ? { belowThreshold: decision.belowThreshold } : {}), source: { file: pointer.file, bytes: pointer.bytes, vcodec: probe!.vcodec, height: probe!.height, fps: probe!.fps, seconds: probe!.seconds, videoMbps: mbps, }, fps, estimate: estimate!, needsFreeBytes, freeBytes, ...(failed?.kept ? { keptFailedEncode: failed.kept } : {}), line, pointer, probe, }; } // Every candidate: an explicit list, or (`select`) every saved video the // selector picks, across channels (or `slugs`). export async function planCompaction(opts: { paths: Paths; settings: SavedVideoCompactionSettings; items?: CompactItem[]; select?: boolean; slugs?: string[]; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean; deps?: CompactDeps; }): Promise { const deps = resolveDeps(opts.paths, opts.settings, opts.deps); let items = opts.items ?? []; const mode: "explicit" | "select" = opts.select ? "select" : "explicit"; if (opts.select) { const listed = opts.slugs?.length ? (await Promise.all(opts.slugs.map((s) => listSavedVideos({ paths: opts.paths, channelSlug: s })))).flat() : await listSavedVideos({ paths: opts.paths }); items = listed.map((e) => ({ slug: e.slug, id: e.videoId })); } const out: CompactPlanItem[] = []; for (const item of items) { const { pointer: _p, probe: _q, videoDir: _d, ...row } = await planOne({ paths: opts.paths, item, mode, settings: opts.settings, retryFailed: opts.retryFailed, reverify: opts.reverify, belowThreshold: opts.belowThreshold, deps, }); out.push(row); } const will = out.filter((i) => i.compact); const totals = { bytes: will.reduce((n, i) => n + (i.source?.bytes ?? 0), 0), estimate: [ will.reduce((n, i) => n + (i.estimate?.bytes[0] ?? 0), 0), will.reduce((n, i) => n + (i.estimate?.bytes[1] ?? 0), 0), ] as [number, number], hours: [ will.reduce((n, i) => n + (i.estimate?.hours[0] ?? 0), 0), will.reduce((n, i) => n + (i.estimate?.hours[1] ?? 0), 0), ] as [number, number], }; const 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` + (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 }; } // --- the run ------------------------------------------------------------------- type ChunkState = ChunkPlan & { file: string; bytes?: number; done: boolean }; // Each chunk's first frame in the copy: the chunks' expected frames, summed. function chunkStartFrames(chunks: { expectedFrames: number }[]): number[] { const out: number[] = []; let at = 0; for (const c of chunks) { out.push(at); at += c.expectedFrames; } return out; } type CompactState = { version: typeof STATE_VERSION; sourceFile: string; sourceBytes: number; sourceSha256: string; settingsKey: string; startedAt: string; sourceFrames: number; sourceFirstPts: number; sourceLastPts: number; sourceFrameStep: number; sourceMaxGap: number; // The source's NOMINAL rate (1 / its median frame step): what the decimation // and every comparison take, never the average a dropped frame moves. sourceFps?: number | null; // The recording's dropped frames (kept as gaps in the copy). sourceGaps?: SourceGaps; // Under a whole ratio: the step of the rule that decides which source // frames the copy keeps (keepMinStep); the encoder's select and every check // apply this one rule. keepMinStep?: number; chunks: ChunkState[]; }; export type CompactOneResult = | { status: "compacted"; line: string; pointer: SavedVideoPointer; dropped: boolean; review: CompactionReviewState; // Something after the swap failed: the swap stands; this says what. afterSwapError?: string; } | { status: "skipped"; reason: string } | { status: "failed"; reason: string } | { status: "stopped"; reason: string }; class VerifyFailure extends Error { constructor( message: string, readonly checks: Partial & { 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); } } function round(n: number, d = 3): number { const f = 10 ** d; return Math.round(n * f) / f; } async function loadState(file: string): Promise { const read = await readJsonFile(file); if (!read.ok || !read.value || typeof read.value !== "object") return null; const s = read.value as CompactState; return s.version === STATE_VERSION && Array.isArray(s.chunks) ? s : null; } function maxGap(pts: Float64Array): number { let g = 0; for (let i = 1; i < pts.length; i += 1) g = Math.max(g, pts[i] - pts[i - 1]); return g; } export type CompactRunOptions = { paths: Paths; // The job this run is (its marker names it; the registry is asked). jobId?: string; settings: SavedVideoCompactionSettings; onLog: (line: string) => void; signal?: AbortSignal; drainSignal?: AbortSignal; deps?: CompactDeps; }; export async function compactOne( opts: CompactRunOptions & { item: CompactItem; mode: "explicit" | "select"; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean }, ): Promise { const log = (s: string) => opts.onLog(s.endsWith("\n") ? s : `${s}\n`); const deps = resolveDeps(opts.paths, opts.settings, opts.deps); const planned = await planOne({ paths: opts.paths, item: opts.item, mode: opts.mode, settings: opts.settings, retryFailed: opts.retryFailed, reverify: opts.reverify, belowThreshold: opts.belowThreshold, deps, }); if (!planned.compact || !planned.pointer || !planned.probe) { // A stale marker beside a video that is not compacted now (an already // compacted one after a crash between the swap and the marker's // removal) is cleared here, so it never blocks the video. if (planned.pointer) { const c = await clearCompactingMarker(planned.pointer.dir).catch(() => null); if (c?.cleared) log(`${opts.item.slug}/${opts.item.id}: a stale compaction marker removed (${c.why}).`); } log(planned.line); return { status: "skipped", reason: planned.reason ?? "not a candidate" }; } await assertSavedVideosStoreWritable(opts.paths, planned.pointer.dir); const existing = await readCompactingMarker(planned.pointer.dir); if (existing) { const c = await clearCompactingMarker(planned.pointer.dir); if (!c.cleared) return { status: "skipped", reason: `another compaction of this video is running (${c.why})` }; log(`${opts.item.slug}/${opts.item.id}: a stale compaction marker removed (${c.why}).`); } // THE MARKER every persist, attach, import, unpersist and drop of this // video reads (lib/compactingMarker-server.ts): written before anything // else, HELD through the swap, the re-check and the drop (review F4), and // removed only at the very end. The compaction's own steps pass its token. const marker = await writeCompactingMarker(planned.pointer.dir, { ...(opts.jobId ? { jobId: opts.jobId } : {}), video: `${opts.item.slug}/${opts.item.id}`, now: deps.now(), }); try { return await compactPlanned(opts, deps, planned, log, marker.token); } finally { await clearCompactingMarker(planned.pointer.dir, { token: marker.token }).catch(() => {}); } } // EVERY STALE MARKER IN THE STORE removed (lib/compactingMarker-server.ts // says what stale is): at editor boot and at the start of every compaction // run. Answers what it found. export async function sweepCompactingMarkers(paths: Paths, onLog?: (l: string) => void): Promise<{ slug: string; id: string; cleared: boolean; why: string }[]> { const out: { slug: string; id: string; cleared: boolean; why: string }[] = []; for (const e of await listSavedVideos({ paths }).catch(() => [])) { const m = await readCompactingMarker(e.pointer.dir).catch(() => null); if (!m) continue; const c = await clearCompactingMarker(e.pointer.dir).catch((err) => ({ cleared: false, why: (err as Error).message })); out.push({ slug: e.slug, id: e.videoId, ...c }); if (c.cleared) onLog?.(`${e.slug}/${e.videoId}: a stale compaction marker removed (${c.why}).\n`); } return out; } async function compactPlanned( opts: CompactRunOptions & { item: CompactItem; retryFailed?: boolean; reverify?: boolean }, deps: Required, planned: Awaited>, log: (s: string) => void, // The marker's token: the drop step passes it (the marker is still held). markerToken: string, ): Promise { const { settings: s, signal } = opts; const tag = `${opts.item.slug}/${opts.item.id}`; const pointer = planned.pointer!; const probe = planned.probe!; const videoDir = planned.videoDir; const src = savedVideoPath(pointer); const fps = planned.fps ?? null; const settingsKey = settingsKeyOf(s, fps); const scratch = path.join(pointer.dir, COMPACTION_SCRATCH_DIRNAME); const stateFile = path.join(scratch, COMPACTION_STATE_FILENAME); const estHigh = planned.estimate!.bytes[1]; log(planned.line.replace(/ — would compact/, "")); // The disk floor: before the first chunk and before every one. const floor = async (written: number): Promise => { const free = await deps.freeBytes(pointer.dir); const need = compactionFreeNeeded(estHigh, written); return free < need ? `the store's disk has ${formatBytes(free)} free; ${tag} needs about ${formatBytes(need)} more ` + `(its chunks and the muxed copy side by side, plus a ${formatBytes(COMPACTION_DISK_MARGIN_BYTES)} margin)` : null; }; await mkdir(scratch, { recursive: true }); let swapped = false; let state: CompactState | null = null; try { // ---- 2. the source, hashed fresh ---- const low0 = await floor(0); if (low0) return { status: "stopped", reason: low0 }; log(`${tag}: hashing ${pointer.file} (${formatBytes(pointer.bytes)}) — the original's sha256 is read fresh, never taken from the pointer.`); const sourceSha = await deps.sha256(src, signal); if (pointer.sha256 && pointer.sha256 !== sourceSha) { return { status: "failed", reason: `${pointer.file}'s bytes do not match the sha256 recorded on its pointer (${pointer.sha256.slice(0, 12)}… recorded, ` + `${sourceSha.slice(0, 12)}… now): the stored original is not what was saved — nothing is compacted`, }; } if (!pointer.sha256) await updateSavedVideoChecksum(videoDir, sourceSha, pointer.file); // 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) ) { log(`${tag}: the scratch state is for another source or other settings — discarded, starting over.`); await rm(scratch, { recursive: true, force: true }); await mkdir(scratch, { recursive: true }); state = null; } const writeState = async () => writeJsonAtomic(stateFile, state); if (!state) { log(`${tag}: scanning ${pointer.file}'s packets (frame count, keyframes)…`); const scan = await deps.scan(src, signal); const nominal = nominalFps(scan.pts) ?? probe.fps; const m = wholeRatio(nominal, fps); const keep = m && nominal ? { minStep: keepMinStep(nominal / m, nominal) } : undefined; const plan = planChunks(scan, s.chunkMinutes * 60, fps, nominal, keep); if (!plan.length) return { status: "failed", reason: "the source has no video packets" }; const n = scan.pts.length; state = { version: STATE_VERSION, sourceFile: pointer.file, sourceBytes: pointer.bytes, sourceSha256: sourceSha, settingsKey, startedAt: deps.now().toISOString(), sourceFrames: n, sourceFirstPts: scan.pts[0], sourceLastPts: scan.pts[n - 1], sourceFrameStep: n > 1 ? scan.pts[n - 1] - scan.pts[n - 2] : 1 / (probe.fps ?? 30), sourceMaxGap: maxGap(scan.pts), sourceFps: nominal, sourceGaps: sourceGaps(scan.pts), ...(keep ? { keepMinStep: keep.minStep } : {}), chunks: plan.map((c) => ({ ...c, file: `chunk-${String(c.index).padStart(4, "0")}${CHUNK_EXT}`, done: false })), }; await writeState(); 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.`); } // ---- 3. the chunks ---- const enc: EncodeSettings = { preset: s.preset, crf: s.crf, gopSeconds: COMPACT_GOP_SECONDS, pixFmt: COMPACT_PIX_FMT, fps, sourceFps: state.sourceFps ?? probe.fps ?? 30, formatStart: probe.formatStart, }; for (const c of state.chunks) { if (c.done) { const ok = await stat(path.join(scratch, c.file)).then((st) => st.size === c.bytes, () => false); if (ok) continue; log(`${tag}: chunk ${c.index} is recorded done but its file is not as recorded — encoding it again.`); c.done = false; } if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; if (opts.drainSignal?.aborted) { log(`${tag}: drained — ${state.chunks.filter((x) => !x.done).length} chunk(s) left for the next run.`); return { status: "stopped", reason: "drained" }; } const written = state.chunks.reduce((n, x) => n + (x.done ? (x.bytes ?? 0) : 0), 0); const low = await floor(written); if (low) { log(`${tag}: stopped — ${low}. A re-run resumes.`); return { status: "stopped", reason: low }; } await assertSavedVideosStoreWritable(opts.paths, pointer.dir); const out = path.join(scratch, c.file); const part = `${out}.part`; await rm(part, { force: true }); log(`${tag}: chunk ${c.index + 1}/${state.chunks.length} (${c.from.toFixed(1)}–${c.to.toFixed(1)} s, ${c.expectedFrames} frames)…`); // WHAT THE ENCODER WROTE, counted: a short or long chunk is encoded once // more; twice is a verdict. for (let attempt = 1; ; attempt += 1) { try { await deps.encodeChunk({ src, chunk: c, settings: enc, out: part, signal }); } catch (err) { await rm(part, { force: true }).catch(() => {}); if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; throw err; } const frames = await deps.countFrames(part); if (frames === c.expectedFrames) break; await rm(part, { force: true }); if (attempt >= 2) { throw new VerifyFailure(`chunk ${c.index} holds ${frames} frames, not the ${c.expectedFrames} expected (encoded twice)`, {}, [c.index]); } log(`${tag}: chunk ${c.index} holds ${frames} frames, not ${c.expectedFrames} — encoding it again.`); } await rename(part, out); c.bytes = (await stat(out)).size; c.done = true; await writeState(); } // ---- 4. the mux ---- if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; const listFile = path.join(scratch, "chunks.txt"); // 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 }); log(`${tag}: joining ${state.chunks.length} chunk(s), every other stream and the chapters of the source copied…`); await deps.mux({ list: listFile, src, probe, out: muxed, signal }); // ---- 5. verify ---- const { checks, clock: keptClock } = await verify({ ...opts, deps, tag, state, src, muxed, probe, fps, videoDir, pointer, scratch, log }); // ---- 6. the swap ---- const at = deps.now(); await fsyncFileAndDir(muxed); const resultSha = await deps.sha256(muxed, signal); const resultProbe = await deps.probe(muxed); const resultBytes = (await stat(muxed)).size; await assertSavedVideosStoreWritable(opts.paths, pointer.dir); const name = compactedFileName(at, await readdir(pointer.dir).catch(() => []), ext); const final = path.join(pointer.dir, name); const encoder = await deps.encoderBanner().catch(() => "ffmpeg"); const 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, storedAt: pointer.storedAt, setAsideAt: at.toISOString(), ...(probe.seconds ? { seconds: probe.seconds } : {}), ...(probe.height ? { height: probe.height } : {}), ...(probe.vcodec ? { vcodec: probe.vcodec } : {}), ...(pointer.origin ? { origin: pointer.origin } : {}), ...(pointer.format?.preset ? { preset: pointer.format.preset } : {}), keptAs: "original", sha256: sourceSha, }; const compacted: SavedVideoCompacted = { at: at.toISOString(), tool: COMPACTION_TOOL, encoder, settings: { codec: "av1", encoder: "libsvtav1", preset: s.preset, crf: s.crf, gopSeconds: COMPACT_GOP_SECONDS, pixFmt: COMPACT_PIX_FMT, fps, audio: "copy", chunkSeconds: s.chunkMinutes * 60, }, source: { file: pointer.file, bytes: pointer.bytes, sha256: sourceSha, ...(probe.vcodec ? { vcodec: probe.vcodec } : {}), ...(probe.height ? { height: probe.height } : {}), ...(probe.fps ? { fps: probe.fps } : {}), ...(probe.seconds ? { seconds: probe.seconds } : {}), frames: state.sourceFrames, ...(probe.videoKbps ? { videoKbps: probe.videoKbps } : {}), ...(pointer.format ? { format: pointer.format } : {}), }, result: { file: name, bytes: resultBytes, sha256: resultSha, vcodec: resultProbe?.vcodec ?? "av1", ...(resultProbe?.height ? { height: resultProbe.height } : {}), // 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 } : {}), }, checks, chunks: state.chunks.length, }; const pointerFile = savedVideoPointerPath(videoDir); const swappedNow = await withPointerLock(videoDir, async () => { const read = await readJsonFile(pointerFile); const raw = read.ok && read.value && typeof read.value === "object" ? { ...(read.value as Record) } : null; // COMPARE-AND-SWAP: the pointer still names exactly the bytes encoded. if ( !raw || raw.file !== pointer.file || raw.bytes !== pointer.bytes || raw.dir !== pointer.dir || raw.storedAt !== pointer.storedAt || // …and is still kept for the same reason, by the same request. !sameProvenance(raw, pointer) || (raw.sha256 !== undefined && raw.sha256 !== sourceSha) || raw.compacted !== undefined ) { return false; } // The clock first (its old map kept to put back), then the file, then // the pointer: a failure puts both back as they were. const oldClock = keptClock ? await recordingClockSidecar.load(videoDir) : null; if (keptClock) await recordingClockSidecar.write(videoDir, { ...keptClock, target: { file: name, bytes: resultBytes } }); try { await rename(muxed, final); await fsyncFileAndDir(final); raw.file = name; raw.bytes = resultBytes; raw.sha256 = resultSha; raw.compacted = compacted; raw.probed = { ...(resultProbe?.seconds ? { seconds: resultProbe.seconds } : {}), ...(resultProbe?.height ? { height: resultProbe.height } : {}), }; // `format` says what the ACTIVE copy is: the same asked-for preset, // the re-encode's height and codec (the download's is in // `compacted.source.format`). if (raw.format && typeof raw.format === "object") { raw.format = { ...(raw.format as Record), ...(resultProbe?.height ? { height: resultProbe.height } : {}), vcodec: "av1", }; } raw.alternates = [...(Array.isArray(raw.alternates) ? raw.alternates : []), original]; await writeJsonAtomic(pointerFile, raw); } catch (err) { // The pointer still names the original: the re-encode goes back to // its scratch name and the clock map to the original's. await rename(final, muxed).catch(() => {}); if (keptClock && oldClock) await recordingClockSidecar.write(videoDir, oldClock).catch(() => {}); throw err; } return true; }); if (!swappedNow) { await rm(muxed, { force: true }); return { status: "failed", reason: "the saved copy changed while it was being compacted (the pointer names other bytes now): nothing swapped" }; } swapped = true; log( `compacted ${tag}: ${formatBytes(pointer.bytes)} ${probe.vcodec ?? "?"} ${probe.height ?? "?"}p${probe.fps ? Math.round(probe.fps) : ""} → ` + `${formatBytes(resultBytes)} AV1 crf ${s.crf}${fps ? ` ${fps} fps` : ""} (${Math.round((resultBytes / pointer.bytes) * 100)}%), ` + `${checks.frames[1]}/${checks.frames[2]} frames, audio copied (identical), whole file SSIM ${checks.wholeFile?.mean.toFixed(3)} ` + `(lowest ${checks.wholeFile?.min.toFixed(3)} at ${checks.wholeFile?.worstAt.toFixed(1)} s), ${checks.quality.metric.toUpperCase()} ` + `${checks.quality.mean.toFixed(checks.quality.metric === "vmaf" ? 1 : 3)} (worst excerpt ${checks.quality.min.toFixed(checks.quality.metric === "vmaf" ? 1 : 3)}); ` + `the original is kept as ${pointer.file} until it is dropped.`, ); await rm(scratch, { recursive: true, force: true }); // ---- 7 and 8: the recheck, then the drop — each its own step ---- const after = await afterSwap({ paths: opts.paths, videoDir, item: opts.item, settings: s, deps, log, tag, signal, markerToken }); return { status: "compacted", line: `compacted ${tag}`, pointer: (await loadSavedVideo(videoDir))!, ...after }; } catch (err) { if (swapped) { // AFTER THE SWAP NOTHING IS UNDONE, and nothing pretends it was: the // re-encode is the active copy, the original is kept beside it. const why = (err as Error).message; log( `compacted ${tag}: the swap is written (the active copy is the re-encode; the original ${pointer.file} is kept beside it). ` + `After it, a step failed: ${why}. Nothing is dropped.`, ); const p = await loadSavedVideo(videoDir); return { status: "compacted", line: `compacted ${tag}`, pointer: p ?? pointer, dropped: false, review: "drop-pending", afterSwapError: why, }; } if (signal?.aborted) return { status: "stopped", reason: "cancelled" }; if (!(err instanceof VerifyFailure)) { // Not a verdict on the re-encode (ffmpeg died, a disk error, the store // started moving): the chunks already encoded stay for the re-run; only // a half-written mux goes. for (const f of ["compacted.mp4", "compacted.mkv"]) await rm(path.join(scratch, f), { force: true }).catch(() => {}); const reason = (err as Error).message; log(`${tag}: NOT compacted — ${reason}. The original stays the active copy, untouched; a re-run resumes from the chunks done.`); return { status: "failed", reason }; } const reason = `verification failed: ${err.message}`; // A VERDICT: the original stays active and untouched. THE 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. ` + (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 }; } } function sameProvenance(raw: Record, pointer: SavedVideoPointer): boolean { const now = parseSavedVideoPointer(raw); return ( !!now && now.keepReason === pointer.keepReason && now.explicit === pointer.explicit && JSON.stringify(now.origin ?? null) === JSON.stringify(pointer.origin ?? null) ); } async function verify(o: { paths: Paths; settings: SavedVideoCompactionSettings; deps: Required; tag: string; state: CompactState; src: string; muxed: string; probe: SourceProbe; fps: number | null; videoDir: string; pointer: SavedVideoPointer; scratch: string; log: (s: string) => void; signal?: AbortSignal; }): Promise<{ checks: SavedVideoCompactedChecks; clock: RecordingClock | null }> { const { deps, tag, state, settings: s, log, signal } = o; const checks: Partial = { passed: false, audio: "unknown" }; // EVERY CHECK RUNS and reports its own result (review, the first real run: // a failure recorded "audio unknown"): a failing one is listed and the next // runs; only a copy that cannot be read at all stops the list. const problems: string[] = []; const failedChunks: number[] = []; const fail = (why: string): void => { problems.push(why); }; // A check that could not be made on this source: named on the record, // never counted as passed. const skip = (what: string): void => { checks.skipped = [...(checks.skipped ?? []), what]; }; const fatal = (why: string): never => { problems.push(why); throw new VerifyFailure(problems.join("; "), { ...checks, failures: [...problems] }, failedChunks); }; const step = async (name: string, run: () => Promise) => { 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, o.src); checks.decoded = dec.ok; // Lines the decode printed that are not damage (a null-muxer timestamp // line, anything unrecognised): kept, never fatal. if (dec.notes?.length) checks.decodeNotes = dec.notes; if (!dec.ok) fail(`the re-encode does not decode cleanly: ${dec.why ?? "errors"}`); // 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) fatal("the re-encode does not open as a video"); const op = outProbe!; const [outScan, srcScan] = await Promise.all([deps.scan(o.muxed, signal), deps.scan(o.src, signal)]); const n = outScan.pts.length; const ratio = wholeRatio(srcFps, o.fps); const keepRule = state.keepMinStep ? { minStep: state.keepMinStep } : undefined; const expectedPts = expectedCopyPts(srcScan.pts, state.chunks, ratio, o.fps && !ratio ? o.fps : null, keepRule); // The kept frames' select for the source side of every comparison: the // encoder's one constant rule (each comparison starts on a kept frame). const keptSelect = (): string | undefined => (keepRule ? keepSelect(keepRule.minStep) : undefined); const expected = state.chunks.reduce((x, c) => x + c.expectedFrames, 0); checks.frames = [state.sourceFrames, n, expected]; if (n !== expected) fail(`the re-encode holds ${n} frames, not the ${expected} the source's ${state.sourceFrames} give${o.fps ? ` at ${o.fps} fps` : ""}`); 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); 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). if (o.probe.audioStart !== null && op.audioStart !== null) { const srcOff = o.probe.videoStart - o.probe.audioStart; const outOff = op.videoStart - op.audioStart; checks.avOffset = [round(srcOff, 4), round(outOff, 4)]; if (Math.abs(srcOff - outOff) > 0.5 / outFps + 1e-3) { fail(`the re-encode's picture starts ${outOff.toFixed(3)} s from its sound, the source's ${srcOff.toFixed(3)} s`); } } const relFirst = (pts0: number, p: SourceProbe) => pts0 - p.formatStart; if (n && Math.abs(relFirst(outScan.pts[0], op) - relFirst(state.sourceFirstPts, o.probe)) > 0.5 / outFps + 1e-3) { fail(`the re-encode's first frame is ${relFirst(outScan.pts[0], op).toFixed(3)} s into it, the source's ${relFirst(state.sourceFirstPts, o.probe).toFixed(3)} s`); } log( `${tag}: ${n}/${expected} frames, each at its source frame's time (worst ${ts.maxDeviation.toFixed(4)} s off); ` + `the recording dropped frames in ${gaps.count} place(s) (${gaps.totalSeconds.toFixed(3)} s, largest ${gaps.largest.toFixed(3)} s), kept as gaps.`, ); // An excerpt or a cut starts ON a kept frame and holds no gap (after a // dropped frame the two decimations would pair other frames). Each file is // seeked a quarter source frame before THAT FRAME IN ITS OWN command-line // timeline: ffmpeg starts an mpegts's from its video, our mp4 copy's from // its container start, and one time for both landed a frame apart. const [copyT0, srcT0] = n && srcScan.pts.length ? await Promise.all([deps.timelineStart(o.muxed, outScan.pts[0]), deps.timelineStart(o.src, srcScan.pts[0])]) : [op.formatStart, o.probe.formatStart]; const quarter = 0.25 / (srcFps ?? outFps); const seekPair = (rel: number) => ({ at: Number(Math.max(0, rel + op.formatStart - copyT0 - quarter).toFixed(4)), sourceAt: Number(Math.max(0, rel + o.probe.formatStart - srcT0 - quarter).toFixed(4)), }); // `regular`: no step in [start, start + seconds] off one copy frame by // more than a tenth — a window the evidence cutter (an x264 re-encode on its // own time base) carries frame for frame. A cut needs one (review H3); an // excerpt does not (it is no re-encode, and both sides keep frames by the // same rule across any gap). const copyStep = 1 / (state.keepMinStep && srcFps ? srcFps / (ratio ?? 1) : outFps); const irregularAt = (j: number) => Math.abs(expRel[j] - expRel[j - 1] - copyStep) > copyStep / 10; const snap = (t: number, seconds: number, regular = false): { rel: number; regular: boolean } => { const rel = expRel; if (!rel.length) return { rel: t, regular: true }; let lo = 0; let hi = rel.length - 1; while (lo < hi) { const mid = (lo + hi) >> 1; if (rel[mid] < t) lo = mid + 1; else hi = mid; } let i = lo; if (!regular) return { rel: rel[i], regular: true }; for (let j = i + 1; j < rel.length && rel[j] <= rel[i] + seconds + copyStep; j += 1) { if (irregularAt(j)) i = j; } const ok = rel[i] + seconds <= rel[rel.length - 1]; return { rel: rel[i], regular: ok }; }; // The audio, copied: identical packets AT IDENTICAL TIMES — with the // timestamps above, the picture against the sound at every frame. await step("the audio comparison", async () => { const [a, b] = await Promise.all([deps.audioHash(o.src, signal), deps.audioHash(o.muxed, signal)]); checks.audioHash = b.data; const sameTiming = sameAudioTiming(a, b); if (a.packets !== b.packets || a.data !== b.data || !sameTiming) { checks.audio = "different"; fail( `the audio is not the source's packet for packet (${a.packets} → ${b.packets} packets` + `${a.data !== b.data ? ", different bytes" : ""}${!sameTiming ? ", different timing" : ""})`, ); } else { checks.audio = "identical"; log(`${tag}: audio identical (${b.packets} packets, at the source's times).`); } }); // Every other stream and the chapters. 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: srcFps, ...(keepRule ? { sourceSelect: keptSelect() } : {}), sourceWidth: o.probe.width, sourceHeight: o.probe.height, tileFloor: s.wholeFileTileMin, signal, }); const v = judgeWholeFile(cmp, { minFrame: s.wholeFileSsimMin, meanFloor: s.wholeFileSsimMean, sigmaK: s.wholeFileSigmaK, sigmaMinMargin: s.wholeFileSigmaMargin, tileRunFrames: s.wholeFileTileRunFrames, expectedFrames: n, fps: outFps, chromaMinFrame: s.wholeFileChromaMin, chromaMeanFloor: s.wholeFileChromaMean, windowFrames: Math.round(s.wholeFileWindowSeconds * outFps), lowerRunFrames: Math.round(s.wholeFileLowerRunSeconds * outFps), chunkStarts: chunkStartFrames(state.chunks), chunkSigmaK: s.wholeFileChunkSigmaK, chunkMargin: s.wholeFileChunkMargin, }); checks.wholeFile = { fps: outFps, width: WHOLE_FILE_WIDTH, frames: cmp.frames.length, mean: round(v.mean, 4), min: round(v.min, 4), worstAt: round(v.minAt / outFps, 3), minFloor: s.wholeFileSsimMin, meanFloor: s.wholeFileSsimMean, maxGapSeconds: round(gap, 4), sd: round(v.sd, 5), median: round(v.median, 4), windowSeconds: s.wholeFileWindowSeconds, worstLocalMargin: round(v.worstLocalMargin, 4), worstLocalAt: round(v.worstLocalAt / outFps, 3), lowerRunSeconds: s.wholeFileLowerRunSeconds, ...(v.lowerState ? { lowerState: { floor: round(v.lowerState.floor, 4), share: round(v.lowerState.share, 3), runs: v.lowerState.runs } } : {}), ...(v.lowerStateRefused ? { lowerStateRefused: v.lowerStateRefused } : {}), relativeFloor: round(v.relativeFloor, 4), chroma: { mean: round(v.chroma.mean, 4), min: round(v.chroma.min, 4), worstAt: round(v.chroma.minAt / outFps, 3), plane: v.chroma.plane, minFloor: s.wholeFileChromaMin, meanFloor: s.wholeFileChromaMean, }, grid: WHOLE_FILE_GRID, tileFloor: s.wholeFileTileMin, tileRunFrames: s.wholeFileTileRunFrames, ...(v.worstTile ? { worstTile: { col: v.worstTile.col, row: v.worstTile.row, min: round(v.worstTile.min, 4), at: round(v.worstTile.minAt / outFps, 3), longestBelow: v.worstTile.longestBelow, }, } : {}), }; if (v.chunks) { checks.chunkMeans = { count: v.chunks.count, sigmaK: v.chunks.sigmaK, margin: v.chunks.margin, worst: v.chunks.worst ? { chunk: v.chunks.worst.index, plane: v.chunks.worst.plane, mean: round(v.chunks.worst.mean, 4), centre: round(v.chunks.worst.centre, 4), floor: round(v.chunks.worst.floor, 4), ...(v.chunks.worst.joinAt !== undefined ? { joinAt: round(v.chunks.worst.joinAt / outFps, 3) } : {}), } : null, exempt: v.chunks.exempt.map((x) => ({ chunk: x.index, plane: x.plane, why: x.why })), }; } if (v.chunks?.worst) failedChunks.push(v.chunks.worst.index); if (!v.ok) fail(`the whole-file comparison: ${v.why}`); log( `${tag}: whole file SSIM ${v.mean.toFixed(4)} mean over ${cmp.frames.length} frames, lowest ${v.min.toFixed(4)} at ${(v.minAt / outFps).toFixed(2)} s; ` + `colour ${v.chroma.mean.toFixed(4)} mean, lowest ${v.chroma.min.toFixed(4)} (${v.chroma.plane}); ` + `worst tile ${v.worstTile ? `${v.worstTile.col},${v.worstTile.row} at ${v.worstTile.min.toFixed(3)} (${v.worstTile.longestBelow} frame(s) below ${s.wholeFileTileMin})` : "none"}.`, ); }); // Quality on excerpts: spread through the file, ACROSS EVERY CHUNK JOIN and // inside every chunk (the count grows with the chunks). const 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(sampleTimes(srcSeconds, s.qualitySamples, EXCERPT_SECONDS, outFps).map((t) => snap(t + relStart, EXCERPT_SECONDS).rel)); // …and at least one every wholeFileWindowSeconds across the whole file: a // degraded stretch longer than the local floor's window looks steady to // that floor, and always holds one of these. for (let t = s.wholeFileWindowSeconds / 2; t < lastAt; t += s.wholeFileWindowSeconds) times.add(snap(t + relStart, EXCERPT_SECONDS).rel); for (const c of state.chunks) { const from = c.from - state.sourceFirstPts; const to = c.last ? srcSeconds : c.to - state.sourceFirstPts; if (c.index > 0) times.add(snap(Math.min(lastAt, Math.max(0, from - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS).rel); times.add(snap(Math.min(lastAt, Math.max(0, (from + to) / 2 - EXCERPT_SECONDS / 2)) + relStart, EXCERPT_SECONDS).rel); } const scores: number[] = []; for (const rel of [...times].sort((x, y) => x - y)) { const { at, sourceAt } = seekPair(rel); const sourceSelect = keptSelect(); if (signal?.aborted) throw new Error("cancelled"); scores.push( await deps.score({ compacted: o.muxed, source: o.src, at, sourceAt, ...(sourceSelect ? { sourceSelect } : {}), seconds: EXCERPT_SECONDS, fps: o.fps, sourceFps: srcFps, metric, scratchDir: o.scratch, signal }), ); } const mean = scores.reduce((x, y) => x + y, 0) / Math.max(1, scores.length); const min = Math.min(...scores); const [minMean, minSample] = metric === "vmaf" ? [s.vmafMinMean, s.vmafMinSample] : [s.ssimMinMean, s.ssimMinSample]; checks.quality = { metric, mean: round(mean), min: round(min), samples: scores.length, minMean, minSample }; if (mean < minMean || min < minSample) { fail(`${metric.toUpperCase()} ${mean.toFixed(2)} mean, ${min.toFixed(2)} at its worst excerpt (needs ${minMean} and ${minSample})`); } log(`${tag}: ${metric.toUpperCase()} ${mean.toFixed(2)} mean over ${scores.length} excerpts (every join and every chunk), worst ${min.toFixed(2)}.`); }); // Real windows cut from each, compared frame by frame. await step("the window cuts", async () => { const cutTimes = sampleTimes(srcSeconds, CUT_SAMPLES, CUT_SECONDS, outFps).map((t) => ({ t, ...snap(t + relStart, CUT_SECONDS, true) })); checks.cuts = []; checks.cutSsimMin = CUT_SSIM_MIN; for (const { t, rel, regular } of cutTimes) { // SKIPPED, AND SAID (review H3): a recording too choppy for a window the // cutter carries frame for frame. A skipped check is named, never passed. if (!regular) { skip(`the window cut near ${t.toFixed(1)} s: no ${CUT_SECONDS} s from there on without a dropped or uneven frame`); continue; } const { at, sourceAt } = seekPair(rel); const sourceSelect = keptSelect(); const c = await deps.cutCompare({ compacted: o.muxed, source: o.src, at, sourceAt, ...(sourceSelect ? { sourceSelect } : {}), seconds: CUT_SECONDS, fps: o.fps, sourceFps: srcFps, scratchDir: o.scratch, signal }); checks.cuts.push({ at, ssim: round(c.ssim, 4) }); if (c.ssim < CUT_SSIM_MIN) fail(`a window cut at ${at.toFixed(1)} s from the re-encode differs from the same cut of the original (SSIM ${c.ssim.toFixed(3)} < ${CUT_SSIM_MIN})`); if (cutIsOffset(c)) { fail( `a window cut at ${at.toFixed(1)} s from the re-encode lands on other frames than the original's ` + `(SSIM ${c.ssim.toFixed(4)} as cut, ${Math.max(c.earlier, c.later).toFixed(4)} a frame ${c.later > c.earlier ? "later" : "earlier"})`, ); } } log(`${tag}: ${checks.cuts.length} window cut(s) through the evidence cutter compared with the original's${checks.skipped?.length ? `; SKIPPED: ${checks.skipped.join("; ")}` : ""}.`); }); // The recording clock. checks.clock = "none"; await step("the recording clock", async () => { const plan = await planRecordingClock(o.videoDir).catch(() => null); if (plan?.kind === "current") { const old = plan.clock; const targetBytes = (await stat(o.muxed)).size; const okAnchors = (old.anchors ?? []).filter((x: { ok?: boolean }) => x.ok).map((x: { at: number }) => x.at); const fresh = await deps.measureClock({ videoDir: o.videoDir, source: plan.source, container: o.muxed, sourceBytes: old.source.bytes, targetBytes, transcribedAt: old.cues?.transcribedAt ?? null, extra: okAnchors, signal, }); const tol = old.params?.tolerance ?? 0.08; const moved = okAnchors.find((t: number) => Math.abs(clockOffsetAt(old, t).offset - clockOffsetAt(fresh, t).offset) > tol); if (fresh.ok !== old.ok || moved !== undefined) { fail( moved !== undefined ? `the recording clock moved: at ${moved.toFixed(1)} s the map against the re-encode is ${clockOffsetAt(fresh, moved).offset.toFixed(3)} s, against the original ${clockOffsetAt(old, moved).offset.toFixed(3)} s` : `the recording clock's map is ${fresh.ok ? "ok" : "NOT ok"} against the re-encode and ${old.ok ? "ok" : "NOT ok"} against the original`, ); } 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. keep = { ...old, retargeted: { at: deps.now().toISOString(), from: old.target, measured: fresh.id, by: COMPACTION_TOOL }, } as RecordingClock; log(`${tag}: the recording clock re-measured against the re-encode: within ${tol} s of the old map at ${okAnchors.length} anchor(s).`); } else if (plan?.kind === "measure") { checks.clock = "stale"; } }); if (problems.length) throw new VerifyFailure(problems.join("; "), { ...checks, failures: [...problems] }, failedChunks); checks.passed = true; return { checks: checks as SavedVideoCompactedChecks, clock: keep }; } // --- after the swap ------------------------------------------------------------ // THE SECOND CHECK (a step of its own): the pointer read back from disk, and // the file it names read back too (lib readBackCompactedCopy: fsynced, out of // the page cache, size, sha256, container, length). Recorded as // `compacted.recheck`. export async function recheckCompactedCopy(opts: { paths: Paths; videoDir: string; deps?: CompactDeps; signal?: AbortSignal; record?: boolean; }): Promise<{ ok: true; sha256: string } | { ok: false; why: string }> { const pointer = await loadSavedVideo(opts.videoDir); const res = pointer ? await readBackCompactedCopy(pointer, { ...(opts.deps?.sha256 ? { hasher: (f: string) => opts.deps!.sha256!(f, opts.signal) } : {}), }) : ({ ok: false, why: "no pointer" } as const); if (opts.record !== false && pointer?.compacted) { const pointerFile = savedVideoPointerPath(opts.videoDir); await withPointerLock(opts.videoDir, async () => { const read = await readJsonFile(pointerFile); if (!read.ok || !read.value || typeof read.value !== "object") return; const raw = { ...(read.value as Record) }; if (!raw.compacted || typeof raw.compacted !== "object") return; raw.compacted = { ...(raw.compacted as Record), recheck: { at: (opts.deps?.now?.() ?? new Date()).toISOString(), ok: res.ok, ...(res.ok ? {} : { why: res.why }) }, }; await writeJsonAtomic(pointerFile, raw); }); } return res; } export function reviewStateOf(pointer: SavedVideoPointer, onPlatform: boolean, dropOriginal: SavedVideoCompactionSettings["dropOriginal"]): CompactionReviewState | null { if (!pointer.compacted) return null; const original = compactedOriginalOf(pointer); if (!original) return "dropped"; if (reviewIsCurrent(pointer, original)) return "reviewed"; if (!onPlatform) return "awaiting-review"; return dropOriginal === "keep" ? "kept" : "drop-pending"; } async function afterSwap(o: { paths: Paths; videoDir: string; item: CompactItem; settings: SavedVideoCompactionSettings; deps: Required; log: (s: string) => void; tag: string; signal?: AbortSignal; markerToken: string; }): Promise<{ dropped: boolean; review: CompactionReviewState }> { const { log, tag } = o; const recheck = await recheckCompactedCopy({ paths: o.paths, videoDir: o.videoDir, deps: o.deps, ...(o.signal ? { signal: o.signal } : {}) }); const pointer = (await loadSavedVideo(o.videoDir))!; const original = compactedOriginalOf(pointer); const presence = await o.deps.presence(o.videoDir); const state = () => reviewStateOf(pointer, presence.onPlatform, o.settings.dropOriginal) ?? "drop-pending"; if (!recheck.ok) { log(`${tag}: the re-check after the swap FAILED (${recheck.why}): the original ${original?.file ?? "?"} is kept.`); return { dropped: false, review: state() }; } log(`${tag}: re-checked from disk: ${pointer.file} is ${pointer.bytes} bytes, sha256 ${recheck.sha256.slice(0, 12)}…, opens and lasts as verified.`); if (!original) return { dropped: false, review: "dropped" }; if (o.settings.dropOriginal !== "after-verify") { log(`${tag}: dropOriginal is "keep": the original ${original.file} stays until a person drops it.`); return { dropped: false, review: state() }; } if (pointer.compacted?.checks.skipped?.length) { log( `${tag}: the verification skipped ${pointer.compacted.checks.skipped.length} check(s) (${pointer.compacted.checks.skipped.join("; ")}): ` + `"after-verify" does not drop the original ${original.file}.`, ); return { dropped: false, review: state() }; } if (!pointer.compacted?.checks.wholeFile || !pointer.compacted.checks.wholeFile.chroma || !pointer.compacted.checks.chunkMeans) { log( `${tag}: the verification has no whole-file luma, colour AND per-chunk comparison: "after-verify" does not drop the original ${original.file}.`, ); return { dropped: false, review: state() }; } if (!presence.onPlatform) { log( `${tag}: not known to be on its platform (${presence.why}): the original ${original.file} ` + "is NOT dropped — it waits for a person's review (get compaction-review).", ); return { dropped: false, review: state() }; } try { // EXACTLY THE ORIGINAL OF THIS COMPACTED COPY, checked again under the // pointer's lock (kind, sha256, file): a persist landing between this // read and that lock re-labels it, and then nothing is dropped. This step // never passes the former-original confirm (a test scans the callers). const r = await dropSavedAlternate(o.videoDir, original.file, { confirmOriginal: true, expect: { keptAs: "original", sha256: pointer.compacted!.source.sha256, file: original.file }, markerToken: o.markerToken, by: "compact-saved-videos (after-verify)", presence, busy: () => o.deps.busy(o.item.slug, o.item.id), readBack: { hasher: (f) => o.deps.sha256(f, o.signal) }, paths: o.paths, }); log(`${tag}: the original ${original.file} dropped (${formatBytes(r.bytes)} freed; sha256 ${original.sha256?.slice(0, 12) ?? "?"}… recorded on the pointer).`); return { dropped: true, review: "dropped" }; } catch (err) { if (!(err instanceof SavedAlternateRefusal)) throw err; log(`${tag}: the original ${original.file} is kept: ${err.message}`); return { dropped: false, review: state() }; } } // --- the job's body ------------------------------------------------------------ export type CompactSavedVideosResult = { compacted: { slug: string; id: string; dropped: boolean; review: CompactionReviewState; afterSwapError?: string }[]; skipped: { slug: string; id: string; reason: string }[]; failed: { slug: string; id: string; reason: string }[]; stopped?: string; }; // Each item in turn, one at a time. export async function compactSavedVideos( opts: CompactRunOptions & { items: CompactItem[]; mode: "explicit" | "select"; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean }, ): Promise { const result: CompactSavedVideosResult = { compacted: [], skipped: [], failed: [] }; // Stale markers first: none of them may block this run (or any other). await sweepCompactingMarkers(opts.paths, opts.onLog).catch(() => {}); for (const item of opts.items) { if (opts.signal?.aborted) { result.stopped = "cancelled"; break; } if (opts.drainSignal?.aborted) { result.stopped = "drained"; break; } const r = await compactOne({ ...opts, item }); if (r.status === "compacted") { result.compacted.push({ ...item, dropped: r.dropped, review: r.review, ...(r.afterSwapError ? { afterSwapError: r.afterSwapError } : {}) }); } else if (r.status === "skipped") result.skipped.push({ ...item, reason: r.reason }); else if (r.status === "failed") result.failed.push({ ...item, reason: r.reason }); else { result.stopped = r.reason; break; } } opts.onLog( `summary: ${JSON.stringify({ compacted: result.compacted, skipped: result.skipped.length, failed: result.failed, ...(result.stopped ? { stopped: result.stopped } : {}), })}\n`, ); return result; } // The settings in force for a run: settings.json's, each override applied // through the same sanitizer. export function effectiveCompactionSettings( base: SavedVideoCompactionSettings, overrides: Partial> = {}, ): SavedVideoCompactionSettings { return sanitizeSavedVideoCompaction({ ...base, ...Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined)) }); } // --- the review list ------------------------------------------------------------- export type CompactionReviewRow = { slug: string; id: string; state: CompactionReviewState; line: string; availability: Availability | null; onPlatform: boolean; presence: string; original?: SavedVideoAlternate; compactedAt: string; bytes: number; sourceBytes: number; checksPassed: boolean; recheck?: SavedVideoCompacted["recheck"]; // What a reviewer watches: the two files, and a command that plays both. watch: { compacted: string; original?: string; command: string }; // An interrupted drop: the original's file still on disk. leftover?: string; }; // Every compacted video, with what its original is waiting for. export async function listCompactionReview(opts: { paths: Paths; settings: Pick; channelSlug?: string; notAnswering?: string[]; deps?: Pick; }): Promise { const presenceOf = opts.deps?.presence ?? ((d: string) => platformPresence(d, { maxAgeDays: opts.settings.availabilityMaxAgeDays }).catch(() => ({ onPlatform: false, availability: null, why: "its availability could not be read", }))); const entries = await listSavedVideos({ paths: opts.paths, ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}), ...(opts.notAnswering ? { notAnswering: opts.notAnswering } : {}), }); const rows: CompactionReviewRow[] = []; for (const e of entries) { const c = e.pointer.compacted; if (!c) continue; const presence = await presenceOf(e.videoDir); const original = compactedOriginalOf(e.pointer) ?? undefined; const compactedPath = savedVideoPath(e.pointer); const originalPath = original ? path.join(e.pointer.dir, original.file) : undefined; const d = c.originalDropped; const leftover = d && d.fileRemoved === false && (await stat(path.join(e.pointer.dir, d.file)).then(() => true, () => false)) ? path.join(e.pointer.dir, d.file) : undefined; rows.push({ slug: e.slug, id: e.videoId, state: reviewStateOf(e.pointer, presence.onPlatform, opts.settings.dropOriginal)!, line: compactedLine(e.pointer) ?? "", availability: presence.availability, onPlatform: presence.onPlatform, presence: presence.why, ...(original ? { original } : {}), compactedAt: c.at, bytes: e.pointer.bytes, sourceBytes: c.source.bytes, checksPassed: c.checks.passed, ...(c.recheck ? { recheck: c.recheck } : {}), watch: { compacted: compactedPath, ...(originalPath ? { original: originalPath } : {}), command: `smplayer ${JSON.stringify(compactedPath)}${originalPath ? ` ${JSON.stringify(originalPath)}` : ""}`, }, ...(leftover ? { leftover } : {}), }); } return rows; } // --- what a rollback must know, and the markers ------------------------------------ // EVERY POINTER THAT KEEPS AN ORIGINAL (`keptAs: "original"`) OR A FORMER ONE // (`"former-original"`), or has a drop in flight (`pendingDrops`). An editor // built from before this release does not know those labels and would treat // such a copy as an ordinary droppable alternate: while this list is not // empty, do not roll the editor back past this release (OPERATING.md). export type KeptOriginalRow = { slug: string; id: string; active: string; compacted: boolean; kept: { file: string; keptAs: "original" | "former-original"; sha256?: string; bytes: number }[]; pendingDrops: { file: string; keptAs?: string; at: string }[]; }; export async function listKeptOriginals(opts: { paths: Paths; channelSlug?: string; notAnswering?: string[] }): Promise { const entries = await listSavedVideos({ paths: opts.paths, ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}), ...(opts.notAnswering ? { notAnswering: opts.notAnswering } : {}), }); const rows: KeptOriginalRow[] = []; for (const e of entries) { const kept = (e.pointer.alternates ?? []) .filter((a) => a.keptAs === "original" || a.keptAs === "former-original") .map((a) => ({ file: a.file, keptAs: a.keptAs as "original" | "former-original", ...(a.sha256 ? { sha256: a.sha256 } : {}), bytes: a.bytes })); const pending = (e.pointer.pendingDrops ?? []).map((d) => ({ file: d.file, ...(d.keptAs ? { keptAs: d.keptAs } : {}), at: d.at })); if (!kept.length && !pending.length) continue; rows.push({ slug: e.slug, id: e.videoId, active: e.pointer.file, compacted: !!e.pointer.compacted, kept, pendingDrops: pending }); } return rows; } export type CompactionMarkerRow = { slug: string; id: string; dir: string; live: boolean; why: string; marker: unknown }; // Every `.compacting.json` in the store, live or stale, and why. export async function listCompactionMarkers(paths: Paths): Promise { const { markerLiveness } = await import("../lib/compactingMarker-server"); const rows: CompactionMarkerRow[] = []; for (const e of await listSavedVideos({ paths })) { const m = await readCompactingMarker(e.pointer.dir).catch(() => null); if (!m) continue; const l = await markerLiveness(m); rows.push({ slug: e.slug, id: e.videoId, dir: e.pointer.dir, live: l.live, why: l.why, marker: m }); } return rows; } export type KeptFailedEncodeRow = { slug: string; id: string; dir: string; at: string; reason: string; failedChunks: number[]; kept: KeptFailedEncode | null; // A scratch in the store with NO POINTER naming its dir (review G3: left // by a removal before this release, or an interrupted one): nothing will // ever re-verify it; clear it. orphaned?: boolean; bytes?: number; }; async function dirBytes(dir: string): Promise { let n = 0; for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) { const p = path.join(dir, e.name); if (e.isDirectory()) n += await dirBytes(p); else n += await stat(p).then((st) => st.size, () => 0); } return n; } // Every failed encode kept in the store (`/.compact-scratch` with a // failed.json): what failed, what is kept and its size — and every scratch in // the store whose video has no pointer any more, as ORPHANED. export async function listKeptFailedEncodes(paths: Paths): Promise { const rows: KeptFailedEncodeRow[] = []; const owned = new Set(); for (const e of await listSavedVideos({ paths })) { owned.add(path.resolve(e.pointer.dir)); const f = await lastFailure(e.pointer.dir).catch(() => null); if (!f) continue; rows.push({ slug: e.slug, id: e.videoId, dir: path.join(e.pointer.dir, COMPACTION_SCRATCH_DIRNAME), at: f.at, reason: f.reason, failedChunks: f.failedChunks, kept: f.kept }); } for (const slug of await readdir(paths.savedVideosDir).catch(() => [] as string[])) { for (const id of await readdir(path.join(paths.savedVideosDir, slug)).catch(() => [] as string[])) { const storeDir = path.resolve(paths.savedVideosDir, slug, id); const scratch = path.join(storeDir, COMPACTION_SCRATCH_DIRNAME); if (owned.has(storeDir) || !(await stat(scratch).then((st) => st.isDirectory(), () => false))) continue; const f = await lastFailure(storeDir).catch(() => null); rows.push({ slug, id, dir: scratch, at: f?.at ?? "", reason: f?.reason ?? "no failed.json (a run that never finished)", failedChunks: f?.failedChunks ?? [], kept: f?.kept ?? null, orphaned: true, bytes: await dirBytes(scratch), }); } } return rows; } // One video's kept failed encode removed (its whole scratch) — refused while // a compaction of it runs (its marker is live). A video with no pointer: its // ORPHANED scratch in the store, under the same refusal. export async function clearKeptFailedEncode(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string; bytes?: number }> { const { markerLiveness } = await import("../lib/compactingMarker-server"); const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id)); const storeDir = p ? p.dir : path.join(paths.savedVideosDir, item.slug, item.id); const scratch = path.join(storeDir, COMPACTION_SCRATCH_DIRNAME); const f = await lastFailure(storeDir).catch(() => null); const present = await stat(scratch).then((st) => st.isDirectory(), () => false); if (p ? !f : !present) return { cleared: false, why: p ? "no failed encode is kept for it" : "no saved video and no scratch in the store" }; const m = await readCompactingMarker(storeDir).catch(() => null); if (m && (await markerLiveness(m)).live) return { cleared: false, why: "a compaction of it is running" }; const bytes = f?.kept?.bytes ?? (await dirBytes(scratch)); await rm(scratch, { recursive: true, force: true }); return { cleared: true, why: `removed${p ? "" : " (orphaned)"} (${formatBytes(bytes)})`, bytes }; } // Clear one video's marker — refused while it is live (cancel the job instead). export async function clearCompactionMarker(paths: Paths, item: CompactItem): Promise<{ cleared: boolean; why: string }> { const p = await loadSavedVideo(path.join(paths.channelsDir, item.slug, "data", item.id)); if (!p) return { cleared: false, why: "no saved video" }; return clearCompactingMarker(p.dir); }