commit 69a0701387fd4bb762c3b387d035980f76b07d88
parent 11c4cf79a0dc5766a5b80bcd8a77993934b134b6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 26 Oct 2026 17:42:57 -0400
record-live on YouTube: separate video + audio streams, merged; an unmerged pair left by a cancel or a crash is merged and landed
A YouTube live stream with --live-from-start offers only separate DASH video and
audio, so `-f best` failed at once ("Requested format is not available") and the
record reported "nothing was recorded" (2026-10-26, 5-XlMxKT494).
- liveFormatSelector(maxHeight, separate): separate is
`bv*[height<=H]+ba/b[height<=H]/bv*+ba/b` (null: `bv*+ba/b`), with
--merge-output-format mp4/mkv and `-o <stem>.%(ext)s`. Muxed (Rumble, Kick)
is unchanged, argv byte for byte.
- `separate` on the request (record-live body, the Record live form's Streams
choice); default by platform: YouTube true, everything else false.
- The landing reads each part's files by stem (livePartFiles): a finished file
first; else its unmerged `.f<id>.<ext>` streams merged by ffmpeg -c copy
(mp4 +faststart when the codecs fit, else mkv; resolvePart), an earlier run's
pair too. Video with no audio is named as not landable.
- A muxed request refused for want of a format says to try "separate": true.
- Tests: a fake yt-dlp (refuses a muxed selector, writes .f270.mp4 + .f234.m4a)
through the real spawnRecorder and the real ffprobe: merged by yt-dlp, and
cancelled mid-record (merged here) both land an h264+aac mp4.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 578 insertions(+), 50 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -120,7 +120,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), "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; the longest part wins. Refused for a stream that is not live. | `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"}'` |
+| `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. | `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"}'` |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
| `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` |
| `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -436,6 +436,7 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150
```sh
pnpm ops record-live --json '{"slug":"example-rumble","url":"https://rumble.com/v1abcde-a-live-show.html"}'
pnpm ops record-live --json '{"slug":"example-kick","url":"https://kick.com/somechannel","doNotClean":true,"note":"keep"}'
+pnpm ops record-live --json '{"slug":"example-youtube","url":"https://www.youtube.com/watch?v=abcdefghijk","fromStart":true}'
pnpm ops import-media --json '{"slug":"example-rumble","path":"/home/me/Podcasts/v1embed.from-start.mp4.part","url":"https://rumble.com/v1abcde-a-live-show.html","move":true,"dryRun":true}' --wait
pnpm ops import-media --json '{"slug":"example-archive","path":"/mnt/old/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"}}' --wait
pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":"keep"}'
@@ -447,8 +448,13 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
`--live-from-start` reads (the private fork's Rumble support). When Rumble refuses yt-dlp, the page is opened in a
browser under `xvfb-run` for its own playlist and ffmpeg records that. Kick's live playlist holds ~30 s, so on
Kick the stream's VOD is polled from its first segment while the channel's live stream records beside it; the
- longer part lands. `job cancel` stops the recorders with SIGINT and lands what they have. A stream that is not
- live is refused: download it, or import a recording of it.
+ longer part lands. A YouTube live stream from its start offers no single stream with both video and audio,
+ only separate DASH video and audio, so on YouTube the recording takes the video at `maxHeight` (720 by default;
+ `null` for the tallest) plus the best audio and merges them when it ends (mp4, else mkv); `"separate"` sets this
+ for any stream (`false`: one muxed stream, as on Rumble and Kick). `job cancel` stops the recorders with SIGINT
+ and lands what they have: video and audio left unmerged by a cancel or a crash are merged then (`-c copy`), and
+ an earlier run's unmerged pair is merged and landed by the next run. A stream that is not live is refused:
+ download it, or import a recording of it.
- `import-media` (Media → **Import a file**) makes one file from outside the archive a normal transcribed item:
`"url"` makes or refreshes the record from its page (metadata only, under the id the archive keys it by — a
Rumble URL's id, not the embed id in the file name), `"id"` names a record already here, `"meta"` describes one
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -2,6 +2,8 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
import path from "node:path";
import type { ChannelConfig } from "../lib/channelConfig";
import type { MediaProbe } from "../lib/mediaImport";
@@ -378,3 +380,182 @@ test("choosePlaylist: the master's variant by height, else the page's DVR chunkl
"https://cdn/x/chunklist_i1_DVR.m3u8",
);
});
+
+// --- YouTube: separate video + audio streams (2026-10-26) ----------------------------
+//
+// A YouTube live stream with --live-from-start offers only separate DASH video
+// and audio, and `-f best` failed at once ("Requested format is not
+// available"). The recorder here is a FAKE yt-dlp (a real child, through the
+// real spawnRecorder) that refuses a muxed selector the way YouTube's did and,
+// for `bv*+ba`, writes the two streams as `<stem>.f270.mp4` + `<stem>.f234.m4a`
+// from small real files made by ffmpeg — then merges them (FAKE_YT_MODE=finish)
+// or waits for the SIGINT and exits without merging (FAKE_YT_MODE=hang, a cancel
+// or a crash before the merge). The landing is the real one with the real
+// ffprobe; only the audio extraction is stubbed. Nothing is fetched.
+
+const FAKE_YTDLP_SOURCE = `#!/usr/bin/env node
+import { copyFileSync, rmSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+const argv = process.argv.slice(2);
+const f = argv[argv.indexOf("-f") + 1];
+const out = argv[argv.indexOf("-o") + 1];
+const id = argv.at(-1).split("v=")[1];
+if (!f.includes("+ba")) {
+ process.stderr.write("ERROR: [youtube] " + id + ": Requested format is not available. Use --list-formats for a list of available formats\\n");
+ process.exit(1);
+}
+const stem = out.replace(/\\.%\\(ext\\)s$/, "");
+const v = stem + ".f270.mp4";
+const a = stem + ".f234.m4a";
+copyFileSync(process.env.FAKE_YT_VIDEO, v);
+copyFileSync(process.env.FAKE_YT_AUDIO, a);
+console.log("[download] Destination: " + v);
+if (process.env.FAKE_YT_MODE === "hang") {
+ process.on("SIGINT", () => process.exit(130));
+ setInterval(() => {}, 1000);
+} else {
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", v, "-i", a, "-map", "0:v", "-map", "1:a", "-c", "copy", "-f", "mp4", stem + ".temp.mp4"]);
+ execFileSync("mv", [stem + ".temp.mp4", stem + ".mp4"]);
+ rmSync(v);
+ rmSync(a);
+ console.log('[Merger] Merging formats into "' + stem + '.mp4"');
+}
+`;
+const YT_SLUG = "synth-youtube";
+const YT_CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@Synth", platform: "youtube", name: "Synth YT" } as ChannelConfig;
+const run = promisify(execFile);
+const MEDIA = path.join(ROOT, "media");
+const VIDEO = path.join(MEDIA, "video-only.mp4");
+const AUDIO = path.join(MEDIA, "audio-only.m4a");
+const FAKE_YTDLP = path.join(ROOT, "fake-yt-dlp.mjs");
+// Fragmented, as a DASH live stream's appended segments are.
+const FRAG = ["-movflags", "frag_keyframe+empty_moov+default_base_moof"];
+let ytReady: Promise<void> | null = null;
+const ytSetup = () =>
+ (ytReady ??= (async () => {
+ await mkdir(path.join(CORPUS, "channels", YT_SLUG, "data"), { recursive: true });
+ await writeFile(path.join(CORPUS, "channels", YT_SLUG, "config.json"), JSON.stringify(YT_CONFIG));
+ await mkdir(MEDIA, { recursive: true });
+ await run("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=320x180:rate=25:duration=3", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-g", "25", ...FRAG, "-f", "mp4", VIDEO]);
+ await run("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=3", "-c:a", "aac", ...FRAG, "-f", "mp4", AUDIO]);
+ await writeFile(FAKE_YTDLP, FAKE_YTDLP_SOURCE, { mode: 0o755 });
+ process.env.FAKE_YT_VIDEO = VIDEO;
+ process.env.FAKE_YT_AUDIO = AUDIO;
+ })());
+// No heavy-slot gate in a temp root: the merge runs ffmpeg directly.
+const ytPaths = { ...paths, ytdlpBin: FAKE_YTDLP, monorepoRoot: ROOT };
+const realLand = {
+ transcode: async (o: { videoDir: string; fmt: string }) => {
+ await writeFile(path.join(o.videoDir, `audio.${o.fmt}`), "audio");
+ },
+ freeBytes: async () => 1e15,
+};
+const YT_META = (id: string) => ({
+ id,
+ extractor: "youtube",
+ title: "A YouTube live stream",
+ live_status: "is_live",
+ formats: [
+ { format_id: "234", protocol: "http_dash_segments_generator", vcodec: "none", acodec: "mp4a.40.2", url: "https://dash.example/234" },
+ { format_id: "270", protocol: "http_dash_segments_generator", height: 1080, vcodec: "avc1", acodec: "none", url: "https://dash.example/270" },
+ ],
+});
+
+async function streamsOf(file: string): Promise<{ v: string | null; a: string | null; seconds: number }> {
+ const { stdout } = await run("ffprobe", ["-v", "error", "-show_format", "-show_streams", "-of", "json", file]);
+ const j = JSON.parse(stdout) as { format: { duration: string }; streams: { codec_type: string; codec_name: string }[] };
+ return {
+ v: j.streams.find((s) => s.codec_type === "video")?.codec_name ?? null,
+ a: j.streams.find((s) => s.codec_type === "audio")?.codec_name ?? null,
+ seconds: Number(j.format.duration),
+ };
+}
+
+async function ytRun(id: string, opts: { mode: "finish" | "hang"; separate?: boolean; log?: string[] }) {
+ await ytSetup();
+ process.env.FAKE_YT_MODE = opts.mode;
+ const ac = new AbortController();
+ const slugStore = path.join(paths.savedVideosDir, YT_SLUG);
+ let stopper: NodeJS.Timeout | null = null;
+ if (opts.mode === "hang") {
+ // Cancel once both streams are on disk.
+ stopper = setInterval(async () => {
+ const names = await readdir(slugStore).catch(() => [] as string[]);
+ if (names.some((n) => n.endsWith(".f270.mp4")) && names.some((n) => n.endsWith(".f234.m4a"))) ac.abort();
+ }, 100);
+ }
+ try {
+ return await recordLiveRun({
+ paths: ytPaths,
+ request: { slug: YT_SLUG, url: `https://www.youtube.com/watch?v=${id}`, ...(opts.separate !== undefined ? { separate: opts.separate } : {}) },
+ plan: { url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", id },
+ channelConfig: YT_CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: (l) => void opts.log?.push(l),
+ signal: ac.signal,
+ deps: { refresh: refreshWith(YT_META(id)), fetchText: async () => { throw new Error("no playlist read is expected"); }, land: realLand, freeBytes: async () => 1e15, handoff },
+ });
+ } finally {
+ if (stopper) clearInterval(stopper);
+ }
+}
+
+test("YouTube, muxed only (the 2026-10-26 failure): the fake refuses `best`, and the log says to record separate streams", async () => {
+ const log: string[] = [];
+ await assert.rejects(ytRun("ytmuxed0001", { mode: "finish", separate: false, log }), /nothing was recorded/);
+ assert.ok(log.some((l) => /Requested format is not available/.test(l)));
+ assert.ok(log.some((l) => /"separate": true/.test(l)));
+});
+
+test("YouTube: separate video + audio by default, merged by yt-dlp, the merged mp4 lands with its sound", async () => {
+ const log: string[] = [];
+ const s = await ytRun("ytmerged001", { mode: "finish", log });
+ assert.ok(log.some((l) => /bv\*\[height<=720\]\+ba\/b\[height<=720\]\/bv\*\+ba\/b/.test(l)), "the separate selector at 720p");
+ assert.ok(log.some((l) => /--merge-output-format mp4\/mkv/.test(l)));
+ assert.equal(s.status, "landed");
+ const dir = path.join(CORPUS, "channels", YT_SLUG, "data", "ytmerged001");
+ const pointer = await loadSavedVideo(dir);
+ assert.equal(pointer?.file, "source-media.mp4");
+ const stored = await streamsOf(s.landed!.container!);
+ assert.deepEqual([stored.v, stored.a], ["h264", "aac"]);
+ assert.ok(Math.abs(stored.seconds - 3) < 0.5, `${stored.seconds} s`);
+ const rec = await liveRecordingSidecar.load(dir);
+ assert.equal(rec?.separate, true);
+ assert.notEqual(rec?.parts[0]?.merged, true, "yt-dlp merged it");
+ const left = (await readdir(path.join(paths.savedVideosDir, YT_SLUG))).filter((n) => n.startsWith(".ytmerged001"));
+ assert.deepEqual(left, [], "no staging left");
+});
+
+test("YouTube cancelled mid-record: the two unmerged streams are merged by record-live, and a playable mp4 with sound lands", async () => {
+ const log: string[] = [];
+ const s = await ytRun("ytcancel001", { mode: "hang", log });
+ assert.equal(s.status, "cancelled");
+ assert.ok(log.some((l) => /left unmerged/.test(l)), log.join(""));
+ assert.ok(s.landed && s.landed.seconds !== null && Math.abs(s.landed.seconds - 3) < 0.5, JSON.stringify(s.landed));
+ const dir = path.join(CORPUS, "channels", YT_SLUG, "data", "ytcancel001");
+ const pointer = await loadSavedVideo(dir);
+ assert.equal(pointer?.file, "source-media.mp4");
+ const stored = await streamsOf(s.landed!.container!);
+ assert.deepEqual([stored.v, stored.a], ["h264", "aac"]);
+ const rec = await liveRecordingSidecar.load(dir);
+ assert.equal(rec?.status, "cancelled");
+ assert.equal(rec?.parts[0]?.merged, true);
+ const left = (await readdir(path.join(paths.savedVideosDir, YT_SLUG))).filter((n) => n.startsWith(".ytcancel001"));
+ assert.deepEqual(left, [], "the streams and the merge are gone from staging");
+});
+
+test("an earlier run's unmerged streams are merged and landed by the next run", async () => {
+ await ytSetup();
+ const slugStore = path.join(paths.savedVideosDir, YT_SLUG);
+ await mkdir(slugStore, { recursive: true });
+ const stem = path.join(slugStore, ".ytleft00001.live-2026-10-25T01-00-00-000Z.ytdlp");
+ await run("cp", [VIDEO, `${stem}.f270.mp4`]);
+ await run("cp", [AUDIO, `${stem}.f234.mp4`]);
+ const log: string[] = [];
+ // This run records nothing (muxed only, refused): the leftover is what lands.
+ const s = await ytRun("ytleft00001", { mode: "finish", separate: false, log });
+ assert.equal(s.status, "landed");
+ assert.ok(log.some((l) => /An earlier recording left 1 part/.test(l)));
+ assert.equal((await streamsOf(s.landed!.container!)).a, "aac");
+ assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".ytleft00001")), []);
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -23,6 +23,13 @@
// Chromium under xvfb (liveSniff.mjs) for its
// playlist, then ffmpeg records that from its first
// listed segment.
+// youtube path A with SEPARATE streams (`separate`, the
+// platform's default): from its start YouTube offers
+// only DASH video and audio, so the video at the
+// height plus the best audio, `<stem>.f<id>.<ext>`
+// while recording, merged by yt-dlp at the end; a
+// pair left unmerged (a cancel, a crash) is merged
+// here before the landing (resolvePart).
// kick the ongoing VOD's EVENT playlist polled from segment
// 0, each new segment appended (pollEventPlaylist),
// and — the operator's by-hand workflow, as insurance
@@ -51,14 +58,18 @@ import {
LIVE_DEFAULT_MAX_HEIGHT,
extractionRefused,
ffmpegLiveArgs,
- liveFormatSelector,
+ formatUnavailable,
liveFromStartUnsupported,
+ livePartFiles,
+ mergeStreamsArgs,
newSegments,
parsePlaylist,
pickVariant,
playlistReach,
+ separateStreamsDefault,
ytdlpLiveArgs,
type LivePart,
+ type LivePartFiles,
type LivePartMethod,
type LiveRecordingRecord,
type MediaPlaylist,
@@ -74,6 +85,7 @@ import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore";
import { getFreeBytes } from "../lib/diskSpace";
import { formatBytes } from "../lib/format";
import { applyPendingKeep } from "../lib/pendingKeep-server";
+import { mp4CanHold, type MediaProbe } from "../lib/mediaImport";
import { getRegistry } from "../jobs/registry";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import { channelExtraArgs, configForVideoUrl } from "../ytdlp/channelArgs";
@@ -100,6 +112,7 @@ export const RECORD_LIVE_BODY_KEYS = [
"url",
"fromStart",
"maxHeight",
+ "separate",
"transcribe",
"doNotClean",
"note",
@@ -130,6 +143,10 @@ export type RecordLiveRequest = {
fromStart?: boolean;
// null = the tallest. Default LIVE_DEFAULT_MAX_HEIGHT.
maxHeight?: number | null;
+ // Separate video + audio streams, merged (true), or one muxed stream
+ // (false). Default: the platform's (separateStreamsDefault — YouTube
+ // separate, Rumble and Kick muxed).
+ separate?: boolean;
transcribe?: boolean;
doNotClean?: boolean;
note?: string;
@@ -156,7 +173,7 @@ export function parseRecordLiveRequest(body: Record<string, unknown>): RecordLiv
if (url) out.url = url;
if (id) out.id = id;
if (maxHeight !== undefined) out.maxHeight = maxHeight;
- for (const k of ["fromStart", "transcribe", "doNotClean", "dryRun"] as const) {
+ for (const k of ["fromStart", "separate", "transcribe", "doNotClean", "dryRun"] as const) {
const v = body[k];
if (v === undefined) continue;
if (typeof v !== "boolean") return { error: `"${k}" must be true or false` };
@@ -488,6 +505,8 @@ export type RecordLiveDeps = {
// kick.com/<channel>/videos, its first entry).
kickVod?: (channel: string, signal: AbortSignal) => Promise<{ id: string; url: string } | null>;
poll?: typeof pollEventPlaylist;
+ // ffmpeg over a separate-streams part left unmerged (mergeStreamsArgs).
+ merge?: (args: string[], signal: AbortSignal) => Promise<void>;
freeBytes?: (dir: string) => Promise<number>;
now?: () => Date;
};
@@ -565,6 +584,76 @@ async function defaultKickVod(
}
}
+// ffmpeg through the heavy slot when the checkout has the gate (a stream copy
+// of hours of video, as the landing's remux is).
+export async function runFfmpegHeavy(paths: Paths, args: string[], signal?: AbortSignal): Promise<void> {
+ const gate = paths.monorepoRoot ? path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs") : null;
+ const gated = gate !== null && (await stat(gate).then((s) => s.isFile(), () => false));
+ await execa(gated ? process.execPath : paths.ffmpegBin, gated ? [gate, "--heavy", "--", paths.ffmpegBin, ...args] : args, {
+ ...(signal ? { cancelSignal: signal } : {}),
+ });
+}
+
+export type ResolvedPart = { file: string; seconds: number | null; merged?: boolean } | { error: string };
+
+// WHAT ONE PART LANDS AS (null: it holds nothing). A finished file ffprobe
+// reads, with audio — the longest when there are several. Else its separate
+// streams, left unmerged by a cancel or a crash: a stream with video and audio
+// as it is; a video stream and an audio stream merged by ffmpeg (`-c copy`,
+// mp4 +faststart when the codecs fit, else mkv) into `<stem>.merged.<ext>`;
+// an audio stream alone as it is. Video with no audio is not landable.
+export async function resolvePart(
+ g: LivePartFiles,
+ dir: string,
+ io: {
+ probe: (file: string) => Promise<MediaProbe | null>;
+ merge: (args: string[]) => Promise<void>;
+ say: (s: string) => void;
+ },
+): Promise<ResolvedPart | null> {
+ const read = async (names: readonly string[]) => {
+ const out: { file: string; probe: MediaProbe }[] = [];
+ for (const n of names) {
+ const file = path.join(dir, n);
+ if ((await stat(file).then((s) => s.size, () => 0)) === 0) continue;
+ const p = await io.probe(file);
+ if (p) out.push({ file, probe: p });
+ }
+ return out.sort((a, b) => (b.probe.seconds ?? -1) - (a.probe.seconds ?? -1));
+ };
+ const finishedAll = await read(g.finished);
+ const finished = finishedAll.filter((f) => f.probe.audioCodec);
+ if (finished.length) return { file: finished[0]!.file, seconds: finished[0]!.probe.seconds };
+ const streams = await read(g.streams);
+ if (!streams.length) {
+ if (finishedAll.length) return { error: `${path.basename(finishedAll[0]!.file)} holds no audio: nothing to transcribe` };
+ const bytes = await Promise.all([...g.finished, ...g.streams].map((n) => stat(path.join(dir, n)).then((s) => s.size, () => 0)));
+ return bytes.some((b) => b > 0) ? { error: "ffprobe cannot read what it holds" } : null;
+ }
+ const both = streams.find((s) => s.probe.videoCodec && s.probe.audioCodec);
+ if (both) return { file: both.file, seconds: both.probe.seconds };
+ const video = streams.find((s) => s.probe.videoCodec);
+ const audio = streams.find((s) => s.probe.audioCodec);
+ if (video && audio) {
+ const mp4 = mp4CanHold(video.probe.videoCodec, audio.probe.audioCodec);
+ const output = path.join(dir, `${g.stem}.merged.${mp4 ? "mp4" : "mkv"}`);
+ io.say(
+ `${g.stem}: its video and audio streams were left unmerged (${path.basename(video.file)}, ${path.basename(audio.file)}); ` +
+ `merging them (stream copy) into ${path.basename(output)}.`,
+ );
+ await rm(output, { force: true });
+ await io.merge(mergeStreamsArgs({ video: video.file, audio: audio.file, output, mp4 }));
+ const p = await io.probe(output);
+ if (!p?.audioCodec) return { error: `the merge of its streams (${path.basename(output)}) cannot be read` };
+ return { file: output, seconds: p.seconds, merged: true };
+ }
+ if (audio) {
+ io.say(`${g.stem}: only its audio stream holds anything (${path.basename(audio.file)}); landed as it is.`);
+ return { file: audio.file, seconds: audio.probe.seconds };
+ }
+ return { error: `video with no audio (${streams.map((s) => path.basename(s.file)).join(", ")}): nothing to transcribe` };
+}
+
export async function recordLiveRun(
opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal },
): Promise<RecordLiveSummary> {
@@ -588,13 +677,16 @@ export async function recordLiveRun(
plan = { ...plan, url: vod.url, id: vod.id };
}
const id = plan.id!;
+ const separate = req.separate ?? separateStreamsDefault(plan.platform);
const cfg = configForVideoUrl(opts.channelConfig, plan.url);
const channelDir = path.join(paths.channelsDir, req.slug);
const videoDir = path.join(channelDir, "data", id);
const summary: RecordLiveSummary = { slug: req.slug, id, dryRun: req.dryRun === true, parts: [], landed: null, status: "recording" };
say(
`Record ${plan.url} into ${req.slug}/${id} — ${fromStart ? "from its start" : "from now"}, ` +
- `${maxHeight === null ? "the tallest" : `≤ ${maxHeight}p`}${req.dryRun ? " (dry run: nothing is fetched or written)" : ""}`,
+ `${maxHeight === null ? "the tallest" : `≤ ${maxHeight}p`}` +
+ `${separate ? ", separate video + audio streams merged" : ", one muxed stream"}` +
+ `${req.dryRun ? " (dry run: nothing is fetched or written)" : ""}`,
);
if (req.dryRun) {
say(
@@ -674,10 +766,11 @@ export async function recordLiveRun(
}
await mkdir(slugStore, { recursive: true });
const stamp = now().toISOString().replace(/[:.]/g, "-");
- const partPath = (tag: string) => path.join(slugStore, `.${id}.live-${stamp}.${tag}.ts`);
- const leftovers = (await readdir(slugStore).catch(() => [] as string[]))
- .filter((n) => n.startsWith(`.${id}.live-`) && n.endsWith(".ts"))
- .map((n) => path.join(slugStore, n));
+ // A part's stem (lib/liveCapture.ts livePartFiles); a muxed part is
+ // `<stem>.ts`, a separate-streams one the files yt-dlp names for it.
+ const stemPath = (tag: string) => path.join(slugStore, `.${id}.live-${stamp}.${tag}`);
+ const partPath = (tag: string) => `${stemPath(tag)}.ts`;
+ const leftovers = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[]));
if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed.`);
const record: LiveRecordingRecord = {
@@ -685,14 +778,17 @@ export async function recordLiveRun(
url: plan.url,
platform: plan.platform,
fromStart,
+ separate,
startedAt: now().toISOString(),
parts: [],
};
const save = () => liveRecordingSidecar.write(videoDir, record);
// How far back the playlist reaches (best effort, one read).
+ // (Not for separate streams from the start: YouTube's DASH from the start is
+ // not the HLS playlist the record lists, which holds only the live edge.)
const fmt = meta ? hlsFormatOf(meta, maxHeight) : null;
- if (fmt && plan.platform !== "kick") {
+ if (fmt && plan.platform !== "kick" && !(separate && fromStart)) {
try {
const pl = parsePlaylist(await getText(fmt.url, signal), fmt.url);
if (pl?.kind === "media") {
@@ -713,11 +809,12 @@ export async function recordLiveRun(
}
await save();
- const parts: { part: LivePart; file: string }[] = [];
+ // Each part by its stem's name (the files on disk are read back by it).
+ const parts: { part: LivePart; stem: string }[] = [];
const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => {
const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString() };
record.parts.push(part);
- parts.push({ part, file });
+ parts.push({ part, stem: path.basename(file).replace(/\.ts$/, "") });
return part;
};
const finish = (part: LivePart, note: string) => {
@@ -736,7 +833,7 @@ export async function recordLiveRun(
mode: "from-start" | "index0" | "now",
extraNote = "",
): Promise<RecorderOutcome> => {
- const file = partPath(tag);
+ const file = separate ? stemPath(tag) : partPath(tag);
const part = begin("ytdlp", url, file, mode !== "now");
await save();
const args = ytdlpLiveArgs({
@@ -744,6 +841,7 @@ export async function recordLiveRun(
output: file,
fromStart: mode === "from-start",
maxHeight,
+ separate,
waitForVideo: liveStatus === "is_upcoming" && tag !== "channel",
channelArgs: [
...channelExtraArgs(cfg, cookies),
@@ -757,6 +855,14 @@ export async function recordLiveRun(
return o;
};
const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0);
+ const filesOf = async (stem: string): Promise<LivePartFiles | null> =>
+ livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).find((g) => g.stem === stem) ?? null;
+ const bytesOf = async (stem: string) => {
+ const g = await filesOf(stem);
+ let n = 0;
+ for (const f of g ? [...g.finished, ...g.streams] : []) n += await sizeOf(path.join(slugStore, f));
+ return n;
+ };
if (plan.platform === "kick") {
const vodFmt = fmt;
@@ -799,12 +905,17 @@ export async function recordLiveRun(
say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment.");
o = await ytdlpPart(plan.url, "ytdlp-index0", "index0", "--no-live-from-start + -live_start_index 0; ");
}
+ if (!signal.aborted && o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) {
+ say(
+ 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.',
+ );
+ }
const last = parts[parts.length - 1];
if (
!signal.aborted &&
o.exitCode !== 0 &&
last &&
- (await sizeOf(last.file)) === 0 &&
+ (await bytesOf(last.stem)) === 0 &&
BROWSER_FALLBACK_PLATFORMS.has(plan.platform) &&
extractionRefused(o.stderrTail)
) {
@@ -844,31 +955,47 @@ export async function recordLiveRun(
say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`);
}
const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s));
- const candidates: { file: string; seconds: number | null; part?: LivePart }[] = [];
- for (const p of parts) {
- if ((await sizeOf(p.file)) === 0) {
- await rm(p.file, { force: true });
- continue;
+ const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s));
+ const at = (n: string) => path.join(slugStore, n);
+ // Every part on disk now — this run's and an earlier run's — by its stem.
+ const groups = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[]));
+ const partOf = new Map(parts.map((p) => [p.stem, p.part]));
+ const candidates: { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles }[] = [];
+ const unlandable: string[] = [];
+ const empty: LivePartFiles[] = [];
+ for (const g of groups) {
+ const part = partOf.get(g.stem);
+ let got: ResolvedPart | null = null;
+ try {
+ got = await resolvePart(g, slugStore, { probe: (f) => probe(f, landSignal), merge: (a) => merge(a, landSignal), say });
+ } catch (err) {
+ unlandable.push(`${g.stem}: ${(err as Error).message}`);
+ }
+ if (part) {
+ part.bytes = 0;
+ for (const f of [...g.finished, ...g.streams]) part.bytes += await sizeOf(at(f));
+ part.seconds = got && !("error" in got) ? got.seconds : null;
+ if (got && !("error" in got) && got.merged) part.merged = true;
+ }
+ if (got && "error" in got) unlandable.push(`${g.stem}: ${got.error}`);
+ else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) });
+ else {
+ empty.push(g);
+ for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true });
}
- const s = (await probe(p.file, landSignal))?.seconds ?? null;
- p.part.seconds = s;
- p.part.bytes = await sizeOf(p.file);
- candidates.push({ file: p.file, seconds: s, part: p.part });
- }
- for (const f of leftovers) {
- if ((await sizeOf(f)) === 0) continue;
- candidates.push({ file: f, seconds: (await probe(f, landSignal))?.seconds ?? null });
}
+ for (const u of unlandable) say(`Not landable: ${u}`);
summary.parts = record.parts.map((p) => ({ method: p.method, seconds: p.seconds ?? null, fromStart: p.fromStart }));
if (candidates.length === 0) {
+ const error = unlandable.length ? `nothing landable was recorded (${unlandable.join("; ")})` : "nothing was recorded";
record.status = cancelled ? "cancelled" : "failed";
record.endedAt = now().toISOString();
- record.error = "nothing was recorded";
+ record.error = error;
await save();
- await abandon();
+ if (!unlandable.length) await abandon();
summary.status = record.status;
say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
- if (!cancelled) throw new Error("nothing was recorded");
+ if (!cancelled) throw new Error(error);
return summary;
}
candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1));
@@ -890,8 +1017,13 @@ export async function recordLiveRun(
signal: landSignal,
...(deps.land ? { deps: deps.land } : {}),
});
- // The other parts were staging scratch; a shorter (or unlanded) one goes.
- for (const c of candidates) if (c !== best || landed.kept === "existing") await rm(c.file, { force: true });
+ // Every part's files were staging scratch (the landed one is moved or
+ // copied into the store); a shorter (or unlanded) part goes, and so do the
+ // streams a merge was made from.
+ for (const c of candidates) await rm(c.file, { force: true });
+ for (const g of [...candidates.map((c) => c.group), ...empty]) {
+ for (const f of [...g.finished, ...g.streams, ...g.scratch]) await rm(at(f), { force: true });
+ }
record.landedPart = best.part ? record.parts.indexOf(best.part) : undefined;
record.kept = landed.kept;
record.status = cancelled ? "cancelled" : "landed";
diff --git a/common/lib/liveCapture.test.ts b/common/lib/liveCapture.test.ts
@@ -5,8 +5,12 @@ import {
extractionRefused,
ffmpegLiveArgs,
liveFormatSelector,
+ formatUnavailable,
liveFromStartUnsupported,
+ livePartFiles,
+ mergeStreamsArgs,
newSegments,
+ separateStreamsDefault,
parsePlaylist,
pickVariant,
playlistReach,
@@ -149,6 +153,82 @@ test("the yt-dlp argv: the channel's args first, the recording's after, MPEG-TS
assert.equal(liveFormatSelector(null), "best");
});
+test("a muxed recording's argv (Rumble, Kick) is exactly what it was: one `best`, MPEG-TS to the file", () => {
+ const args = ytdlpLiveArgs({
+ url: "https://rumble.com/v1-x.html",
+ output: "/store/s/.v1.live.ytdlp.ts",
+ fromStart: true,
+ maxHeight: 720,
+ channelArgs: ["--impersonate", "chrome"],
+ });
+ assert.deepEqual(args, [
+ "--ignore-config", "--no-playlist", "--impersonate", "chrome", "--live-from-start",
+ "-f", "best[height<=720]/best", "--hls-use-mpegts", "--no-part", "--fixup", "never",
+ "--no-write-info-json", "--no-write-subs", "--no-write-auto-subs", "--no-write-thumbnail",
+ "--no-write-description", "--no-download-archive", "--no-mtime", "--newline",
+ "-o", "/store/s/.v1.live.ytdlp.ts", "--", "https://rumble.com/v1-x.html",
+ ]);
+ assert.deepEqual(ytdlpLiveArgs({ url: "u", output: "o.ts", fromStart: true, maxHeight: 720, channelArgs: [], separate: false }), ytdlpLiveArgs({ url: "u", output: "o.ts", fromStart: true, maxHeight: 720, channelArgs: [] }));
+});
+
+test("separate streams (YouTube): the video at the height plus the best audio, merged; the output a stem", () => {
+ assert.equal(liveFormatSelector(720, true), "bv*[height<=720]+ba/b[height<=720]/bv*+ba/b");
+ assert.equal(liveFormatSelector(null, true), "bv*+ba/b");
+ assert.equal(liveFormatSelector(720, false), "best[height<=720]/best");
+ assert.equal(separateStreamsDefault("youtube"), true);
+ for (const p of ["rumble", "kick", "twitch", "unknown", null]) assert.equal(separateStreamsDefault(p), false, String(p));
+ const args = ytdlpLiveArgs({
+ url: "https://www.youtube.com/watch?v=5-XlMxKT494",
+ output: "/store/s/.5-XlMxKT494.live-T.ytdlp",
+ fromStart: true,
+ maxHeight: 720,
+ channelArgs: [],
+ separate: true,
+ });
+ assert.equal(args[args.indexOf("-f") + 1], "bv*[height<=720]+ba/b[height<=720]/bv*+ba/b");
+ assert.equal(args[args.indexOf("--merge-output-format") + 1], "mp4/mkv");
+ assert.equal(args[args.indexOf("-o") + 1], "/store/s/.5-XlMxKT494.live-T.ytdlp.%(ext)s");
+ for (const flag of ["--live-from-start", "--no-part"]) assert.ok(args.includes(flag), flag);
+ assert.ok(formatUnavailable("ERROR: [youtube] 5-XlMxKT494: Requested format is not available. Use --list-formats"));
+});
+
+test("a part's files by stem: finished, unmerged streams, yt-dlp's scratch", () => {
+ const id = "5-XlMxKT494";
+ const s1 = `.${id}.live-2026-10-26T12-00-00-000Z.ytdlp`;
+ const s2 = `.${id}.live-2026-10-25T09-00-00-000Z.ytdlp-index0`;
+ const groups = livePartFiles(id, [
+ `${s1}.f270.mp4`,
+ `${s1}.f234.m4a`,
+ `${s1}.f270.mp4-Frag12`,
+ `${s1}.f234.m4a.ytdl`,
+ `${s1}.temp.mp4`,
+ `${s2}.ts`,
+ `${s2}.merged.mp4`,
+ `.${id}.land-1.part`,
+ `.other.live-2026-10-26T12-00-00-000Z.ytdlp.ts`,
+ "5-XlMxKT494",
+ ]);
+ assert.deepEqual(groups, [
+ { stem: s2, finished: [`${s2}.merged.mp4`, `${s2}.ts`], streams: [], scratch: [] },
+ {
+ stem: s1,
+ finished: [],
+ streams: [`${s1}.f234.m4a`, `${s1}.f270.mp4`],
+ scratch: [`${s1}.f234.m4a.ytdl`, `${s1}.f270.mp4-Frag12`, `${s1}.temp.mp4`],
+ },
+ ]);
+ // yt-dlp's DASH downloader names both streams with the merge's extension.
+ assert.deepEqual(livePartFiles(id, [`${s1}.f270.mp4`, `${s1}.f234.mp4`, `${s1}.mp4`])[0], {
+ stem: s1,
+ finished: [`${s1}.mp4`],
+ streams: [`${s1}.f234.mp4`, `${s1}.f270.mp4`],
+ scratch: [],
+ });
+ const m = mergeStreamsArgs({ video: "v.mp4", audio: "a.m4a", output: "o.mp4", mp4: true });
+ assert.deepEqual(m.slice(m.indexOf("-i")), ["-i", "v.mp4", "-i", "a.m4a", "-map", "0:v:0", "-map", "1:a:0", "-c", "copy", "-movflags", "+faststart", "-f", "mp4", "o.mp4"]);
+ assert.deepEqual(mergeStreamsArgs({ video: "v", audio: "a", output: "o.mkv", mp4: false }).slice(-3), ["-f", "matroska", "o.mkv"]);
+});
+
test("the ffmpeg argv: from the first listed segment, stream copy, retries", () => {
const args = ffmpegLiveArgs({ url: "https://cdn/x.m3u8", output: "/o.ts", fromStart: true, userAgent: "UA", referer: "https://rumble.com/" });
assert.equal(args[args.indexOf("-live_start_index") + 1], "0");
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -202,24 +202,57 @@ export function extractionRefused(stderr: string): boolean {
);
}
-// The quality selector for a live recording. Live HLS formats are muxed
-// (video + audio in one), so one `best` filter picks one.
-export function liveFormatSelector(maxHeight: number | null): string {
+// SEPARATE STREAMS OR ONE. A Rumble or Kick live playlist is muxed (video and
+// audio in one HLS variant), so one `best` filter picks one. A YouTube live
+// stream with `--live-from-start` offers ONLY separate DASH video and audio
+// (measured 2026-10-26 on 5-XlMxKT494: eight formats, the metadata pass picked
+// `270+234`), and `-f best` failed at once with "Requested format is not
+// available". A separate-streams recording takes the video at the height asked
+// for plus the best audio, and yt-dlp merges them when it ends.
+export const MUXED_LIVE_PLATFORMS: ReadonlySet<string> = new Set(["rumble", "kick"]);
+
+// The platforms recorded as separate video + audio unless the request says
+// otherwise (`separate`).
+export const SEPARATE_LIVE_PLATFORMS: ReadonlySet<string> = new Set(["youtube"]);
+
+export function separateStreamsDefault(platform: string | null | undefined): boolean {
+ return platform != null && SEPARATE_LIVE_PLATFORMS.has(platform);
+}
+
+// The quality selector for a live recording. Muxed: one `best` (at or under
+// the height). Separate: the video at or under the height plus the best
+// audio, then a muxed one at that height, then any video plus audio.
+export function liveFormatSelector(maxHeight: number | null, separate = false): string {
+ if (separate) return maxHeight === null ? "bv*+ba/b" : `bv*[height<=${maxHeight}]+ba/b[height<=${maxHeight}]/bv*+ba/b`;
return maxHeight === null ? "best" : `best[height<=${maxHeight}]/best`;
}
+// The containers yt-dlp may merge separate streams into: mp4 when the codecs
+// fit it (h264/av1 + aac), else mkv. The landing copies either as it is.
+export const LIVE_MERGE_OUTPUT_FORMAT = "mp4/mkv";
+
// THE yt-dlp RECORDING (path A). `channelArgs` are the channel's own
// (channelExtraArgs: cookies, the platform's args — Rumble's `--impersonate` —
-// and `ytdlpExtraArgs`). The output is MPEG-TS written straight to `output`
-// (`--hls-use-mpegts --no-part --fixup never`): a recording cut short by a
-// cancel or a crash is the same readable file a finished one is, and the
-// landing (controller/landMedia.ts) remuxes it to mp4 either way.
+// and `ytdlpExtraArgs`).
+//
+// Muxed: MPEG-TS written straight to `output` (`--hls-use-mpegts --no-part
+// --fixup never`): a recording cut short by a cancel or a crash is the same
+// readable file a finished one is, and the landing (controller/landMedia.ts)
+// remuxes it to mp4 either way.
+//
+// Separate (`separate`): `output` is a STEM, and yt-dlp writes each stream to
+// `<stem>.f<format id>.<ext>` while it records (`--no-part`: whole fragments
+// appended, readable at any moment), then merges them into `<stem>.<ext>`
+// (LIVE_MERGE_OUTPUT_FORMAT) and removes them. A recording stopped before the
+// merge leaves the streams, and record-live merges them itself
+// (livePartFiles, mergeStreamsArgs).
export function ytdlpLiveArgs(opts: {
url: string;
output: string;
fromStart: boolean;
maxHeight: number | null;
channelArgs: readonly string[];
+ separate?: boolean;
// An upcoming stream: wait for it to start, re-asking every 60 s. Never for
// a stream that is (or was) live — yt-dlp would wait for the NEXT one.
waitForVideo?: boolean;
@@ -232,7 +265,8 @@ export function ytdlpLiveArgs(opts: {
opts.fromStart ? "--live-from-start" : "--no-live-from-start",
...(opts.waitForVideo ? ["--wait-for-video", "60"] : []),
"-f",
- liveFormatSelector(opts.maxHeight),
+ liveFormatSelector(opts.maxHeight, opts.separate === true),
+ ...(opts.separate ? ["--merge-output-format", LIVE_MERGE_OUTPUT_FORMAT] : []),
"--hls-use-mpegts",
"--no-part",
"--fixup",
@@ -246,12 +280,75 @@ export function ytdlpLiveArgs(opts: {
"--no-mtime",
"--newline",
"-o",
- opts.output,
+ opts.separate ? `${opts.output}.%(ext)s` : opts.output,
"--",
opts.url,
];
}
+// --- a part's files on disk -----------------------------------------------------
+
+// A recording part is a STEM in the store's slug dir,
+// `.<id>.live-<stamp>.<tag>`, and the files named for it:
+// finished `<stem>.ts` (muxed), `<stem>.<ext>` (yt-dlp's merge), or
+// `<stem>.merged.<ext>` (record-live's own merge)
+// streams `<stem>.f<format id>.<ext>`: one separate stream, unmerged
+// scratch yt-dlp's fragments and state (`-Frag<n>`, `.ytdl`, `.part`)
+// and its merge in progress (`<stem>.temp.<ext>`)
+export type LivePartFiles = { stem: string; finished: string[]; streams: string[]; scratch: string[] };
+
+const LIVE_STEM_RE = /^([^.]+)\.([\w-]+)\.(.+)$/;
+
+// The parts of record `id` the names (a directory listing) hold, by stem, in
+// name order. Names that are not a part of `id` are left out.
+export function livePartFiles(id: string, names: readonly string[]): LivePartFiles[] {
+ const prefix = `.${id}.live-`;
+ const by = new Map<string, LivePartFiles>();
+ for (const name of [...names].sort()) {
+ if (!name.startsWith(prefix)) continue;
+ const m = LIVE_STEM_RE.exec(name.slice(prefix.length));
+ if (!m) continue;
+ const stem = `${prefix}${m[1]}.${m[2]}`;
+ const rest = m[3]!;
+ let g = by.get(stem);
+ if (!g) by.set(stem, (g = { stem, finished: [], streams: [], scratch: [] }));
+ if (/-Frag\d+|\.ytdl$|\.part$|^temp\./i.test(rest)) g.scratch.push(name);
+ else if (/^f[^.]+\.[a-z0-9]+$/i.test(rest)) g.streams.push(name);
+ else if (/^(?:merged\.)?[a-z0-9]+$/i.test(rest)) g.finished.push(name);
+ else g.scratch.push(name);
+ }
+ return [...by.values()];
+}
+
+// ffmpeg's merge of a video stream and an audio stream, stream-copied:
+// mp4 (+faststart) when `mp4` (the codecs fit it), else mkv.
+export function mergeStreamsArgs(opts: { video: string; audio: string; output: string; mp4: boolean }): string[] {
+ return [
+ "-nostdin",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ opts.video,
+ "-i",
+ opts.audio,
+ "-map",
+ "0:v:0",
+ "-map",
+ "1:a:0",
+ "-c",
+ "copy",
+ ...(opts.mp4 ? ["-movflags", "+faststart", "-f", "mp4"] : ["-f", "matroska"]),
+ opts.output,
+ ];
+}
+
+// yt-dlp found no format the selector names.
+export function formatUnavailable(stderr: string): boolean {
+ return /Requested format is not available/i.test(stderr);
+}
+
// The HLS demuxer refuses a segment whose URL does not end in a listed media
// extension. Rumble's CDN (seen 2026-10-23) serves a stream's segments as byte
// ranges of one `.tar` (`…/81j9A.gaa.tar?r_file=media-0.ts&r_range=…`), so the
@@ -332,6 +429,9 @@ export type LivePart = {
bytes?: number;
// Why it ended, or failed.
note?: string;
+ // Its separate streams were left unmerged (a cancel, a crash) and merged
+ // by record-live.
+ merged?: boolean;
};
export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled";
@@ -341,6 +441,9 @@ export type LiveRecordingRecord = {
url: string;
platform: string;
fromStart: boolean;
+ // Recorded as separate video + audio streams (the request's `separate`, else
+ // the platform's default).
+ separate?: boolean;
startedAt: string;
endedAt?: string;
parts: LivePart[];
diff --git a/common/lib/mediaImport.ts b/common/lib/mediaImport.ts
@@ -156,6 +156,11 @@ export function readProbe(json: unknown): MediaProbe | null {
const MP4_VIDEO = new Set(["h264", "hevc", "av1", "mpeg4", "vp9"]);
const MP4_AUDIO = new Set(["aac", "mp3", "ac3", "eac3", "opus", "alac", "flac"]);
+// An mp4 can hold these codecs (null: no such stream).
+export function mp4CanHold(videoCodec: string | null, audioCodec: string | null): boolean {
+ return (videoCodec === null || MP4_VIDEO.has(videoCodec)) && (audioCodec === null || MP4_AUDIO.has(audioCodec));
+}
+
// A file's extension, without a trailing `.part` (a yt-dlp partial names the
// container it was to become).
export function sourceExt(name: string): string {
@@ -187,9 +192,7 @@ export function finalizeFor(name: string, probe: MediaProbe): LandingFinalize |
if (!partial && isMkv && ["mkv", "webm"].includes(ext)) {
return { action: "copy", ext, reason: `${fmt} as it is` };
}
- const mp4Ok =
- (probe.videoCodec === null || MP4_VIDEO.has(probe.videoCodec)) &&
- (probe.audioCodec === null || MP4_AUDIO.has(probe.audioCodec));
+ const mp4Ok = mp4CanHold(probe.videoCodec, probe.audioCodec);
if (mp4Ok) {
return {
action: "remux",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **Record live works on YouTube.** On 2026-10-26 `pnpm ops record-live` on a live YouTube stream failed at once with "Requested format is not available" and recorded nothing, though the stream's first 33 minutes were there to record. The recorder asked for one stream holding both video and audio, which Rumble and Kick have and YouTube's from-the-start recording does not: it offers the video and the audio separately. On YouTube a recording now takes the video at the chosen height (720p by default, the tallest with `"maxHeight": null`) plus the best audio, and joins them when the stream ends. `"separate": true` or `false` chooses for any stream, and the Record live form has a **Streams** choice. Stopping a recording (`job cancel`), or a crash, before the two were joined no longer loses it: the video and audio left behind are joined without re-encoding and land as one mp4 with sound, and a pair an earlier run left is landed by the next one. Rumble and Kick record exactly as before. A stream recorded as one stream that turns out to have none says to try `"separate": true`. Needs a restart of the editor.
- **A report video's fact-check counter never cuts its label short.** The deck's count box showed the verdict's label and cut what did not fit with "…", so the Huck cut's count read "HUCK'S BLEND …". A verdict can now carry a `tallyLabel` (`render.chrome.factcheck.verdicts.<V>.tallyLabel`), a short word for the count box alone, and the Huck cut's says "Pitches"; the finale's totals and stats keep the full "Huck's Blend pitches". Without one, the box shows the label if it fits, else the longest run of the label's last words that fits. A `tallyLabel` that does not fit, or a label with no last words that fit, is refused by name when the manifest is checked, not found in the render. Labels that already fit draw exactly as before.
- **A post screenshot alone in the posts feed fills the card's width.** The feed only let a tall screenshot grow into the room beside the card under it, and it kept that room even when the card under it was about to be pushed out of the column, so the Huck video's 21 October "new kind of seizure" post stood alone at 345 px wide in a 556 px card with the column empty under it. A screenshot whose card arrives alone, or pushes the one under it out, now takes the card's full width, its height following the picture, up to the column's height (larger than the screenshot itself if the width needs it). With a card under it that stays on screen, the feed draws exactly as before, and a feed with no screenshots builds the same page, so its cached render is reused.
- **A report video's trailer can be cut from the finished video, so it shows the whole timeline.** The Huck trailer was a short take of its own: 14 clips with their own rail, so the on-screen timeline, dates and tallies said the video was two minutes long. `umtool trailer <project> --take <take> --beats beats.json --intro --finale 8` now cuts the trailer from the take's finished master instead. Each beat is a clip's source seconds (or master seconds), and the take's own build records find where those seconds play in the master. The rail on screen is the full video's, so a viewer can see there is more. Nothing is rendered again: it is one ffmpeg pass, crossfaded and encoded with the take's own settings. It writes `<slug>.trailer.mp4` beside the master and a `.trailer.json` record of what was cut. A beat that reaches into one of the master's own crossfades is moved in, and the command says so. A beat that runs into the next piece (the intro into the first clip, the last beat into the finale) plays straight on, so no moment is shown twice. Unknown clips, beats outside what was cut, and takes with no build are refused by name.
diff --git a/editor/app/api/ops/record-live/route.ts b/editor/app/api/ops/record-live/route.ts
@@ -5,11 +5,13 @@ import { jobResponse, ops, reqSlug } from "../_lib";
export const dynamic = "force-dynamic";
// POST { slug, url? | id?, fromStart? (true), maxHeight? (720; null = tallest),
-// transcribe?, doNotClean?, note?, dryRun? } -> { ok: true, jobId }
+// separate? (YouTube true, else false), transcribe?, doNotClean?, note?,
+// dryRun? } -> { ok: true, jobId }
//
// A LIVE STREAM RECORDED UNTIL IT ENDS (controller/recordLive.ts;
// plans/live-capture.md): yt-dlp `--live-from-start` (Rumble's DVR playlist
-// holds the stream from its start for its first 4 hours); on Rumble, when
+// holds the stream from its start for its first 4 hours; YouTube's from the
+// start is separate DASH video + audio, merged); on Rumble, when
// yt-dlp is refused, the page's own playlist found by a browser and recorded
// by ffmpeg; on Kick, the ongoing VOD polled from its first segment beside the
// channel's live stream. Then the longest part lands as the video's source,
diff --git a/editor/app/channels/[slug]/components/LiveMediaTools.tsx b/editor/app/channels/[slug]/components/LiveMediaTools.tsx
@@ -118,6 +118,8 @@ export function RecordLiveForm({ slug, videoId }: { slug: string; videoId?: stri
const [url, setUrl] = useState("");
const [fromStart, setFromStart] = useState(true);
const [best, setBest] = useState(false);
+ // "auto": the platform's default (YouTube separate video + audio; Rumble, Kick one muxed stream).
+ const [streams, setStreams] = useState<"auto" | "separate" | "muxed">("auto");
const [transcribe, setTranscribe] = useState(false);
const [keep, setKeep] = useState(false);
const [note, setNote] = useState("");
@@ -126,6 +128,7 @@ export function RecordLiveForm({ slug, videoId }: { slug: string; videoId?: stri
...(videoId ? { id: videoId } : { url: url.trim() }),
...(fromStart ? {} : { fromStart: false }),
...(best ? { maxHeight: null } : {}),
+ ...(streams === "auto" ? {} : { separate: streams === "separate" }),
...(transcribe ? { transcribe: true } : {}),
...(keep ? { doNotClean: true } : {}),
...(note.trim() ? { note: note.trim() } : {}),
@@ -149,6 +152,19 @@ export function RecordLiveForm({ slug, videoId }: { slug: string; videoId?: stri
Tallest quality (else 720p)
</label>
<label className="flex items-center gap-2">
+ Streams
+ <select
+ value={streams}
+ onChange={(e) => setStreams(e.target.value as "auto" | "separate" | "muxed")}
+ aria-label="record streams"
+ className={input}
+ >
+ <option value="auto">by platform (YouTube: separate)</option>
+ <option value="separate">separate video + audio, merged</option>
+ <option value="muxed">one stream with both</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-2">
<input type="checkbox" checked={transcribe} onChange={(e) => setTranscribe(e.target.checked)} aria-label="queue a transcription when it ends" />
Queue its transcription when it ends
</label>
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -390,7 +390,7 @@ const ACTIONS = [
// LIVE STREAM RECORDED from its start (plans/live-capture.md): import-media
// ({slug, path, url? | id? | meta?, move?, replace?, audio?, transcribe?,
// doNotClean?, note?, dryRun?}) and record-live ({slug, url? | id?,
- // fromStart?, maxHeight?, transcribe?, doNotClean?, note?, dryRun?}), each a
+ // fromStart?, maxHeight?, separate?, transcribe?, doNotClean?, note?, dryRun?}), each a
// job; both land through the same code.
"import-media",
"record-live",
@@ -1515,12 +1515,16 @@ export function usage() {
' 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; the",
- " longest part wins. Refused for a stream that is not live.",
+ " 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.",
"",
'prepare-playable remuxes each of a channel\'s saved containers, losslessly',
' (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes',