commit f5c7264941a9cb5bbb0229b79cef23b78ed7bd9d
parent 8b91abae71cbbc10aeb38ef38e40cd6439656c5c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 23:37:06 -0400
common: a whole file from the stored media URL, read the way the player reads it — sequential Range requests with the page's Referer and Origin, resumable from a probed-clean byte count, the audio check's cadence, rollback, final probe and corrupt-full-source over a producer of its own; the storedUrlDownloads channel key, the stored-url-ranged attempt kind, a fake ranged CDN in the test kit
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
15 files changed, 1194 insertions(+), 10 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -46,6 +46,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `cookieMode` | config | Per-channel override of the global cookie mode. Absent = inherit. |
| `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. |
| `audioCheck` | config | Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {"enabled": false}` turns it off); the channel's opt-in for any other platform. See [`audioCheck`](#audiocheck). |
+| `storedUrlDownloads` | config | Whether a full download (transcribe handling) reads the media URL the record's `metadata.info.json` already stores, the way the platform's own player reads it — ranged requests with the page's Referer and Origin, no yt-dlp — through the same audio check. `"never"` (the default: the page, as always), `"fallback"` (the page first; on a rate limit, or a held platform, the stored URL) or `"only"` (the stored URL and no page request; a video without one fails, asking nothing). Odysee only (its CDN hosts). Two such downloads on one platform are at least 20 minutes apart: the CDN allows one new file per rest. A request's own `storedUrl` overrides it. |
| `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). |
| `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). |
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -9,6 +9,7 @@ import { isCookieMode, type CookieMode } from "./cookiePolicy";
import type { FieldDocs } from "./fieldDocs";
import { coerceRecordedDateRule, type RecordedDateRule } from "./recordedDate";
import { coerceMirrorConfig, type MirrorConfig } from "./mirrors/config";
+import { isStoredUrlMode, type StoredUrlMode } from "./storedMediaUrl";
export type ChannelHandling = "youtube" | "transcribe";
@@ -148,6 +149,9 @@ export type ChannelConfig = {
cookieMode?: CookieMode;
sleepBetweenDownloadsSeconds?: number;
audioCheck?: AudioCheckConfig;
+ // Release 32 R7: whether a full download may read the record's stored media
+ // URL (lib/storedMediaUrl.ts) the way the platform's player does.
+ storedUrlDownloads?: StoredUrlMode;
recordedDate?: RecordedDateRule;
mirror?: MirrorConfig;
};
@@ -208,6 +212,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
"Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600.",
audioCheck:
"Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {\"enabled\": false}` turns it off); the channel's opt-in for any other platform.",
+ storedUrlDownloads:
+ 'Whether a full download (transcribe handling) reads the media URL the record\'s `metadata.info.json` already stores, the way the platform\'s own player reads it — ranged requests with the page\'s Referer and Origin, no yt-dlp — through the same audio check. `"never"` (the default: the page, as always), `"fallback"` (the page first; on a rate limit, or a held platform, the stored URL) or `"only"` (the stored URL and no page request; a video without one fails, asking nothing). Odysee only (its CDN hosts). Two such downloads on one platform are at least 20 minutes apart: the CDN allows one new file per rest. A request\'s own `storedUrl` overrides it.',
recordedDate:
"For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped.",
mirror:
@@ -415,6 +421,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
? Math.min(Math.floor(v), CHANNEL_SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS)
: undefined,
audioCheck: coerceAudioCheck,
+ storedUrlDownloads: (v) => (isStoredUrlMode(v) ? v : undefined),
recordedDate: coerceRecordedDateRule,
mirror: coerceMirrorConfig,
};
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -75,6 +75,7 @@ export const channelConfigObjectSchema = z.object({
cookieMode: field("cookieMode"),
sleepBetweenDownloadsSeconds: field("sleepBetweenDownloadsSeconds"),
audioCheck: field("audioCheck"),
+ storedUrlDownloads: field("storedUrlDownloads"),
recordedDate: field("recordedDate"),
mirror: field("mirror"),
});
diff --git a/common/lib/downloadOutcome.ts b/common/lib/downloadOutcome.ts
@@ -82,7 +82,13 @@ export type DownloadAttemptKind =
// plain download from archive.org. `ytdlpExitCode` is 0 for a fetch that
// delivered a verified file and 1 for one that did not.
| "archiveorg-torrent"
- | "archiveorg-direct";
+ | "archiveorg-direct"
+ // The WHOLE file read from the media URL the record already stores, the way
+ // the platform's player reads it — sequential Range requests with the page's
+ // Referer and Origin, no yt-dlp (release 32 R7, ytdlp/storedUrlDownload.ts).
+ // `ytdlpExitCode` is 0 for a file that came down whole and 1 otherwise;
+ // `storedUrl` says from where and why.
+ | "stored-url-ranged";
export type AudioCheckProbeVerdict = "clean" | "partial" | "malformed";
@@ -103,6 +109,20 @@ export type DownloadAttempt = {
availabilityClass?: Availability;
error?: string;
audioCheck?: AudioCheckAttemptStats;
+ // A "stored-url-ranged" attempt: the CDN host, why the stored URL was read
+ // (the page lookup rate-limited, the platform held, or the request said
+ // `only`), and the bytes on disk when it ended (of `totalBytes`, when the CDN
+ // said). `httpStatus`: the refusal that stopped it, if one did.
+ storedUrl?: StoredUrlAttempt;
+};
+
+export type StoredUrlAttempt = {
+ host: string;
+ why: "rate-limited" | "held" | "only";
+ bytes: number;
+ totalBytes?: number;
+ resumedFrom?: number;
+ httpStatus?: number;
};
// ONE RETRY OF A corrupt-full-source VIDEO (release 30, lane Q), appended to
diff --git a/common/lib/mediaTier.test.ts b/common/lib/mediaTier.test.ts
@@ -52,6 +52,9 @@ const TABLE: ReadonlyArray<[string, "media" | "text" | "scratch", boolean]> = [
["audio.mp4.corrupt-kept", "scratch", false],
["audio.salvage.wav", "scratch", false],
[".audio.salvage.wav.parakeet", "scratch", false],
+ // Release 32 R7: the stored-URL ranged download's partial and its resume state.
+ ["audio.mp4.stored.part", "scratch", false],
+ ["audio.mp4.stored.part.json", "scratch", false],
// The hot text.
["transcript.json", "text", false],
["transcript.en.vtt", "text", false],
diff --git a/common/lib/mediaTier.ts b/common/lib/mediaTier.ts
@@ -59,6 +59,10 @@ const SCRATCH_PATTERNS: ReadonlyArray<RegExp> = [
// yt-dlp's resume-state file beside one (`audio.m4a.ytdl`).
/\.part$/,
/\.ytdl$/,
+ // The stored-URL ranged download's resume state beside its partial
+ // (`audio.mp4.stored.part.json`, ytdlp/storedUrlDownload.ts; the partial
+ // itself, `audio.mp4.stored.part`, is the `.part` rule above).
+ /\.stored\.part\.json$/,
// The media-tier hook's own temps (`lib/mediaTier-server.ts`): the link
// beside the name, and the bytes being placed in `media/<id>/`.
/\.tierlink-\d+$/,
diff --git a/common/lib/storedMediaUrl.ts b/common/lib/storedMediaUrl.ts
@@ -55,6 +55,46 @@ export type StoredMediaUrl = {
// run, or a cooldown), the platform is held, or the request said `only`.
export type StoredUrlWhy = "rate-limited" | "held" | "only";
+// The browser user agent a stored media URL is read with: the player's, not
+// yt-dlp's (release 32). Shared by the clip cut (ytdlp/fetchWindowManaged.ts)
+// and the whole-file ranged download (ytdlp/storedUrlDownload.ts).
+export const STORED_MEDIA_USER_AGENT =
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
+
+// The headers the platform's own player sends with a read of its CDN: the page's
+// Referer and Origin and a browser user agent. No cookies, no token.
+export function storedMediaHeaders(
+ stored: Pick<StoredMediaUrl, "referer">,
+): Record<string, string> {
+ return {
+ "User-Agent": STORED_MEDIA_USER_AGENT,
+ Referer: stored.referer,
+ Origin: new URL(stored.referer).origin,
+ Accept: "*/*",
+ };
+}
+
+// A WHOLE FILE FROM THE STORED URL (release 32 R7, ytdlp/storedUrlDownload.ts):
+// Odysee's CDN serves the player's ranged reads of a file, but allows ONE new
+// original file per platform after a rest (measured 2026-10-16: the next, a
+// minute later, answered 429). So two stored-URL downloads on one platform are
+// at least this far apart — the batch waits rather than 429s. Kept in the
+// platform pacing state (jobs/platformGap.ts) under storedUrlGapKey.
+export const STORED_URL_NEW_FILE_GAP_MS = 20 * 60_000;
+
+export function storedUrlGapKey(platform: string): string {
+ return `stored-url:${platform}`;
+}
+
+// The mode a download runs with: the request's, else the channel's
+// `storedUrlDownloads`, else never.
+export function resolveStoredUrlMode(
+ request: StoredUrlMode | undefined,
+ channel: StoredUrlMode | undefined,
+): StoredUrlMode {
+ return request ?? channel ?? "never";
+}
+
export function storedUrlWhyText(why: StoredUrlWhy, platform: string): string {
if (why === "only") return "(asked: only)";
return `— ${platform} lookup ${why === "held" ? "held" : "rate-limited"}`;
diff --git a/common/testing/audio/corruptAudio.d.mts b/common/testing/audio/corruptAudio.d.mts
@@ -3,7 +3,7 @@ export function hasFfmpeg(): boolean;
export function burstTimes(opts?: { duration?: number; first?: number; every?: number }): number[];
export function makeToneFile(
file: string,
- opts?: { duration?: number; first?: number; every?: number },
+ opts?: { duration?: number; first?: number; every?: number; faststart?: boolean },
): string;
export function corruptBytes(
src: string,
diff --git a/common/testing/audio/corruptAudio.mjs b/common/testing/audio/corruptAudio.mjs
@@ -33,12 +33,15 @@ export function burstTimes({ duration = 30, first = 2, every = 4 } = {}) {
}
// An AAC-in-MP4 tone-burst recording at `file`.
-export function makeToneFile(file, { duration = 30, first = 2, every = 4 } = {}) {
+// `faststart` (release 32 R7) puts the MP4's index at the START, as a web
+// player's file has it — a growing partial of it decodes up to where it ends.
+export function makeToneFile(file, { duration = 30, first = 2, every = 4, faststart = false } = {}) {
const expr = `if(gte(t,${first})*lt(mod(t-${first},${every}),0.3),0.5*sin(2*PI*1000*t),0)`;
execFileSync("ffmpeg", [
"-nostdin", "-v", "error", "-y",
"-f", "lavfi", "-i", `aevalsrc='${expr}':s=${TONE_RATE}:d=${duration}`,
"-c:a", "aac", "-b:a", "64k",
+ ...(faststart ? ["-movflags", "+faststart"] : []),
file,
]);
return file;
diff --git a/common/testing/web/fakeRangedCdn.d.mts b/common/testing/web/fakeRangedCdn.d.mts
@@ -0,0 +1,31 @@
+export const CDN_ORIGIN: string;
+
+export type FakeCdnRequest = {
+ path: string;
+ range: string | null;
+ referer: string | null;
+ origin: string | null;
+ ua: string | null;
+ status: number;
+ bytes: number;
+ at: number;
+};
+
+export type FakeRangedCdn = {
+ base: string;
+ requests: FakeCdnRequest[];
+ url(path: string): string;
+ fetch(url: string | URL, init?: RequestInit): Promise<Response>;
+ refuseAfterBytes(n: number): void;
+ allowAgain(): void;
+ close(): Promise<void>;
+};
+
+export function startFakeRangedCdn(opts?: {
+ files?: Record<string, Buffer>;
+ refuseAfterBytes?: number;
+ refuseStatus?: number;
+ corruptOnce?: { path: string; buf: Buffer; from: number; to: number };
+ ignoreRange?: boolean;
+ allowUnranged?: boolean;
+}): Promise<FakeRangedCdn>;
diff --git a/common/testing/web/fakeRangedCdn.mjs b/common/testing/web/fakeRangedCdn.mjs
@@ -0,0 +1,106 @@
+// A fake media CDN on loopback (release 32 R7): what Odysee's
+// `player.odycdn.com` answered on 2026-10-16, for the stored-URL ranged
+// download. No test reaches the real CDN.
+//
+// const cdn = await startFakeRangedCdn({ files: { "/v6/streams/<claim>/<sd>.mp4": buf } });
+// cdn.fetch a fetch that sends https://player.odycdn.com/… here
+// cdn.url(p) the real-shaped URL of a file (https://player.odycdn.com<p>)
+// cdn.requests every request, in order: { path, range, referer, origin, ua, status, bytes, at }
+// cdn.refuseAfterBytes(n) from now on, once n more bytes are served, answer 429
+// await cdn.close()
+//
+// Behaviour, as measured:
+// - a RANGED GET with the player's Referer and Origin answers 206 with
+// `Content-Range: bytes a-b/total`;
+// - an UNRANGED GET answers 429 (the CDN treats it as a bulk download — what
+// yt-dlp's generic extractor got), unless opts.allowUnranged (then 200);
+// - no Referer → 403;
+// - a range past the end → 416 `Content-Range: bytes */total`;
+// - opts.refuseAfterBytes: once that many bytes have been served in all, every
+// request answers opts.refuseStatus (default 429) — "one file per rest";
+// - opts.corruptOnce: { path, buf, from, to } — the first time a read overlaps
+// bytes [from, to) of that file it is served from `buf` (a damaged copy of
+// the same length) instead: a source that serves malformed audio
+// intermittently. Every later read of those bytes is clean.
+// - opts.ignoreRange: answer every GET 200 with the whole file.
+
+import http from "node:http";
+
+export const CDN_ORIGIN = "https://player.odycdn.com";
+
+export async function startFakeRangedCdn(opts = {}) {
+ const files = opts.files ?? {};
+ const requests = [];
+ let refuseBudget = typeof opts.refuseAfterBytes === "number" ? opts.refuseAfterBytes : null;
+ const refuseStatus = opts.refuseStatus ?? 429;
+ const corrupt = opts.corruptOnce ? { ...opts.corruptOnce, used: false } : null;
+
+ const server = http.createServer((req, res) => {
+ const u = new URL(req.url ?? "/", "http://x");
+ const range = req.headers.range;
+ const rec = {
+ path: u.pathname,
+ range: range ?? null,
+ referer: req.headers.referer ?? null,
+ origin: req.headers.origin ?? null,
+ ua: req.headers["user-agent"] ?? null,
+ status: 0,
+ bytes: 0,
+ at: Date.now(),
+ };
+ requests.push(rec);
+ const end = (status, headers = {}, body) => {
+ rec.status = status;
+ res.writeHead(status, headers);
+ res.end(body);
+ };
+ const file = files[u.pathname];
+ if (!file) return end(404, { "content-type": "text/plain" }, "not found");
+ if (!req.headers.referer) return end(403, { "content-type": "text/plain" }, "forbidden");
+ if (refuseBudget !== null && refuseBudget <= 0) {
+ return end(refuseStatus, { "content-type": "text/plain" }, refuseStatus === 429 ? "Too Many Requests" : "Forbidden");
+ }
+ const total = file.length;
+ const serve = (status, from, to, headers) => {
+ // [from, to] inclusive, capped by the remaining budget.
+ let last = to;
+ if (refuseBudget !== null) last = Math.min(last, from + refuseBudget - 1);
+ let body = file.subarray(from, last + 1);
+ if (corrupt && !corrupt.used && corrupt.path === u.pathname && from < corrupt.to && last >= corrupt.from) {
+ corrupt.used = true;
+ body = Buffer.from(corrupt.buf.subarray(from, last + 1));
+ }
+ if (refuseBudget !== null) refuseBudget -= body.length;
+ rec.bytes = body.length;
+ const h = { "content-type": "video/mp4", "accept-ranges": "bytes", "content-length": String(body.length), ...headers };
+ if (status === 206) h["content-range"] = `bytes ${from}-${from + body.length - 1}/${total}`;
+ end(status, h, body);
+ };
+ if (opts.ignoreRange) return serve(200, 0, total - 1, {});
+ if (!range) {
+ if (opts.allowUnranged) return serve(200, 0, total - 1, {});
+ return end(429, { "content-type": "text/plain" }, "Too Many Requests");
+ }
+ const m = /^bytes=(\d+)-(\d*)$/.exec(range);
+ if (!m) return end(416, { "content-range": `bytes */${total}` }, "");
+ const from = Number(m[1]);
+ const to = m[2] === "" ? total - 1 : Math.min(Number(m[2]), total - 1);
+ if (from >= total) return end(416, { "content-range": `bytes */${total}` }, "");
+ return serve(206, from, to, {});
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return {
+ base,
+ requests,
+ url: (p) => `${CDN_ORIGIN}${p}`,
+ fetch: (url, init) => fetch(String(url).replace(/^https?:\/\/player\.odycdn\.com/, base), init),
+ refuseAfterBytes: (n) => {
+ refuseBudget = n;
+ },
+ allowAgain: () => {
+ refuseBudget = null;
+ },
+ close: () => new Promise((r) => server.close(() => r())),
+ };
+}
diff --git a/common/ytdlp/audioCheckedDownload.ts b/common/ytdlp/audioCheckedDownload.ts
@@ -95,7 +95,11 @@ export type CheckpointAction =
| "restart"
| "skip-size-gate"
| "skip-copy-timeout"
- | "skip-missing-part";
+ | "skip-missing-part"
+ // The stored-URL ranged download (storedUrlDownload.ts): the partial's
+ // container could not be opened yet (an MP4 whose index is longer than what
+ // has come down) and nothing has probed clean — too early to judge.
+ | "skip-not-yet-readable";
export type CheckpointRecord = {
at: string;
@@ -163,8 +167,10 @@ export type AudioCheckedOpts = {
debugPauseMs?: number;
};
-// Resolved knobs.
-type Knobs = {
+// Resolved knobs. Exported for the stored-URL ranged download
+// (ytdlp/storedUrlDownload.ts), which runs the same cadence over a producer of
+// its own.
+export type Knobs = {
// The configured probe interval — the AIMD ceiling and starting point. The
// live cadence (currentIntervalMs in runAudioCheckedYtdlp) shrinks below this
// on malformed checkpoints and relaxes back up toward it, never past it.
@@ -186,7 +192,9 @@ type Knobs = {
resumeDuringProbe: boolean;
};
-function resolveKnobs(opts: AudioCheckedOpts): Knobs {
+export function resolveKnobs(
+ opts: Pick<AudioCheckedOpts, "channelConfig" | "debugPauseMs">,
+): Knobs {
const cfg = opts.channelConfig.audioCheck;
const intervalMsOverride = envIntOverride("E2E_AUDIO_CHECK_INTERVAL_MS");
const sizeGateOverride = envIntOverride("E2E_AUDIO_CHECK_SIZE_GATE");
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -50,7 +50,12 @@ import { channelExtraArgs, configForVideoUrl } from "./channelArgs";
import { runOneYtdlp } from "./runOneYtdlp";
import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged";
import { clipFormatSelector, copyClipFormatSelector } from "./downloadFormat";
-import { storedUrlWhyText, type StoredMediaUrl, type StoredUrlWhy } from "../lib/storedMediaUrl";
+import {
+ STORED_MEDIA_USER_AGENT,
+ storedUrlWhyText,
+ type StoredMediaUrl,
+ type StoredUrlWhy,
+} from "../lib/storedMediaUrl";
// The source height a clip is worth fetching at. 720 is umtool's number and the
// reason is the render: the deliverable is 1080p with a clip inset, so pixels
@@ -191,8 +196,8 @@ class MalformedWindowError extends Error {}
// ffmpeg's argv for a window cut from a stored media URL (see fetchWindowOnce): the player's
// headers, an input seek so only the window's bytes are fetched, a frame-accurate re-encode
// (as --force-keyframes-at-cuts) capped at the clip height, faststart mp4.
-export const STORED_MEDIA_USER_AGENT =
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
+// The constant lives in lib/storedMediaUrl.ts (the whole-file download reads with it too).
+export { STORED_MEDIA_USER_AGENT };
export function storedMediaFfmpegArgs(
stored: Pick<StoredMediaUrl, "url" | "referer">,
diff --git a/common/ytdlp/storedUrlDownload.test.ts b/common/ytdlp/storedUrlDownload.test.ts
@@ -0,0 +1,374 @@
+// The stored-URL ranged download (release 32 R7) against a fake CDN on
+// loopback (testing/web/fakeRangedCdn.mjs) and a synthetic recording
+// (testing/audio/corruptAudio.mjs). Real ffmpeg for the probes and the
+// extraction; skipped without it. No real network.
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile, stat } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { corruptBytes, hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs";
+import { startFakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { Paths } from "../lib/paths";
+import { storedMediaUrlFromInfo, STORED_MEDIA_USER_AGENT } from "../lib/storedMediaUrl";
+import { storedContainerExt, storedPartNames, storedUrlDownload } from "./storedUrlDownload";
+
+const FF = hasFfmpeg();
+const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567";
+const FILE_PATH = `/v6/streams/${CLAIM}/a1b2c3.mp4`;
+const PAGE = `https://odysee.com/@synth:1/synthetic-stream:${CLAIM}`;
+const paths = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths;
+const config = { handling: "transcribe", audioFormat: "mp3" } as ChannelConfig;
+// Every chunk past the first is probed (the cadence and the size gate at 0).
+const EVERY_CHUNK = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 };
+
+async function recording(dir: string): Promise<{ clean: Buffer; bad: Buffer }> {
+ const src = makeToneFile(path.join(dir, "src.mp4"), { duration: 60, faststart: true });
+ const badFile = corruptBytes(src, path.join(dir, "bad.mp4"), { fromFrac: 0.45, toFrac: 0.5 });
+ return { clean: await readFile(src), bad: await readFile(badFile) };
+}
+
+function storedFor(url: string) {
+ const s = storedMediaUrlFromInfo({ webpage_url: PAGE, formats: [{ url, protocol: "https", ext: "mp4" }] });
+ assert.ok(s, "the fake's URL passes the allowlist");
+ return s;
+}
+
+async function setup() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "stored-ranged-"));
+ const videoDir = path.join(root, "data", CLAIM);
+ await import("node:fs/promises").then((m) => m.mkdir(videoDir, { recursive: true }));
+ return { root, videoDir };
+}
+
+test("names: the container's extension is the URL's when it is media, else mp4", () => {
+ assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc.mp4"), "mp4");
+ assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc.m4a"), "m4a");
+ assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc"), "mp4");
+ assert.equal(storedContainerExt("https://player.odycdn.com/v6/streams/x/abc.exe"), "mp4");
+ assert.deepEqual(storedPartNames("https://player.odycdn.com/a/b.mp4"), {
+ container: "audio.mp4",
+ part: "audio.mp4.stored.part",
+ state: "audio.mp4.stored.part.json",
+ });
+});
+
+test("the whole file comes down in ranged reads with the player's headers, then audio.mp3; the container goes", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean } });
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: config,
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 16 * 1024, knobs: EVERY_CHUNK },
+ });
+ assert.equal(r.kind, "ok", log);
+ assert.equal(r.bytes, clean.length);
+ assert.equal(r.totalBytes, clean.length);
+ assert.equal(r.finalProbeVerdict, "clean");
+ assert.ok(r.checkpoints.some((c) => c.action === "advance"));
+ assert.equal(r.rollbacks, 0);
+ // Every read was ranged, sequential, with the player's headers.
+ assert.ok(cdn.requests.length >= 4);
+ let expect = 0;
+ for (const q of cdn.requests) {
+ assert.equal(q.status, 206);
+ assert.match(q.range ?? "", new RegExp(`^bytes=${expect}-`));
+ assert.equal(q.referer, "https://odysee.com/");
+ assert.equal(q.origin, "https://odysee.com");
+ assert.equal(q.ua, STORED_MEDIA_USER_AGENT);
+ expect += q.bytes;
+ }
+ const entries = (await readdir(videoDir)).sort();
+ assert.deepEqual(entries, ["audio.mp3"], "the container and the scratch are gone");
+ assert.match(log, /DLOM_PROGRESS status=finished downloaded=\d+ total=\d+/);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a 429 mid-file keeps the partial; the next run resumes from its last good byte and finishes", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, refuseAfterBytes: 40 * 1024 });
+ const stored = storedFor(cdn.url(FILE_PATH));
+ const run = () =>
+ storedUrlDownload({
+ paths,
+ videoDir,
+ stored,
+ channelConfig: { ...config, keepSourceVideo: true },
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK },
+ });
+ try {
+ const first = await run();
+ assert.equal(first.kind, "rate-limited");
+ assert.equal(first.httpStatus, 429);
+ const names = storedPartNames(stored.url);
+ const state = JSON.parse(await readFile(path.join(videoDir, names.state), "utf8"));
+ assert.equal(state.url, stored.url);
+ assert.equal(state.totalBytes, clean.length);
+ const partSize = (await stat(path.join(videoDir, names.part))).size;
+ assert.ok(state.goodBytes > 0 && state.goodBytes <= partSize, "a probed-clean prefix is recorded");
+ // After the rest.
+ cdn.allowAgain();
+ const before = cdn.requests.length;
+ const second = await run();
+ assert.equal(second.kind, "ok");
+ assert.equal(second.resumedFrom, state.goodBytes);
+ assert.equal(cdn.requests[before].range, `bytes=${state.goodBytes}-${state.goodBytes + 8 * 1024 - 1}`);
+ // keepSourceVideo: the container stays, byte-identical to the source.
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean);
+ assert.deepEqual((await readdir(videoDir)).sort(), ["audio.mp3", "audio.mp4"]);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a 403 stops the same way (the platform backs off)", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, refuseAfterBytes: 16 * 1024, refuseStatus: 403 });
+ try {
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: config,
+ audioFormat: "mp3",
+ audioCheck: false,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024 },
+ });
+ assert.equal(r.kind, "rate-limited");
+ assert.equal(r.httpStatus, 403);
+ // With the check off every written byte counts as good.
+ const state = JSON.parse(await readFile(path.join(videoDir, "audio.mp4.stored.part.json"), "utf8"));
+ assert.equal(state.goodBytes, r.bytes);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a malformed chunk is rolled back and read again; the file ends clean", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean, bad } = await recording(root);
+ const cdn = await startFakeRangedCdn({
+ files: { [FILE_PATH]: clean },
+ corruptOnce: { path: FILE_PATH, buf: bad, from: Math.floor(clean.length * 0.45), to: Math.floor(clean.length * 0.5) },
+ });
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: { ...config, keepSourceVideo: true },
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK },
+ });
+ assert.equal(r.kind, "ok", log);
+ assert.ok(r.rollbacks >= 1, "the malformed checkpoint rolled back");
+ assert.ok(r.checkpoints.some((c) => c.action === "rollback" && c.verdict === "malformed"));
+ assert.match(log, /Checkpoint MALFORMED at \d+ bytes\. Rolling back to \d+ bytes/);
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean, "the re-read bytes are the clean ones");
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a source malformed at every read: more rollbacks than allowed is failed-corrupt-source, the partial kept", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { bad } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: bad } });
+ try {
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: config,
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: { ...EVERY_CHUNK, maxRollbacks: 1 } },
+ });
+ assert.equal(r.kind, "failed-corrupt-source");
+ assert.equal(r.rollbacks, 2);
+ const entries = await readdir(videoDir);
+ assert.ok(entries.includes("audio.mp4.stored.part"));
+ assert.ok(entries.includes("audio.mp4.stored.part.json"));
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("malformed past every checkpoint: the final probe re-reads once, then corrupt-full-source keeps the file", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { bad } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: bad } });
+ try {
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: config,
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ // No periodic probe at all: only the final one sees the damage.
+ deps: { fetch: cdn.fetch, chunkBytes: 32 * 1024, knobs: { intervalMs: 3_600_000 } },
+ });
+ assert.equal(r.kind, "corrupt-full-source");
+ assert.equal(r.finalProbeVerdict, "malformed");
+ assert.match(log, /Re-reading from 0 bytes once before giving up/);
+ assert.deepEqual(await readdir(videoDir), ["audio.mp4"], "the file is kept, no scratch");
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), bad);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a partial with no resume state (or another URL's) is discarded, never extended", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean } });
+ const stored = storedFor(cdn.url(FILE_PATH));
+ try {
+ await writeFile(path.join(videoDir, "audio.mp4.stored.part"), Buffer.alloc(5000, 7));
+ await writeFile(
+ path.join(videoDir, "audio.mp4.stored.part.json"),
+ JSON.stringify({ version: 1, url: "https://player.odycdn.com/other.mp4", totalBytes: 9, goodBytes: 5000 }),
+ );
+ let log = "";
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored,
+ channelConfig: { ...config, keepSourceVideo: true },
+ audioFormat: "mp3",
+ audioCheck: false,
+ onLog: (s) => (log += s),
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 32 * 1024 },
+ });
+ assert.equal(r.kind, "ok");
+ assert.equal(r.resumedFrom, 0);
+ assert.match(log, /Discarded audio\.mp4\.stored\.part/);
+ assert.match(cdn.requests[0].range ?? "", /^bytes=0-/);
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a cancel stops between reads with the partial kept", async () => {
+ const { root, videoDir } = await setup();
+ const buf = Buffer.alloc(64 * 1024, 1);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: buf } });
+ const ac = new AbortController();
+ try {
+ let reads = 0;
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: config,
+ audioFormat: "mp3",
+ audioCheck: false,
+ onLog: () => {},
+ signal: ac.signal,
+ deps: {
+ fetch: async (u, i) => {
+ reads++;
+ if (reads === 3) ac.abort();
+ return cdn.fetch(u, i);
+ },
+ chunkBytes: 8 * 1024,
+ },
+ });
+ assert.equal(r.kind, "aborted");
+ const entries = await readdir(videoDir);
+ assert.ok(entries.includes("audio.mp4.stored.part"));
+ assert.ok(entries.includes("audio.mp4.stored.part.json"));
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a CDN that ignores the range: the whole body is the file", { skip: !FF }, async () => {
+ const { root, videoDir } = await setup();
+ const { clean } = await recording(root);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, ignoreRange: true });
+ try {
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: { ...config, keepSourceVideo: true },
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024, knobs: EVERY_CHUNK },
+ });
+ assert.equal(r.kind, "ok");
+ assert.equal(cdn.requests.length, 1);
+ assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a 404 is an http-error, nothing kept", async () => {
+ const { root, videoDir } = await setup();
+ const cdn = await startFakeRangedCdn({ files: {} });
+ try {
+ const r = await storedUrlDownload({
+ paths,
+ videoDir,
+ stored: storedFor(cdn.url(FILE_PATH)),
+ channelConfig: config,
+ audioFormat: "mp3",
+ audioCheck: true,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: { fetch: cdn.fetch },
+ });
+ assert.equal(r.kind, "http-error");
+ assert.equal(r.httpStatus, 404);
+ assert.deepEqual(await readdir(videoDir), []);
+ } finally {
+ await cdn.close();
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/ytdlp/storedUrlDownload.ts b/common/ytdlp/storedUrlDownload.ts
@@ -0,0 +1,581 @@
+// A WHOLE FILE FROM THE STORED MEDIA URL, READ THE WAY THE PLAYER READS IT
+// (release 32 R7).
+//
+// Measured 2026-10-16: Odysee answers yt-dlp with 429 — its lookup API, and its
+// own fetch of the stored original-file URL (one unranged GET) — while a
+// browser gets 200 and 206. The player's reads are RANGED GETs of
+// `player.odycdn.com/v6/streams/<claim>/<sd>.mp4` with the page's Referer and
+// Origin and a browser user agent, no cookies. The clip-window path cuts that
+// way with ffmpeg (fetchWindowManaged.ts); this is the same for a FULL download:
+//
+// - sequential Range requests of a fixed chunk (STORED_URL_CHUNK_BYTES) with
+// the player's headers (lib/storedMediaUrl.ts storedMediaHeaders), appended
+// to `audio.<ext>.stored.part` in the video's dir;
+// - resumable: `audio.<ext>.stored.part.json` says which URL the partial is of
+// and how many of its bytes passed the last integrity probe; a resume
+// truncates to that and asks for the rest. A partial without one (or of
+// another URL) is discarded — its provenance is unknown;
+// - a 429 or 403 mid-file stops with the partial KEPT (resume later) and the
+// caller backs the platform off; the abort signal stops it the same way;
+// - THE AUDIO CHECK, the same pipeline as the audio-checked yt-dlp download
+// (audioCheckedDownload.ts), on a producer of its own: its knobs and AIMD
+// cadence (resolveKnobs, audioCheckCadence.ts), a periodic probe of the
+// growing partial, a malformed verdict rolling back to the last good byte
+// count (a truncate — the producer is this loop, so there is nothing to
+// SIGSTOP and no `.good` copy to take), more than `maxRollbacks` in a row
+// ending failed-corrupt-source; then the final probe of the whole file, one
+// re-fetch from the last good byte on a malformed verdict, and a second
+// malformed verdict ending corrupt-full-source with the file KEPT;
+// - then the configured audio extraction (transcodeAudio) and, unless the
+// channel keeps its source, the container removed — exactly as the
+// audio-checked download ends.
+//
+// The caller (downloadOneManaged.ts) owns the rest: the gap between two new
+// files on a platform, the outcome sidecar, the media tier's hook, the archive
+// line and the corrupt-source refetch around it.
+
+import { open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import type { AudioFormat, ChannelConfig } from "../lib/channelConfig";
+import { isRealAudioFile } from "../lib/mediaFiles";
+import { removeMediaFile } from "../lib/mediaTier-server";
+import type { Paths } from "../lib/paths";
+import { storedMediaHeaders, type StoredMediaUrl } from "../lib/storedMediaUrl";
+import { transcodeAudio } from "../controller/transcode";
+import { DLOM_PROBE_MARKER, DOWNLOAD_PROGRESS_MARKER } from "../jobs/progressParsers";
+import { resolveKnobs, type CheckpointRecord, type Knobs } from "./audioCheckedDownload";
+import { backoffInterval, formatInterval, recoverInterval, type CadenceParams } from "./audioCheckCadence";
+import type { StreamVerdict } from "./ffmpegStreamClassify";
+import { probeAudioStream } from "./ffmpegStreamProbe";
+
+// One ranged read. The player asks for a few MiB at a time; 8 MiB keeps a 3 GB
+// file to ~400 requests of one connection each, one after another.
+export const STORED_URL_CHUNK_BYTES = 8 * 1024 * 1024;
+
+export const STORED_PART_SUFFIX = ".stored.part";
+export const STORED_STATE_SUFFIX = ".stored.part.json";
+
+export type StoredUrlDownloadKind =
+ | "ok"
+ // The CDN answered 429 or 403: the partial is kept, the platform backs off.
+ | "rate-limited"
+ // Any other refusal (404, 410, 5xx, a range it would not serve).
+ | "http-error"
+ // The connection failed or ended with nothing.
+ | "network"
+ | "failed-corrupt-source"
+ | "corrupt-full-source"
+ | "aborted"
+ // The file came down clean and the audio extraction failed; the container stays.
+ | "extract-failed";
+
+export type StoredUrlDownloadResult = {
+ kind: StoredUrlDownloadKind;
+ // Bytes of the partial (or the whole file) on disk when it ended.
+ bytes: number;
+ totalBytes: number | null;
+ // Where this run started reading (0, or a resumed partial's good bytes).
+ resumedFrom: number;
+ httpStatus?: number;
+ error?: string;
+ checkpoints: CheckpointRecord[];
+ rollbacks: number;
+ restarts: number;
+ finalProbeVerdict?: StreamVerdict;
+ // The container's file name in the video dir (`audio.<ext>`).
+ container: string;
+};
+
+export type StoredUrlDownloadDeps = {
+ // How a range is asked for. Default: the global fetch. Tests send the CDN
+ // host to a fake on loopback (testing/web/fakeRangedCdn.mjs).
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
+ chunkBytes?: number;
+ // Overrides of the audio check's resolved knobs (tests: a 0 ms interval, a
+ // small size gate).
+ knobs?: Partial<Knobs>;
+ now?: () => number;
+};
+
+export type StoredUrlDownloadOpts = {
+ paths: Paths;
+ videoDir: string;
+ stored: StoredMediaUrl;
+ channelConfig: ChannelConfig;
+ audioFormat: AudioFormat;
+ // audioCheckApplies(config, PAGE url) — decided by the caller.
+ audioCheck: boolean;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ deps?: StoredUrlDownloadDeps;
+};
+
+// The container extension a stored URL names: its path's, when that is a media
+// extension the app knows (`audio.<ext>` a real audio file), else mp4.
+export function storedContainerExt(url: string): string {
+ let ext = "";
+ try {
+ const base = new URL(url).pathname.split("/").pop() ?? "";
+ const dot = base.lastIndexOf(".");
+ ext = dot > 0 ? base.slice(dot + 1).toLowerCase() : "";
+ } catch {
+ /* not a URL: the default */
+ }
+ return ext && isRealAudioFile(`audio.${ext}`) ? ext : "mp4";
+}
+
+export function storedPartNames(url: string): { container: string; part: string; state: string } {
+ const container = `audio.${storedContainerExt(url)}`;
+ return {
+ container,
+ part: container + STORED_PART_SUFFIX,
+ state: container + STORED_STATE_SUFFIX,
+ };
+}
+
+type ResumeState = {
+ version: 1;
+ url: string;
+ totalBytes: number | null;
+ // The bytes of the partial that passed the last probe (with the audio check
+ // off: every byte written).
+ goodBytes: number;
+ updatedAt: string;
+};
+
+async function readState(file: string): Promise<ResumeState | null> {
+ try {
+ const raw = JSON.parse(await readFile(file, "utf8")) as Partial<ResumeState>;
+ if (
+ raw &&
+ raw.version === 1 &&
+ typeof raw.url === "string" &&
+ typeof raw.goodBytes === "number" &&
+ Number.isFinite(raw.goodBytes) &&
+ raw.goodBytes >= 0
+ ) {
+ return {
+ version: 1,
+ url: raw.url,
+ goodBytes: raw.goodBytes,
+ totalBytes: typeof raw.totalBytes === "number" ? raw.totalBytes : null,
+ updatedAt: String(raw.updatedAt ?? ""),
+ };
+ }
+ } catch {
+ /* no state */
+ }
+ return null;
+}
+
+async function sizeOf(file: string): Promise<number | null> {
+ try {
+ return (await stat(file)).size;
+ } catch {
+ return null;
+ }
+}
+
+async function truncateTo(file: string, bytes: number): Promise<void> {
+ const fh = await open(file, "r+");
+ try {
+ await fh.truncate(bytes);
+ } finally {
+ await fh.close();
+ }
+}
+
+// ffmpeg's words for "this is not (yet) a file I can open".
+const NOT_YET_READABLE_RE = /Error opening input|moov atom not found|Invalid data found when processing input/i;
+
+const CONTENT_RANGE_RE = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i;
+const UNSATISFIED_RANGE_RE = /^bytes\s+\*\/(\d+)$/i;
+
+function isAbort(err: unknown, signal: AbortSignal): boolean {
+ return signal.aborted || (err as Error)?.name === "AbortError";
+}
+
+export async function storedUrlDownload(
+ opts: StoredUrlDownloadOpts,
+): Promise<StoredUrlDownloadResult> {
+ const { videoDir, stored, signal, onLog } = opts;
+ const fetchImpl = opts.deps?.fetch ?? ((u: string, i: RequestInit) => fetch(u, i));
+ const chunkBytes = Math.max(1, opts.deps?.chunkBytes ?? STORED_URL_CHUNK_BYTES);
+ const now = opts.deps?.now ?? Date.now;
+ const knobs: Knobs = { ...resolveKnobs({ channelConfig: opts.channelConfig }), ...(opts.deps?.knobs ?? {}) };
+ const names = storedPartNames(stored.url);
+ const partFile = path.join(videoDir, names.part);
+ const stateFile = path.join(videoDir, names.state);
+ const containerFile = path.join(videoDir, names.container);
+ const headers = storedMediaHeaders(stored);
+
+ const checkpoints: CheckpointRecord[] = [];
+ let rollbacks = 0;
+ let restarts = 0;
+ let consecutiveRollbacks = 0;
+ let finalProbeMalformed = 0;
+ let finalProbeVerdict: StreamVerdict | undefined;
+ let currentIntervalMs = knobs.intervalMs;
+ let cleanStreak = 0;
+ const cadence: CadenceParams = {
+ ceilingMs: knobs.intervalMs,
+ floorMs: knobs.backoffFloorMs,
+ factor: knobs.backoffFactor,
+ recoverStepMs: knobs.recoverStepMs,
+ recoverAfterClean: knobs.recoverAfterClean,
+ };
+
+ // ---- Resume, or start clean ----
+ let total: number | null = null;
+ let offset = 0;
+ let goodBytes = 0;
+ const partSize = await sizeOf(partFile);
+ const prior = await readState(stateFile);
+ if (partSize !== null) {
+ if (prior && prior.url === stored.url && prior.goodBytes <= partSize) {
+ if (prior.goodBytes < partSize) await truncateTo(partFile, prior.goodBytes);
+ offset = goodBytes = prior.goodBytes;
+ total = prior.totalBytes;
+ onLog(
+ `Resuming ${names.part} at ${offset} bytes` +
+ (total ? ` of ${total}` : "") +
+ (opts.audioCheck ? " (the last probed-clean byte)" : "") +
+ ".\n",
+ );
+ } else {
+ await rm(partFile, { force: true });
+ onLog(`Discarded ${names.part}: no resume state for this URL.\n`);
+ }
+ } else if (prior) {
+ await rm(stateFile, { force: true });
+ }
+ const resumedFrom = offset;
+
+ const saveState = async (): Promise<void> => {
+ const state: ResumeState = {
+ version: 1,
+ url: stored.url,
+ totalBytes: total,
+ goodBytes,
+ updatedAt: new Date(now()).toISOString(),
+ };
+ await writeFile(stateFile, JSON.stringify(state) + "\n");
+ };
+
+ const result = (
+ kind: StoredUrlDownloadKind,
+ extra: { httpStatus?: number; error?: string; bytes?: number } = {},
+ ): StoredUrlDownloadResult => ({
+ kind,
+ bytes: extra.bytes ?? offset,
+ totalBytes: total,
+ resumedFrom,
+ ...(extra.httpStatus !== undefined ? { httpStatus: extra.httpStatus } : {}),
+ ...(extra.error ? { error: extra.error } : {}),
+ checkpoints,
+ rollbacks,
+ restarts,
+ ...(finalProbeVerdict ? { finalProbeVerdict } : {}),
+ container: names.container,
+ });
+
+ // A stop that keeps the partial for a resume: the good bytes recorded.
+ const keepPartial = async (
+ kind: StoredUrlDownloadKind,
+ extra: { httpStatus?: number; error?: string } = {},
+ ): Promise<StoredUrlDownloadResult> => {
+ if (!opts.audioCheck) goodBytes = offset;
+ if ((await sizeOf(partFile)) !== null) await saveState().catch(() => {});
+ return result(kind, extra);
+ };
+
+ // ---- The integrity probe of the partial (audio check on) ----
+ let lastCheckAt = now();
+ let lastProbeMs = 0;
+ let prevProbeMs = 0;
+ const checkpoint = async (): Promise<"ok" | "rolled-back" | "too-many"> => {
+ if (offset <= goodBytes + knobs.sizeGateBytes) {
+ checkpoints.push({ at: new Date(now()).toISOString(), bytes: offset, verdict: null, action: "skip-size-gate" });
+ return "ok";
+ }
+ const estMs = lastProbeMs > 0 ? lastProbeMs + Math.max(0, lastProbeMs - prevProbeMs) : 0;
+ onLog(`${DLOM_PROBE_MARKER} status=start estMs=${Math.round(estMs)}\n`);
+ const started = now();
+ const probe = await probeAudioStream({ ffmpegBin: opts.paths.ffmpegBin, file: partFile, signal, onLog });
+ const durationMs = now() - started;
+ prevProbeMs = lastProbeMs;
+ lastProbeMs = durationMs;
+ lastCheckAt = now();
+ const intervalSec = Math.round(currentIntervalMs / 1000);
+ // TOO EARLY TO JUDGE: ffmpeg could not open the container at all and no
+ // checkpoint has been clean yet — the first reads of an MP4 whose index is
+ // longer than what has come down. Not corruption; the next read decides.
+ // (A header that is itself damaged is caught by the final probe.)
+ if (probe.verdict === "malformed" && goodBytes === 0 && NOT_YET_READABLE_RE.test(probe.stderr)) {
+ checkpoints.push({
+ at: new Date(now()).toISOString(),
+ bytes: offset,
+ verdict: null,
+ action: "skip-not-yet-readable",
+ durationMs,
+ });
+ onLog(`${DLOM_PROBE_MARKER} status=done skip=1\n`);
+ onLog(`Checkpoint at ${offset} bytes: the container cannot be opened yet; reading on.\n`);
+ return "ok";
+ }
+ if (probe.verdict === "clean" || probe.verdict === "partial") {
+ checkpoints.push({
+ at: new Date(now()).toISOString(),
+ bytes: offset,
+ verdict: probe.verdict,
+ action: "advance",
+ durationMs,
+ intervalMs: currentIntervalMs,
+ });
+ onLog(`${DLOM_PROBE_MARKER} status=done durationMs=${durationMs} intervalSec=${intervalSec} reset=0\n`);
+ onLog(`Checkpoint OK at ${offset} bytes (verdict=${probe.verdict}).\n`);
+ goodBytes = offset;
+ consecutiveRollbacks = 0;
+ await saveState();
+ const rec = recoverInterval(currentIntervalMs, cleanStreak, cadence);
+ if (rec.intervalMs > currentIntervalMs) {
+ onLog(
+ `Audio-check interval recovering: ${formatInterval(currentIntervalMs)} -> ${formatInterval(rec.intervalMs)} after clean checkpoints\n`,
+ );
+ }
+ currentIntervalMs = rec.intervalMs;
+ cleanStreak = rec.cleanStreak;
+ return "ok";
+ }
+ const action = goodBytes > 0 ? "rollback" : "restart";
+ checkpoints.push({
+ at: new Date(now()).toISOString(),
+ bytes: offset,
+ verdict: probe.verdict,
+ action,
+ durationMs,
+ intervalMs: currentIntervalMs,
+ });
+ onLog(`${DLOM_PROBE_MARKER} status=done durationMs=${durationMs} intervalSec=${intervalSec} reset=1\n`);
+ onLog(
+ `Checkpoint MALFORMED at ${offset} bytes. ` +
+ (goodBytes > 0 ? `Rolling back to ${goodBytes} bytes.\n` : "No clean checkpoint yet; restarting from 0.\n"),
+ );
+ cleanStreak = 0;
+ const next = backoffInterval(currentIntervalMs, cadence);
+ if (next < currentIntervalMs) {
+ onLog(
+ `Audio-check interval backoff: ${formatInterval(currentIntervalMs)} -> ${formatInterval(next)} after malformed checkpoint\n`,
+ );
+ currentIntervalMs = next;
+ }
+ if (action === "rollback") rollbacks++;
+ else restarts++;
+ consecutiveRollbacks++;
+ await truncateTo(partFile, goodBytes);
+ offset = goodBytes;
+ await saveState();
+ return consecutiveRollbacks > knobs.maxRollbacks ? "too-many" : "rolled-back";
+ };
+
+ // ---- Progress, for the /jobs bars (the yt-dlp template's shape) ----
+ let lastProgressAt = 0;
+ let windowStartAt = now();
+ let windowStartBytes = offset;
+ const progress = (final = false): void => {
+ const t = now();
+ if (!final && t - lastProgressAt < 1000) return;
+ lastProgressAt = t;
+ const secs = Math.max(0.001, (t - windowStartAt) / 1000);
+ const speed = Math.max(0, (offset - windowStartBytes) / secs);
+ const eta = total && speed > 0 ? Math.round((total - offset) / speed) : "NA";
+ onLog(
+ `${DOWNLOAD_PROGRESS_MARKER} status=${final ? "finished" : "downloading"} downloaded=${offset} ` +
+ `total=${total ?? "NA"} frag=NA/NA speed=${speed.toFixed(2)} eta=${eta}\n`,
+ );
+ };
+
+ onLog(
+ `Reading ${stored.url} in ranges of ${chunkBytes} bytes, as the player does ` +
+ `(Referer ${stored.referer}); audio check ${opts.audioCheck ? "on" : "off"}.\n`,
+ );
+
+ // ---- The loop: one ranged read at a time ----
+ for (;;) {
+ if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
+ if (total !== null && offset > total) {
+ // A partial longer than the file is not of this file.
+ onLog(`The partial is longer than the file (${offset} > ${total}); starting over.\n`);
+ await rm(partFile, { force: true });
+ offset = goodBytes = 0;
+ restarts++;
+ }
+ if (total === null || offset < total) {
+ const end = total !== null ? Math.min(total - 1, offset + chunkBytes - 1) : offset + chunkBytes - 1;
+ let res: Response;
+ try {
+ res = await fetchImpl(stored.url, {
+ headers: { ...headers, Range: `bytes=${offset}-${end}` },
+ signal,
+ redirect: "follow",
+ });
+ } catch (err) {
+ if (isAbort(err, signal)) return keepPartial("aborted", { error: "cancelled" });
+ return keepPartial("network", { error: `the ranged read at ${offset} failed: ${(err as Error).message}` });
+ }
+ if (res.status === 429 || res.status === 403) {
+ await res.body?.cancel().catch(() => {});
+ onLog(
+ `HTTP Error ${res.status}: ${res.status === 429 ? "Too Many Requests" : "Forbidden"} — the CDN refused ` +
+ `the read at ${offset} bytes; the partial is kept for a resume.\n`,
+ );
+ return keepPartial("rate-limited", {
+ httpStatus: res.status,
+ error: `HTTP Error ${res.status} from ${stored.host} at ${offset} bytes`,
+ });
+ }
+ if (res.status === 416) {
+ await res.body?.cancel().catch(() => {});
+ const m = UNSATISFIED_RANGE_RE.exec(res.headers.get("content-range") ?? "");
+ if (m) total = Number(m[1]);
+ if (total !== null && offset >= total) continue;
+ return keepPartial("http-error", { httpStatus: 416, error: `the CDN would not serve bytes from ${offset}` });
+ }
+ let whole = false;
+ if (res.status === 206) {
+ const m = CONTENT_RANGE_RE.exec(res.headers.get("content-range") ?? "");
+ if (!m || Number(m[1]) !== offset) {
+ await res.body?.cancel().catch(() => {});
+ return keepPartial("http-error", {
+ httpStatus: 206,
+ error: `the CDN answered another range (${res.headers.get("content-range") ?? "none"}) for ${offset}`,
+ });
+ }
+ if (m[3] !== "*") total = Number(m[3]);
+ } else if (res.status === 200) {
+ // The range was ignored: the body is the whole file. Read it from 0.
+ whole = true;
+ if (offset > 0) {
+ onLog(`The CDN ignored the range at ${offset}; reading the whole file from the start.\n`);
+ await rm(partFile, { force: true });
+ offset = goodBytes = 0;
+ }
+ const len = Number(res.headers.get("content-length"));
+ if (Number.isFinite(len) && len > 0) total = len;
+ } else {
+ await res.body?.cancel().catch(() => {});
+ return keepPartial("http-error", {
+ httpStatus: res.status,
+ error: `HTTP Error ${res.status} from ${stored.host} at ${offset} bytes`,
+ });
+ }
+ // Append the body.
+ const before = offset;
+ const fh = await open(partFile, offset === 0 ? "w" : "a");
+ try {
+ if (res.body) {
+ for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
+ if (signal.aborted) break;
+ await fh.write(chunk);
+ offset += chunk.byteLength;
+ progress();
+ }
+ }
+ } catch (err) {
+ await fh.close().catch(() => {});
+ if (isAbort(err, signal)) return keepPartial("aborted", { error: "cancelled" });
+ return keepPartial("network", { error: `the read at ${before} ended early: ${(err as Error).message}` });
+ }
+ await fh.close();
+ if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
+ if (whole && total === null) total = offset;
+ if (offset === before) {
+ return keepPartial("network", { error: `the CDN sent no bytes at ${offset}` });
+ }
+ if (!opts.audioCheck) {
+ goodBytes = offset;
+ await saveState();
+ }
+ // The periodic probe of the growing partial, between reads. Not on the
+ // read that completed the file: the final probe is next.
+ const done = total !== null && offset >= total;
+ if (opts.audioCheck && !done && now() - lastCheckAt >= currentIntervalMs) {
+ const c = await checkpoint();
+ if (signal.aborted) return keepPartial("aborted", { error: "cancelled" });
+ if (c === "too-many") {
+ onLog(
+ `More than ${knobs.maxRollbacks} rollbacks in a row: the source keeps serving malformed audio. ` +
+ `The partial is kept at ${goodBytes} bytes.\n`,
+ );
+ windowStartAt = now();
+ windowStartBytes = offset;
+ return result("failed-corrupt-source", { error: "the source served malformed audio at every attempt" });
+ }
+ if (c === "rolled-back") {
+ windowStartAt = now();
+ windowStartBytes = offset;
+ }
+ }
+ if (!done) continue;
+ }
+
+ // ---- The whole file is on disk ----
+ progress(true);
+ await rename(partFile, containerFile);
+ if (opts.audioCheck) {
+ const probe = await probeAudioStream({ ffmpegBin: opts.paths.ffmpegBin, file: containerFile, signal, onLog });
+ finalProbeVerdict = probe.verdict;
+ if (probe.verdict === "malformed") {
+ if (signal.aborted) {
+ await rename(containerFile, partFile).catch(() => {});
+ return keepPartial("aborted", { error: "cancelled" });
+ }
+ finalProbeMalformed++;
+ if (finalProbeMalformed > 1) {
+ onLog(
+ `Final probe verdict: malformed again after re-reading. Keeping the downloaded file and flagging ` +
+ `corrupt-full-source: ${containerFile}\n`,
+ );
+ await rm(stateFile, { force: true });
+ return result("corrupt-full-source");
+ }
+ // Re-read from the last good checkpoint (never the whole of a file the
+ // checkpoints never reached past: that is a re-read from 0).
+ const from = goodBytes < offset ? goodBytes : 0;
+ onLog(`Final probe verdict: malformed. Re-reading from ${from} bytes once before giving up.\n`);
+ await rename(containerFile, partFile);
+ await truncateTo(partFile, from);
+ offset = goodBytes = from;
+ rollbacks++;
+ await saveState();
+ continue;
+ }
+ }
+ await rm(stateFile, { force: true });
+ break;
+ }
+
+ // ---- The configured audio extraction ----
+ if (names.container === `audio.${opts.audioFormat}`) {
+ onLog(`File already in target format (${names.container}); skipping transcode.\n`);
+ return result("ok");
+ }
+ try {
+ await transcodeAudio({
+ paths: opts.paths,
+ videoDir,
+ sourceFilename: names.container,
+ targetFormat: opts.audioFormat,
+ onLog,
+ signal,
+ });
+ } catch (err) {
+ if (signal.aborted) return result("aborted", { error: "cancelled" });
+ onLog(`Final transcode failed: ${(err as Error).message}\n`);
+ return result("extract-failed", { error: `the audio extraction failed: ${(err as Error).message}` });
+ }
+ if (!opts.channelConfig.keepSourceVideo) {
+ await removeMediaFile(videoDir, names.container);
+ }
+ return result("ok");
+}