commit ba817293f0cec7e0fc5e888c0feaff1e6c378635
parent d0d20ac9a0434695364a8d23a6cc652a6169ae80
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 14:34:12 -0500
record-live: parts that together hold more than the longest are joined, proven or not at all
When the landed file would not hold the stream and two or more parts with
a known place do (a from-start part that stopped short and a live-edge
part, or live-edge parts a restart left one after another), they are
joined with ffmpeg's concat, stream-copied (controller/liveJoin.ts).
A live-edge part's place is found by its sound: its first 20 s (8 kHz,
the recording clock's locate) searched in the part before it around its
clock place, a second anchor near the join agreeing within 0.25 s; it is
cut where the part before ends, at the keyframe before the cut, and the
seconds heard twice are recorded. A part that starts after the one before
ends is joined as it is and the gap is stated by the clock; a gap never
counts as covering the stream and needs a person.
Nothing is trusted until proven: the joined file is written under a
scratch name and kept only when its length is its segments' within
max(1 s, 0.2 %) and the sound around every join and at its head matches
its parts. Its parts are removed only after it has landed. Unproven, parts
whose codecs or picture size differ (no re-encode), or a part with no
known place: the longest lands and the rest are kept, as before. The
joins are on the row and in data/<id>/live-joins.json, each segment's
place in the stream, in its file and in the joined file, for the clip
tools.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
10 files changed, 790 insertions(+), 9 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | |
| `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(<id>)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` |
| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.<fmt>, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` |
-| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. After a live-edge fallback, from its start is tried again BESIDE the live-edge recording (never touching it): every 15 min (jittered), one try at a time, at most 8; a try that holds the whole stream when landed recovers the start (startRecovery). Each recorder has a stall watchdog: no growth for liveRecording.stallMinutes (10) stops that recorder, its part kept; while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a new part records — at most 3 restarts an hour and 12 a run (restarts). "insurance"?: true \| "whole" \| false — a live-edge recorder beside a from-start recording of a stream already live, until the start has caught up (+5 min), or for the whole stream; absent, on exactly when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep) when the recording starts. Its part goes at landing only when the landed file holds the whole stream; otherwise it is kept and listed. After an editor restart, a run the shutdown or a crash interrupted restarts by itself (once per run, 3 an hour per stream, never after a Cancel; liveRecording. autoRestartOnBoot): the new run reads the stream's state first — live, it records; ended, it lands what is in staging; unreadable, it starts nothing and the row needs a person. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` |
+| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. After a live-edge fallback, from its start is tried again BESIDE the live-edge recording (never touching it): every 15 min (jittered), one try at a time, at most 8; a try that holds the whole stream when landed recovers the start (startRecovery). Each recorder has a stall watchdog: no growth for liveRecording.stallMinutes (10) stops that recorder, its part kept; while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a new part records — at most 3 restarts an hour and 12 a run (restarts). "insurance"?: true \| "whole" \| false — a live-edge recorder beside a from-start recording of a stream already live, until the start has caught up (+5 min), or for the whole stream; absent, on exactly when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep) when the recording starts. Its part goes at landing only when the landed file holds the whole stream; otherwise it is kept and listed. After an editor restart, a run the shutdown or a crash interrupted restarts by itself (once per run, 3 an hour per stream, never after a Cancel; liveRecording. autoRestartOnBoot): the new run reads the stream's state first — live, it records; ended, it lands what is in staging; unreadable, it starts nothing and the row needs a person. When no single part holds the stream but two or more together hold more, they are joined (-c copy): an overlap at the point their sound shares, a gap stated by the clock; the joined file lands only when PROVEN (its length, its sound around every join), its parts removed only after; the joins are on the row (joins) and in data/<id>/live-joins.json (each segment's place in the stream and in the file). Unproven, or codecs that differ: the longest lands and the rest are kept. A gap needs a person. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` |
| `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` |
| `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -> {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` |
| `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -> {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` |
@@ -494,7 +494,7 @@ get live-recordings [<slug>[/<id>]] [--all] is THE answer to "is this
settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,
capturedSeconds (once landed), coverage, attempts, failureClass,
fallback, lost, startRecovery, restarts, insurance, restart (what the
- boot pass did), missingStream, keptParts, error, mustKeep,
+ boot pass did), joins, missingStream, keptParts, error, mustKeep,
needsAttention, reason, check; `files` names a live-recordings.json that
did not read (set aside, never overwritten). Default: what is recording,
what needs a person, the last 7 days; --all every run kept
diff --git a/common/controller/liveJoin.test.ts b/common/controller/liveJoin.test.ts
@@ -0,0 +1,66 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveJoin.test.ts
+//
+// The join of live-recording parts (controller/liveJoin.ts) with the REAL
+// tools — ffmpeg's cut and concat, ffprobe, the decode the recording clock
+// uses — over two small files made here from one seeded noise "stream": part
+// A is its seconds 0–90, part B its seconds 60–150 (a 30 s overlap), whose
+// recorder started 2 s after its sound (the clock says 62). No network.
+
+const run = promisify(execFile);
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-join-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+const { joinLiveParts, ffmpegJoinDeps } = await import("./liveJoin");
+
+const have = await run("ffmpeg", ["-version"]).then(() => true, () => false);
+
+async function part(name: string, from: number, seconds: number): Promise<string> {
+ const out = path.join(ROOT, name);
+ await run("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `anoisesrc=d=160:c=pink:r=16000:seed=42:a=0.5`,
+ "-f", "lavfi", "-i", "testsrc=s=64x48:r=5:d=160",
+ "-ss", String(from), "-t", String(seconds),
+ "-map", "1:v", "-map", "0:a",
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "10",
+ "-c:a", "aac", "-b:a", "32k",
+ out,
+ ]);
+ return out;
+}
+
+test("two overlapping parts are joined by ffmpeg at the overlap their sound shares, and the join is proven", { skip: !have && "no ffmpeg" }, async () => {
+ const a = await part(".exmpl.live-s.ytdlp.mp4", 0, 90);
+ const b = await part(".exmpl.live-s.ytdlp-edge.mp4", 60, 90);
+ const start = Date.parse("2026-11-21T00:00:00.000Z");
+ const said: string[] = [];
+ const r = await joinLiveParts({
+ parts: [
+ { stem: "a", file: a, seconds: 90, fromStart: true, startedAt: new Date(start).toISOString() },
+ { stem: "b", file: b, seconds: 90, fromStart: false, startedAt: new Date(start + 62_000).toISOString() },
+ ],
+ streamStartedAt: new Date(start).toISOString(),
+ outStem: path.join(ROOT, ".exmpl.live-s.joined"),
+ deps: ffmpegJoinDeps({ ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" }),
+ say: (s) => void said.push(s),
+ });
+ assert.ok(r.ok, `joined: ${"why" in r ? r.why : ""} ${said.join(" | ")}`);
+ if (!r.ok) return;
+ assert.equal(r.joins.length, 1);
+ assert.equal(r.joins[0]!.kind, "overlap");
+ assert.ok(Math.abs(r.joins[0]!.seconds - 30) < 0.1, `overlap ${r.joins[0]!.seconds}`);
+ assert.ok(Math.abs(r.segments[1]!.streamFrom - 60) < 0.1, `B found at ${r.segments[1]!.streamFrom}`);
+ assert.ok(Math.abs(r.seconds - (90 + 90 - r.segments[1]!.fileFrom)) < 1, `joined ${r.seconds} s`);
+ assert.ok(r.seconds >= 149 && r.seconds <= 153, `the union: ${r.seconds} s`);
+ const names = await readdir(ROOT);
+ assert.ok(names.includes(path.basename(r.file)), "the joined file");
+ assert.equal(names.filter((n) => /\.temp\./.test(n)).length, 0, "no scratch left");
+});
diff --git a/common/controller/liveJoin.ts b/common/controller/liveJoin.ts
@@ -0,0 +1,374 @@
+// PARTS OF ONE LIVE RECORDING JOINED INTO ONE FILE — record-live's landing
+// (controller/recordLive.ts), when no single part holds the stream but two or
+// more together hold more than the longest alone: a from-start part that
+// stopped short and a live-edge part (a fallback, the insurance recorder), or
+// live-edge parts a restart left one after the other.
+//
+// WHERE EACH PART SITS IN THE STREAM. A from-start part begins at the
+// stream's second 0. A live-edge part begins about (its startedAt − the
+// stream's start) in, by the clock — and the live edge lags the clock, so its
+// real place is found BY CONTENT: its first PROBE_SECONDS of sound (8 kHz,
+// lib/recordingClock.mjs locate) searched in the part before it, from
+// SEARCH_BEFORE_S before its clock place to SEARCH_AFTER_S after; a match
+// must score ≥ MIN_SCORE and stand MIN_PEAK_RATIO above any other peak, and a
+// second anchor near where the join will be must agree within LAG_TOLERANCE_S.
+//
+// overlap the next part is cut where the one before ends (`-c copy`, which
+// starts at the keyframe at or before the cut: those seconds are
+// heard twice, `duplicatedSeconds`); the joined file's timeline is
+// the stream's from the first part's start
+// gap the next part begins after the one before ends (or overlaps it
+// too little to align): joined as it is, the gap stated by the
+// clock (`basis: "clock"`, about N s). The joined file's timeline
+// is NOT the stream's after it — live-joins.json maps each segment.
+//
+// NOTHING IS TRUSTED UNTIL PROVEN. The joined file is written under a scratch
+// name (no reader takes it for a part) and kept only when its duration is the
+// segments' sum within max(1 s, 0.2 %) and, at every join, the sound 5–25 s
+// before matches the segment before and 5–25 s after matches the segment
+// after (and its head matches the first part). Anything else — a failed
+// check, codecs or sizes that differ (a stream copy cannot join them, and a
+// re-encode of hours is not done here), a part with no known place — and the
+// joined file is removed: the landing lands the longest and keeps the rest,
+// as before. The parts themselves are never touched here; the landing
+// removes a joined part only after the joined file has landed.
+
+import path from "node:path";
+import { rename, rm, writeFile } from "node:fs/promises";
+import { execa } from "execa";
+import { locate } from "../lib/recordingClock.mjs";
+import { decodeExcerpt } from "../lib/recordingClock-server";
+import type { LiveJoin, LiveJoinSegment } from "../lib/liveCapture";
+import "../lib/childKillGuard";
+
+export const JOIN_SAMPLE_RATE = 8000;
+export const JOIN_PROBE_SECONDS = 20;
+export const JOIN_SEARCH_BEFORE_S = 180;
+export const JOIN_SEARCH_AFTER_S = 60;
+export const JOIN_MIN_SCORE = 0.35;
+export const JOIN_MIN_PEAK_RATIO = 1.15;
+export const JOIN_LAG_TOLERANCE_S = 0.25;
+// An overlap shorter than this (by the clock) is not aligned: a gap join.
+export const JOIN_MIN_OVERLAP_S = 25;
+// A part that adds less than this past the union's end is not joined.
+export const JOIN_MIN_GAIN_S = 30;
+export const JOIN_MAX_PARTS = 4;
+// A part shorter than this is never joined (the checks need its sound).
+export const JOIN_MIN_PART_S = 60;
+
+export type JoinStreams = {
+ seconds: number | null;
+ videoCodec: string | null;
+ audioCodec: string | null;
+ width: number | null;
+ height: number | null;
+ sampleRate: number | null;
+ channels: number | null;
+};
+
+export type JoinDeps = {
+ // Mono float samples at `rate` of [from, from + seconds) of `file`.
+ decode: (file: string, from: number, seconds: number, rate: number) => Promise<Float32Array>;
+ // `file` from `from` seconds to its end, stream-copied into `out`; returns
+ // where the copy really starts (the keyframe at or before `from`).
+ cut: (file: string, from: number, out: string) => Promise<number>;
+ // The files one after the other, stream-copied into `out`.
+ concat: (files: string[], out: string) => Promise<void>;
+ probe: (file: string) => Promise<JoinStreams | null>;
+};
+
+export type JoinPart = {
+ stem: string;
+ file: string;
+ seconds: number;
+ fromStart: boolean;
+ // When its recorder started (ISO).
+ startedAt: string | null;
+};
+
+export type JoinResult =
+ | { ok: true; file: string; seconds: number; joins: LiveJoin[]; segments: LiveJoinSegment[]; stems: string[] }
+ | { ok: false; why: string };
+
+type Seg = { part: JoinPart; file: string; fileFrom: number; streamFrom: number; streamFromBasis: "start" | "content" | "clock" };
+
+function matchAt(
+ probe: Float32Array,
+ search: Float32Array,
+ searchStart: number,
+ expected: number | null,
+): { at: number; score: number; ok: boolean; why?: string } {
+ const hit = locate(probe, search, { guard: Math.round(0.25 * JOIN_SAMPLE_RATE) });
+ if (!hit) return { at: NaN, score: 0, ok: false, why: "silent" };
+ const at = searchStart + hit.lag / JOIN_SAMPLE_RATE;
+ const ratio = hit.second > 1e-9 ? hit.score / hit.second : 99;
+ if (hit.score < JOIN_MIN_SCORE) return { at, score: hit.score, ok: false, why: `weak (${hit.score.toFixed(2)})` };
+ if (ratio < JOIN_MIN_PEAK_RATIO) return { at, score: hit.score, ok: false, why: `ambiguous (${ratio.toFixed(2)})` };
+ if (expected !== null && Math.abs(at - expected) > JOIN_LAG_TOLERANCE_S) {
+ return { at, score: hit.score, ok: false, why: `off by ${(at - expected).toFixed(2)} s` };
+ }
+ return { at, score: hit.score, ok: true };
+}
+
+const r3 = (x: number) => Math.round(x * 1000) / 1000;
+
+export async function joinLiveParts(o: {
+ parts: JoinPart[];
+ streamStartedAt: string | null;
+ // `<stem>` for the joined file (its scratch name is `<stem>.temp.<ext>`).
+ outStem: string;
+ deps: JoinDeps;
+ say: (s: string) => void;
+}): Promise<JoinResult> {
+ const { deps, say } = o;
+ const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN;
+ const usable = o.parts.filter((p) => p.seconds >= JOIN_MIN_PART_S);
+ const fromStart = usable.filter((p) => p.fromStart).sort((a, b) => b.seconds - a.seconds);
+ const base = fromStart[0] ?? [...usable].filter((p) => p.startedAt).sort((a, b) => Date.parse(a.startedAt!) - Date.parse(b.startedAt!))[0];
+ if (!base) return { ok: false, why: "no part long enough to join" };
+ // A part's place by the clock, in the stream (from-start base) or after
+ // the base's start (a live-edge base).
+ const clockPlace = (p: JoinPart): number | null => {
+ if (!p.startedAt) return null;
+ const t = Date.parse(p.startedAt);
+ if (base.fromStart) return Number.isFinite(startMs) ? (t - startMs) / 1000 : null;
+ return (t - Date.parse(base.startedAt!)) / 1000;
+ };
+ const others = usable
+ .filter((p) => p !== base && !p.fromStart)
+ .map((p) => ({ p, place: clockPlace(p) }))
+ .filter((x): x is { p: JoinPart; place: number } => x.place !== null)
+ .sort((a, b) => a.place - b.place);
+ if (!others.length) return { ok: false, why: "no other part with a known place in the stream" };
+
+ const probes = new Map<string, JoinStreams>();
+ for (const p of [base, ...others.map((x) => x.p)]) {
+ const s = await deps.probe(p.file);
+ if (!s) return { ok: false, why: `${path.basename(p.file)} cannot be read` };
+ probes.set(p.stem, s);
+ }
+ const b0 = probes.get(base.stem)!;
+ const same = (s: JoinStreams) =>
+ s.videoCodec === b0.videoCodec &&
+ s.audioCodec === b0.audioCodec &&
+ s.width === b0.width &&
+ s.height === b0.height &&
+ s.sampleRate === b0.sampleRate &&
+ s.channels === b0.channels;
+
+ const segs: Seg[] = [{ part: base, file: base.file, fileFrom: 0, streamFrom: 0, streamFromBasis: base.fromStart ? "start" : "clock" }];
+ const joins: LiveJoin[] = [];
+ const scratch: string[] = [];
+ const cleanup = async () => {
+ for (const f of scratch) await rm(f, { force: true });
+ };
+ let unionEnd = base.seconds;
+ const rate = JOIN_SAMPLE_RATE;
+ for (const { p, place } of others) {
+ if (segs.length >= JOIN_MAX_PARTS) break;
+ if (place + p.seconds < unionEnd + JOIN_MIN_GAIN_S) continue;
+ if (!same(probes.get(p.stem)!)) {
+ say(`${path.basename(p.file)} is not joined: its codecs or picture size differ from ${path.basename(base.file)} (a stream copy cannot join them).`);
+ continue;
+ }
+ const last = segs[segs.length - 1]!;
+ // Stream second → seconds into the last segment's file.
+ const inLast = (t: number) => t - last.streamFrom + last.fileFrom;
+ const lastFileEnd = inLast(unionEnd);
+ if (place < unionEnd - JOIN_MIN_OVERLAP_S) {
+ // OVERLAP: where does this part's start sit in the last one?
+ const from = Math.max(last.fileFrom, inLast(place) - JOIN_SEARCH_BEFORE_S);
+ const to = Math.min(lastFileEnd, inLast(place) + JOIN_SEARCH_AFTER_S + JOIN_PROBE_SECONDS);
+ if (to - from < JOIN_PROBE_SECONDS * 1.5) {
+ say(`${path.basename(p.file)}: too little of the part before it to search; not joined.`);
+ break;
+ }
+ const probeA = await deps.decode(p.file, 0, JOIN_PROBE_SECONDS, rate);
+ const search = await deps.decode(last.file, from, to - from, rate);
+ const m1 = matchAt(probeA, search, from, null);
+ if (!m1.ok) {
+ say(`${path.basename(p.file)}: its start is not found in ${path.basename(last.file)} (${m1.why}); not joined — the longest lands, the rest are kept.`);
+ break;
+ }
+ // m1.at: seconds into the last file where this part's second 0 is.
+ const streamAt = m1.at - last.fileFrom + last.streamFrom;
+ const cutAt = unionEnd - streamAt; // seconds into this part
+ // The second anchor, just before where the join will be.
+ const a2 = Math.max(0, cutAt - JOIN_PROBE_SECONDS - 5);
+ const probeB = await deps.decode(p.file, a2, JOIN_PROBE_SECONDS, rate);
+ const expect2 = m1.at + a2;
+ const from2 = Math.max(last.fileFrom, expect2 - 3);
+ const search2 = await deps.decode(last.file, from2, Math.min(lastFileEnd, expect2 + JOIN_PROBE_SECONDS + 3) - from2, rate);
+ const m2 = matchAt(probeB, search2, from2, expect2);
+ if (!m2.ok) {
+ say(`${path.basename(p.file)}: the second check near the join does not agree (${m2.why}); not joined — the longest lands, the rest are kept.`);
+ break;
+ }
+ const segFile = `${o.outStem}.seg${segs.length}.temp${path.extname(p.file) || ".mkv"}`;
+ scratch.push(segFile);
+ const realFrom = await deps.cut(p.file, cutAt, segFile);
+ const dup = Math.max(0, cutAt - realFrom);
+ joins.push({
+ at: 0, // set below, once the segments' lengths are known
+ kind: "overlap",
+ seconds: r3(unionEnd - streamAt),
+ duplicatedSeconds: r3(dup),
+ basis: "content",
+ score: r3(Math.min(m1.score, m2.score)),
+ parts: [last.part.stem, p.stem],
+ });
+ segs.push({ part: p, file: segFile, fileFrom: realFrom, streamFrom: streamAt, streamFromBasis: "content" });
+ unionEnd = streamAt + p.seconds;
+ } else {
+ // GAP (or too little overlap to align): joined as it is, stated.
+ const gap = Math.max(0, place - unionEnd);
+ joins.push({ at: 0, kind: "gap", seconds: r3(gap), basis: "clock", parts: [last.part.stem, p.stem] });
+ segs.push({ part: p, file: p.file, fileFrom: 0, streamFrom: Math.max(place, unionEnd), streamFromBasis: "clock" });
+ unionEnd = Math.max(place, unionEnd) + p.seconds;
+ }
+ }
+ if (segs.length < 2) {
+ await cleanup();
+ return { ok: false, why: "nothing could be joined" };
+ }
+
+ // Each segment's length in the joined file, and where each join falls.
+ const lengths: number[] = [];
+ for (let i = 0; i < segs.length; i++) {
+ const s = segs[i]!;
+ const total = i === 0 ? s.part.seconds : (await deps.probe(s.file))?.seconds ?? null;
+ if (total === null) {
+ await cleanup();
+ return { ok: false, why: `the cut of ${path.basename(s.part.file)} cannot be read` };
+ }
+ lengths.push(i === 0 ? total : total);
+ }
+ const ext = segs.every((s) => /\.ts$/i.test(s.part.file)) ? ".ts" : ".mkv";
+ const temp = `${o.outStem}.temp${ext}`;
+ const final = `${o.outStem}${ext}`;
+ scratch.push(temp);
+ try {
+ await deps.concat(
+ segs.map((s) => s.file),
+ temp,
+ );
+ } catch (err) {
+ await cleanup();
+ return { ok: false, why: `the join failed: ${(err as Error).message.split("\n")[0]}` };
+ }
+
+ // PROVEN, or nothing.
+ const joined = await deps.probe(temp);
+ const sum = lengths.reduce((n, l) => n + l, 0);
+ const tol = Math.max(1, sum * 0.002);
+ if (!joined?.seconds || Math.abs(joined.seconds - sum) > tol) {
+ await cleanup();
+ return { ok: false, why: `the joined file is ${joined?.seconds ?? "?"} s, its parts ${r3(sum)} s: not proven` };
+ }
+ const check = async (segFile: string, segAt: number, joinedAt: number, what: string): Promise<string | null> => {
+ const probe = await deps.decode(segFile, segAt, JOIN_PROBE_SECONDS, rate);
+ const from = Math.max(0, joinedAt - 3);
+ const search = await deps.decode(temp, from, JOIN_PROBE_SECONDS + 6, rate);
+ const m = matchAt(probe, search, from, joinedAt);
+ return m.ok ? null : `${what}: ${m.why}`;
+ };
+ const fails: string[] = [];
+ const head = await check(segs[0]!.file, 5, 5, "the head");
+ if (head) fails.push(head);
+ let at = 0;
+ for (let i = 0; i < segs.length; i++) {
+ const s = segs[i]!;
+ const len = lengths[i]!;
+ // The segment file's own clock: the base whole, a cut from 0, a gap part whole.
+ if (i > 0) {
+ joins[i - 1]!.at = r3(at);
+ const before = segs[i - 1]!;
+ const beforeLen = lengths[i - 1]!;
+ const b = await check(before.file, beforeLen - 25, at - 25, `before join ${i}`);
+ const a = await check(s.file, 5, at + 5, `after join ${i}`);
+ if (b) fails.push(b);
+ if (a) fails.push(a);
+ }
+ at += len;
+ }
+ if (fails.length) {
+ await cleanup();
+ return { ok: false, why: `the joined file does not hold its parts where it should (${fails.join("; ")}): not proven` };
+ }
+ await rename(temp, final);
+ for (const f of scratch) if (f !== temp) await rm(f, { force: true });
+ let joinedFrom = 0;
+ const segments: LiveJoinSegment[] = segs.map((s, i) => {
+ const len = lengths[i]!;
+ const seg: LiveJoinSegment = {
+ stem: s.part.stem,
+ streamFrom: r3(s.streamFrom + 0),
+ streamFromBasis: s.streamFromBasis,
+ fileFrom: r3(s.fileFrom),
+ fileTo: r3(s.fileFrom + len),
+ joinedFrom: r3(joinedFrom),
+ joinedTo: r3(joinedFrom + len),
+ };
+ joinedFrom += len;
+ return seg;
+ });
+ return { ok: true, file: final, seconds: joined.seconds, joins, segments, stems: segs.map((s) => s.part.stem) };
+}
+
+// --- the real tools: ffmpeg/ffprobe -----------------------------------------------
+
+export function ffmpegJoinDeps(bins: { ffmpegBin: string; ffprobeBin: string }, signal?: AbortSignal): JoinDeps {
+ const opt = signal ? { cancelSignal: signal } : {};
+ return {
+ decode: (file, from, seconds, rate) =>
+ decodeExcerpt({ ffmpegBin: bins.ffmpegBin, file, from, seconds, sampleRate: rate, ...(signal ? { signal } : {}) }),
+ cut: async (file, from, out) => {
+ await execa(bins.ffmpegBin, ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-ss", from.toFixed(3), "-i", file, "-map", "0", "-c", "copy", "-avoid_negative_ts", "make_zero", out], opt);
+ // Where the copy starts: its length against the whole's.
+ const whole = await probeJoinStreams(bins.ffprobeBin, file);
+ const part = await probeJoinStreams(bins.ffprobeBin, out);
+ if (!whole?.seconds || !part?.seconds) throw new Error(`the cut of ${path.basename(file)} cannot be read`);
+ return Math.max(0, whole.seconds - part.seconds);
+ },
+ concat: async (files, out) => {
+ const list = `${out}.list.txt`;
+ await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n");
+ try {
+ const mkv = /\.mkv$/i.test(out);
+ await execa(
+ bins.ffmpegBin,
+ ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-map", "0", "-c", "copy", ...(mkv ? ["-f", "matroska"] : ["-f", "mpegts"]), out],
+ opt,
+ );
+ } finally {
+ await rm(list, { force: true });
+ }
+ },
+ probe: (file) => probeJoinStreams(bins.ffprobeBin, file),
+ };
+}
+
+export async function probeJoinStreams(ffprobeBin: string, file: string): Promise<JoinStreams | null> {
+ const r = await execa(ffprobeBin, ["-v", "error", "-show_format", "-show_streams", "-of", "json", file], { reject: false });
+ if (r.exitCode !== 0) return null;
+ try {
+ const j = JSON.parse(String(r.stdout)) as {
+ format?: { duration?: string };
+ streams?: { codec_type?: string; codec_name?: string; width?: number; height?: number; sample_rate?: string; channels?: number }[];
+ };
+ const v = j.streams?.find((s) => s.codec_type === "video");
+ const a = j.streams?.find((s) => s.codec_type === "audio");
+ const d = Number(j.format?.duration);
+ return {
+ seconds: Number.isFinite(d) ? d : null,
+ videoCodec: v?.codec_name ?? null,
+ audioCodec: a?.codec_name ?? null,
+ width: v?.width ?? null,
+ height: v?.height ?? null,
+ sampleRate: a?.sample_rate ? Number(a.sample_rate) : null,
+ channels: a?.channels ?? null,
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts
@@ -168,6 +168,13 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes:
};
extra.push(w[ins.state] ?? `insurance: ${ins.state}`);
}
+ if (v.joins && v.joins.length) {
+ const gaps = v.joins.filter((j) => j.kind === "gap");
+ extra.push(
+ `landed as ${v.joins.length + 1} parts joined` +
+ (gaps.length ? ` — ${gaps.length} GAP${gaps.length === 1 ? "" : "S"} of about ${gaps.map((g) => spanWords(g.seconds)).join(", ")} (by the clock) NOT recorded` : ", each join checked by its sound"),
+ );
+ }
if (v.restarts && v.restarts.count > 0) extra.push(`its recorder was restarted ${v.restarts.count} time${v.restarts.count === 1 ? "" : "s"} (stalled or died while live)`);
if (v.restarts?.refused) extra.push(`NOT restarted again though the stream was live: ${v.restarts.refused}`);
const tail = extra.length ? `; ${extra.join("; ")}` : "";
@@ -319,6 +326,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
...(own?.startRecovery ? { startRecovery: own.startRecovery } : {}),
...(own?.restarts ? { restarts: own.restarts } : {}),
...(own?.insurance ? { insurance: own.insurance } : {}),
+ ...(own?.joins ? { joins: own.joins } : {}),
attempts: own?.attempts ?? row.attempts,
parts,
slug,
@@ -337,6 +345,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
missingStream: own?.missingStream ?? row.missingStream,
startRecovery: own?.startRecovery ?? row.startRecovery,
restarts: own?.restarts ?? row.restarts,
+ joins: own?.joins ?? row.joins,
}),
};
const shown =
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -1684,3 +1684,186 @@ test("slice 4: the insurance knob is parsed and asked again by Record again", as
assert.match((parseRecordLiveRequest({ slug: "s", url: "https://www.youtube.com/watch?v=exmplknob01", insurance: "yes" }) as { error: string }).error, /insurance/);
assert.deepEqual(recordAgainRequest({ slug: "s", insurance: false } as never), { insurance: false });
});
+
+// --- SLICE 5: parts joined into one file, proven or not at all ---------------------
+//
+// A fake "media" file here also says where it sits in the stream and what it
+// sounds like (`stream=<s>;seed=<k>`): the fake decode hands back that sound,
+// a deterministic noise of the stream's own sample index, so the real
+// alignment (lib/recordingClock.mjs locate) finds parts by their sound. The
+// fake cut starts at the keyframe at or before the cut (every 2 s); the fake
+// concat writes the segments it was given (or, `drop`, loses the last).
+
+const noiseAt = (seed: number, n: number) => {
+ let x = (Math.imul(n, 2654435761) + Math.imul(seed + 1, 40503)) >>> 0;
+ x ^= x >>> 13;
+ x = Math.imul(x, 0x5bd1e995) >>> 0;
+ x ^= x >>> 15;
+ return x / 4294967296 - 0.5;
+};
+type FakeSeg = { stream: number; seconds: number; seed: number };
+const readFake = async (file: string): Promise<FakeSeg[]> => {
+ const t = await readFile(file, "utf8").catch(() => "");
+ const segs = /segs=([^;]+)/.exec(t);
+ if (segs) return segs[1]!.split(",").map((x) => { const [s, l, k] = x.split(":").map(Number); return { stream: s!, seconds: l!, seed: k! }; });
+ const num = (k: string, d: number) => Number(new RegExp(`${k}=([\\d.]+)`).exec(t)?.[1] ?? d);
+ return [{ stream: num("stream", 0), seconds: num("seconds", 0), seed: num("seed", 0) }];
+};
+function fakeJoinDeps(o: { drop?: boolean } = {}) {
+ return {
+ decode: async (file: string, from: number, seconds: number, rate: number) => {
+ const segs = await readFake(file);
+ const out = new Float32Array(Math.round(seconds * rate));
+ for (let i = 0; i < out.length; i++) {
+ let t = from + i / rate;
+ for (const g of segs) {
+ if (t < g.seconds) {
+ out[i] = noiseAt(g.seed, Math.round((g.stream + t) * rate));
+ break;
+ }
+ t -= g.seconds;
+ }
+ }
+ return out;
+ },
+ cut: async (file: string, from: number, out: string) => {
+ const [g] = await readFake(file);
+ const real = Math.floor(from / 2) * 2;
+ await writeFile(out, `format=mov,mp4;seconds=${g!.seconds - real};stream=${g!.stream + real};seed=${g!.seed};`);
+ return real;
+ },
+ concat: async (files: string[], out: string) => {
+ const all = (await Promise.all(files.map(readFake))).flat();
+ const kept = o.drop ? all.slice(0, -1) : all;
+ const total = kept.reduce((n, g) => n + g.seconds, 0);
+ await writeFile(out, `format=matroska;seconds=${total};segs=${kept.map((g) => `${g.stream}:${g.seconds}:${g.seed}`).join(",")};`);
+ },
+ probe: async (file: string) => {
+ const t = await readFile(file, "utf8").catch(() => "");
+ if (!/format=/.test(t)) return null;
+ const segs = await readFake(file);
+ return { seconds: segs.reduce((n, g) => n + g.seconds, 0), videoCodec: "h264", audioCodec: "aac", width: 1280, height: 720, sampleRate: 48000, channels: 2 };
+ },
+ };
+}
+
+// An earlier run left a from-start part (stream 0–3000 s) and a live-edge part
+// whose recorder started `edgeClock` s into the stream and whose sound begins
+// at `edgeStream` (the live edge lags the clock); the stream has ended; the
+// boot pass's restart lands what is in staging.
+async function joinCase(id: string, o: { edgeClock: number; edgeStream: number; edgeSeconds: number; edgeSeed?: number; duration?: number; deps?: ReturnType<typeof fakeJoinDeps> }) {
+ const S0 = 1_790_000_000;
+ const iso = (sec: number) => new Date((S0 + sec) * 1000).toISOString();
+ const runAt = iso(0);
+ const stamp = runAt.replace(/[:.]/g, "-");
+ const a = `.${id}.live-${stamp}.ytdlp`;
+ const b = `.${id}.live-${stamp}.ytdlp-edge-a4`;
+ await mkdir(store(), { recursive: true });
+ await writeFile(path.join(store(), `${a}.mp4`), "format=mov,mp4;seconds=3000;stream=0;seed=7;");
+ await writeFile(path.join(store(), `${b}.mp4`), `format=mov,mp4;seconds=${o.edgeSeconds};stream=${o.edgeStream};seed=${o.edgeSeed ?? 7};`);
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await ytChannel();
+ await upsertLiveRecordingRow(paths, YT_SLUG, {
+ id,
+ url: ytUrl(id),
+ platform: "youtube",
+ startedAt: runAt,
+ endedAt: iso(o.edgeClock + o.edgeSeconds),
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ fromStart: true,
+ attempts: 2,
+ mustKeep: true,
+ streamStartedAt: iso(0),
+ parts: [
+ { method: "ytdlp", url: ytUrl(id), fromStart: true, startedAt: iso(1), stem: a },
+ { method: "ytdlp", url: ytUrl(id), fromStart: false, startedAt: iso(o.edgeClock), stem: b },
+ ],
+ restart: { at: iso(9000), by: "boot", state: "asked" },
+ });
+ return incidentRun(id, writesAfter(0), {
+ request: { resumeOf: runAt },
+ meta: { ...YT_META(id), live_status: "was_live", release_timestamp: S0, ...(o.duration ? { duration: o.duration } : {}) },
+ deps: { join: o.deps ?? fakeJoinDeps() },
+ });
+}
+const left = async (id: string) => (await readdir(store())).filter((n) => n.startsWith(`.${id}.`));
+
+test("slice 5: an overlap found by its sound — the two parts joined at it, proven, landed whole; both parts removed only after, the joins recorded", async () => {
+ const id = "exmpljoin01";
+ // The live edge started 20 s behind the clock, at stream second 2401.
+ const { run, calls, log } = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 3000, duration: 5401 });
+ const s = await run;
+ assert.equal(calls.length, 0);
+ assert.equal(s.status, "landed");
+ assert.ok(log.some((l) => /Joined 2 parts/.test(l)), log.filter((l) => /join/i.test(l)).join(""));
+ // 3000 s of the first, then the second from its keyframe at 598 s.
+ assert.equal(s.landed?.seconds, 3000 + (3000 - 598));
+ const row = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(row.joins?.length, 1);
+ const j = row.joins![0]!;
+ assert.equal(j.kind, "overlap");
+ assert.equal(j.basis, "content");
+ assert.equal(j.at, 3000);
+ assert.equal(j.seconds, 599, "the overlap, found by sound (the clock said 579)");
+ assert.equal(j.duplicatedSeconds, 1, "the cut starts a keyframe early");
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.removedParts?.length, 2);
+ assert.ok(row.removedParts!.every((r) => /inside the joined file/.test(r.why)));
+ assert.deepEqual(await left(id), [], "nothing left in staging: the joined file landed, its parts went after");
+ assert.equal(row.needsAttention, false);
+ const { liveJoinsSidecar } = await import("../lib/mediaImport-server");
+ const side = await liveJoinsSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id));
+ assert.equal(side?.segments.length, 2);
+ assert.deepEqual(
+ side!.segments.map((g) => [g.streamFrom, g.streamFromBasis, g.fileFrom, g.joinedFrom, g.joinedTo]),
+ [
+ [0, "start", 0, 0, 3000],
+ [2401, "content", 598, 3000, 5402],
+ ],
+ );
+});
+
+test("slice 5: a gap — joined as they are, the gap stated by the clock, never covering; the row needs a person", async () => {
+ const id = "exmpljoin02";
+ const { run } = await joinCase(id, { edgeClock: 3600, edgeStream: 3600, edgeSeconds: 1800, duration: 5400 });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(s.landed?.seconds, 4800);
+ const row = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(row.joins?.[0]?.kind, "gap");
+ assert.equal(row.joins?.[0]?.basis, "clock");
+ assert.equal(row.joins?.[0]?.seconds, 600);
+ assert.equal(row.coverage?.covers, false, "a gap never holds the whole stream");
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /GAP of about 10 min/);
+ const { liveJoinsSidecar } = await import("../lib/mediaImport-server");
+ const side = await liveJoinsSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id));
+ assert.deepEqual(side!.segments[1], { stem: side!.segments[1]!.stem, streamFrom: 3600, streamFromBasis: "clock", fileFrom: 0, fileTo: 1800, joinedFrom: 3000, joinedTo: 4800 });
+});
+
+test("slice 5: an unprovable join — the sound does not match, or the joined file is not what it should be — lands the longest and keeps the rest", async () => {
+ // (a) The live-edge part's sound is not the stream the first part holds.
+ const id = "exmpljoin03";
+ const a = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, edgeSeed: 99, duration: 5301 });
+ const s = await a.run;
+ assert.equal(s.landed?.seconds, 3000, "the longest");
+ assert.ok(a.log.some((l) => /Not joined/.test(l)));
+ const row = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(row.joins, undefined);
+ assert.equal(row.keptParts?.length, 1, "the other part is kept");
+ assert.equal(row.needsAttention, true);
+ const files = await left(id);
+ assert.equal(files.length, 1);
+ assert.match(files[0]!, /ytdlp-edge-a4\.mp4$/, "no joined or scratch file is left");
+
+ // (b) The joined file lost a segment: its length is not its parts' — not proven.
+ const id2 = "exmpljoin04";
+ const b = await joinCase(id2, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ drop: true }) });
+ const s2 = await b.run;
+ assert.equal(s2.landed?.seconds, 3000);
+ assert.ok(b.log.some((l) => /not proven/.test(l)));
+ const row2 = (await rowOf(id2)).find((r) => r.resumeOf)!;
+ assert.equal(row2.keptParts?.length, 1);
+ assert.deepEqual((await left(id2)).map((n) => /ytdlp-edge-a4\.mp4$/.test(n)), [true]);
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -92,6 +92,7 @@ import {
type KeptPart,
type LiveBootRestartState,
type LiveInsurance,
+ type LiveJoinsRecord,
type RemovedPart,
type LiveFailureClass,
type LivePart,
@@ -105,7 +106,8 @@ import {
type StartRecovery,
type StreamCoverage,
} from "../lib/liveCapture";
-import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import { liveJoinsSidecar, liveRecordingSidecar } from "../lib/mediaImport-server";
+import { ffmpegJoinDeps, joinLiveParts, type JoinDeps } from "./liveJoin";
import { loadLiveRecordingRows, rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server";
import { liveRecordingCheckCommand, liveStallMinutes } from "./liveRecordings";
import { markLiveBootRestart } from "./liveRecordingBoot";
@@ -620,6 +622,9 @@ export type RecordLiveDeps = {
insurancePollMs?: number;
insuranceMarginMs?: number;
insuranceGraceMs?: number;
+ // Joining parts at the landing (controller/liveJoin.ts; default ffmpeg's);
+ // null never joins.
+ join?: JoinDeps | null;
};
export type RecordLiveJobOpts = {
@@ -1931,7 +1936,7 @@ async function recordLiveRunInner(
return summary;
}
candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1));
- const best = candidates[0]!;
+ let best = candidates[0]!;
// Inside the landed file without asking how long the stream is: a shorter
// part of THIS run, both from the start (both begin where the stream's
// record begins).
@@ -1989,7 +1994,76 @@ async function recordLiveRunInner(
lastEndedAt: record.parts.reduce<string | null>((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null),
wholeFromStart: landedFromStart === true && !record.missingStream,
});
- const cov = record.coverage;
+ let cov = record.coverage;
+ // SLICE 5 — PARTS JOINED (controller/liveJoin.ts): the longest does not hold
+ // the stream, and two or more parts with a known place together hold more.
+ // The joined file lands only once PROVEN (its length, its sound at every
+ // join); its parts are removed only after it has landed. Unproven: the
+ // longest lands and the rest are kept, as before.
+ let joinsRecord: Omit<LiveJoinsRecord, "landedAt" | "container"> | null = null;
+ if (!cov.covers && candidates.length >= 2 && !record.missingStream && deps.join !== null) {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ const earlier = new Map(rows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x]));
+ const placed = candidates.flatMap((c) => {
+ const p = c.part ?? earlier.get(c.group.stem);
+ return p && c.seconds !== null ? [{ c, jp: { stem: c.group.stem, file: c.file, seconds: c.seconds, fromStart: p.fromStart, startedAt: p.startedAt ?? null } }] : [];
+ });
+ if (placed.length >= 2) {
+ const joinStem = stemPath("joined");
+ const r = await joinLiveParts({
+ parts: placed.map((x) => x.jp),
+ streamStartedAt: record.streamStartedAt ?? null,
+ outStem: joinStem,
+ deps: deps.join ?? ffmpegJoinDeps({ ffmpegBin: paths.ffmpegBin, ffprobeBin: paths.ffprobeBin }, landSignal),
+ say,
+ }).catch((err: Error) => ({ ok: false as const, why: err.message }));
+ if (r.ok) {
+ const inJoin = new Set(r.stems);
+ const gaps = r.joins.filter((j) => j.kind === "gap");
+ say(
+ `Joined ${r.stems.length} parts into one (${spanWords(r.seconds)}): ` +
+ r.joins
+ .map((j) =>
+ j.kind === "overlap"
+ ? `at ${spanWords(j.at)} an overlap of ${spanWords(j.seconds)} found by their sound${j.duplicatedSeconds ? ` (${j.duplicatedSeconds} s heard twice)` : ""}`
+ : `at ${spanWords(j.at)} a GAP of about ${spanWords(j.seconds)} by the clock — not recorded`,
+ )
+ .join("; ") +
+ ". Each join was checked.",
+ );
+ // Every joined part is inside the joined file (proven): removed
+ // after it lands. The rest keep the coverage rule below.
+ for (const c of placed.map((x) => x.c).filter((c) => inJoin.has(c.group.stem))) {
+ const i = others.findIndex((o) => o.group.stem === c.group.stem);
+ if (i >= 0) others.splice(i, 1);
+ if (toRemove.some((t) => t.group.stem === c.group.stem)) continue;
+ toRemove.push({
+ group: c.group,
+ why: "inside the joined file (its length and its sound at each join checked)",
+ extra: [c.file],
+ o: { group: c.group, why: `joined into ${path.basename(r.file)}`, seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file] },
+ });
+ }
+ const base = r.segments[0]!;
+ best = { file: r.file, seconds: r.seconds, group: { stem: path.basename(joinStem), finished: [path.basename(r.file)], streams: [], scratch: [] } };
+ landedFromStart = base.streamFromBasis === "start";
+ record.joins = r.joins;
+ joinsRecord = { seconds: r.seconds, segments: r.segments, joins: r.joins };
+ const dup = r.joins.reduce((n, j) => n + (j.duplicatedSeconds ?? 0), 0);
+ record.coverage = streamCoverage({
+ capturedSeconds: Math.round((r.seconds - dup) * 1000) / 1000,
+ endMeta,
+ streamStartedAt: record.streamStartedAt ?? null,
+ lastEndedAt: record.parts.reduce<string | null>((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null),
+ // A join with a gap never holds the whole stream.
+ wholeFromStart: landedFromStart && gaps.length === 0,
+ });
+ cov = record.coverage;
+ } else {
+ say(`Not joined: ${r.why}. The longest lands; the rest are kept.`);
+ }
+ }
+ }
// SLICE 2: a from-start try beside the live edge is the landed file and holds
// the whole stream — the start is not lost after all.
if (record.startRecovery && best.part?.recovery === true && cov.covers) {
@@ -2074,6 +2148,11 @@ async function recordLiveRunInner(
if (kept.length) record.keptParts = kept;
record.endedAt = now().toISOString();
if (removed.length) record.removedParts = removed;
+ if (joinsRecord) {
+ await liveJoinsSidecar
+ .write(videoDir, { landedAt: now().toISOString(), container: landed.container, ...joinsRecord })
+ .catch((e: Error) => say(`live-joins.json could not be written (${e.message}); the joins are on the row.`));
+ }
if (record.missingStream) say(`Landed without its ${record.missingStream} stream: it needs a person.`);
if (!record.coverage.covers && record.coverage.streamSeconds !== null && record.coverage.capturedSeconds !== null) {
say(
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -560,8 +560,61 @@ export type LiveRecordingRecord = {
resumeOf?: string;
// The insurance recorder beside the from-start recording (LiveInsurance).
insurance?: LiveInsurance;
+ // The landed file is parts joined into one (controller/liveJoin.ts): where
+ // each join is, and what it is. Also in data/<id>/live-joins.json.
+ joins?: LiveJoin[];
};
+// --- parts joined into one file (controller/liveJoin.ts) ---------------------------
+
+// One join in the joined file: `at` seconds into it. overlap: the two parts
+// share `seconds` of the stream, found by their sound (basis "content");
+// `duplicatedSeconds` are heard twice at the join (the cut starts at a
+// keyframe). gap: `seconds` of the stream are in NEITHER part, by the clock
+// (basis "clock", about) — the joined file's timeline after it is not the
+// stream's (live-joins.json maps it).
+export type LiveJoin = {
+ at: number;
+ kind: "overlap" | "gap";
+ seconds: number;
+ duplicatedSeconds?: number;
+ basis: "content" | "clock";
+ score?: number;
+ parts: string[];
+};
+
+// Where one part is in the joined file and in the stream: the joined file's
+// [joinedFrom, joinedTo) is the part file's [fileFrom, fileTo), which begins
+// `streamFrom` seconds into the stream (basis: "start" a from-start part,
+// "content" found by sound, "clock" by the clock).
+export type LiveJoinSegment = {
+ stem: string;
+ streamFrom: number;
+ streamFromBasis: "start" | "content" | "clock";
+ fileFrom: number;
+ fileTo: number;
+ joinedFrom: number;
+ joinedTo: number;
+};
+
+export const LIVE_JOINS_FILENAME = "live-joins.json";
+
+// data/<id>/live-joins.json: the landed container was joined from parts.
+export type LiveJoinsRecord = {
+ landedAt: string;
+ container: string | null;
+ seconds: number;
+ segments: LiveJoinSegment[];
+ joins: LiveJoin[];
+};
+
+export function coerceLiveJoins(raw: unknown): LiveJoinsRecord | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as LiveJoinsRecord;
+ if (!Array.isArray(r.segments) || !Array.isArray(r.joins) || typeof r.seconds !== "number") return null;
+ return r;
+}
+
// --- the insurance recorder: the live edge while the start catches up ----------
//
// A from-start recording of a stream that has run for a while is BEHIND the
diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts
@@ -35,6 +35,7 @@ import type {
LostSpan,
LiveBootRestart,
LiveInsurance,
+ LiveJoin,
LiveRestarts,
MissingStream,
StartRecovery,
@@ -82,6 +83,7 @@ export type LiveRecordingRow = {
resumeOf?: string;
restart?: LiveBootRestart;
insurance?: LiveInsurance;
+ joins?: LiveJoin[];
acknowledgedAt?: string;
acknowledgedBy?: string;
// The run (its jobId, else its startedAt) that later landed this id.
@@ -159,6 +161,8 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s
// (startRecovery "recovered")
// restarts refused the stream was live and its recorder
// stalled or died once too often
+// joined with a gap parts joined into the landed file
+// with seconds of the stream in none
// one stream missing it landed without video or audio
// parts kept on disk (keptParts) until acknowledged, whatever lands
// later: a later recording does not
@@ -167,7 +171,7 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s
// recording that holds the whole stream (supersededBy).
export function rowNeedsAttention(
r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy"> &
- Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart">>,
+ Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins">>,
): boolean {
if (r.acknowledgedAt) return false;
if (r.keptParts && r.keptParts.length > 0) return true;
@@ -180,6 +184,8 @@ export function rowNeedsAttention(
if (r.status === "cancelled" && r.mustKeep === true) return true;
if (r.fallback === "live-edge" && r.startRecovery?.state !== "recovered") return true;
if (r.restarts?.refused) return true;
+ // Landed as parts joined with a gap: those seconds are in no part.
+ if (r.joins?.some((j) => j.kind === "gap")) return true;
return r.missingStream !== undefined;
}
@@ -259,6 +265,7 @@ export function rowOfRecord(
...(rec.restarts ? { restarts: { ...rec.restarts, at: [...rec.restarts.at] } } : {}),
...(rec.resumeOf ? { resumeOf: rec.resumeOf } : {}),
...(rec.insurance ? { insurance: { ...rec.insurance } } : {}),
+ ...(rec.joins && rec.joins.length ? { joins: rec.joins.map((j) => ({ ...j, parts: [...j.parts] })) } : {}),
};
}
diff --git a/common/lib/mediaImport-server.ts b/common/lib/mediaImport-server.ts
@@ -8,11 +8,14 @@ import {
coerceMediaImport,
type MediaImportEntry,
} from "./mediaImport";
-import { LIVE_RECORDING_FILENAME, coerceLiveRecording } from "./liveCapture";
+import { LIVE_JOINS_FILENAME, LIVE_RECORDING_FILENAME, coerceLiveJoins, coerceLiveRecording } from "./liveCapture";
export const mediaImportSidecar = sidecar(MEDIA_IMPORT_FILENAME, sidecarField(coerceMediaImport));
export const liveRecordingSidecar = sidecar(LIVE_RECORDING_FILENAME, sidecarField(coerceLiveRecording));
+// A landed live recording joined from parts (controller/liveJoin.ts): the
+// segments and the joins, for the clip tools.
+export const liveJoinsSidecar = sidecar(LIVE_JOINS_FILENAME, sidecarField(coerceLiveJoins), { indent: 2 });
export async function recordMediaImport(videoDir: string, entry: MediaImportEntry): Promise<void> {
const prev = await mediaImportSidecar.load(videoDir);
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -2698,7 +2698,14 @@ export function usage() {
" an hour per stream, never after a Cancel; liveRecording.",
" autoRestartOnBoot): the new run reads the stream's state first — live,",
" it records; ended, it lands what is in staging; unreadable, it starts",
- " nothing and the row needs a person.",
+ " nothing and the row needs a person. When no single part holds the",
+ " stream but two or more together hold more, they are joined (-c copy):",
+ " an overlap at the point their sound shares, a gap stated by the clock;",
+ " the joined file lands only when PROVEN (its length, its sound around",
+ " every join), its parts removed only after; the joins are on the row",
+ " (joins) and in data/<id>/live-joins.json (each segment's place in the",
+ " stream and in the file). Unproven, or codecs that differ: the longest",
+ " lands and the rest are kept. A gap needs a person.",
"",
"get live-recordings [<slug>[/<id>]] [--all] is THE answer to \"is this",
" stream being recorded, and is it growing\" — never a job for the video",
@@ -2709,7 +2716,7 @@ export function usage() {
" settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,",
" capturedSeconds (once landed), coverage, attempts, failureClass,",
" fallback, lost, startRecovery, restarts, insurance, restart (what the",
- " boot pass did), missingStream, keptParts, error, mustKeep,",
+ " boot pass did), joins, missingStream, keptParts, error, mustKeep,",
" needsAttention, reason, check; `files` names a live-recordings.json that",
" did not read (set aside, never overwritten). Default: what is recording,",
" what needs a person, the last 7 days; --all every run kept",