commit de7260e8d3c9abb38b15e216def69aab1951b7a8 parent 5f567a33ba5bf6d4732def0b697a1ea9c7ef0f0b Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 17 Oct 2026 00:19:19 -0400 Merge r32/odysee-ranged: a full Odysee download reads the stored media URL the way the player does — the page opened first (headless Chromium), resumable ranged reads with the player's headers, the audio check with rollback, one new file per 20 min; opt-in per request (transcribe-one, retry-bucket, download-missing) or per channel (storedUrlDownloads) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> # Conflicts: # editor/CHANGELOG.md # plans/FACTS.md Diffstat:
45 files changed, 2900 insertions(+), 64 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/COMMANDS.md b/COMMANDS.md @@ -117,8 +117,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | | `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` | -| `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. | | -| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | +| `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | | +| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | | @@ -144,7 +144,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | -| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false. | | +| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -89,7 +89,11 @@ import { type DownloadFailureClass } from "../lib/availability"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { isAutoSubsOnly } from "../lib/subtitleProvenance"; import { readVideoFiles } from "../lib/videoStatus"; -import { type DownloadOutcomeStatus } from "../lib/downloadOutcome"; +import { + storedUrlAttemptOf, + type DownloadOutcomeStatus, + type StoredUrlAttempt, +} from "../lib/downloadOutcome"; import { downloadQueueKey } from "../lib/queueKeys"; import { isGateHeld } from "../lib/pauseGates"; import { @@ -2037,6 +2041,7 @@ async function runLoop( channelSlug, outcome: result.outcome, ...(result.failureClass ? { failureClass: result.failureClass } : {}), + ...(result.viaStoredUrl ? { viaStoredUrl: true } : {}), }, settledAt, Math.random, @@ -2167,6 +2172,8 @@ type LaunchArgs = { type UnitResult = { outcome: "transcribed" | "skipped" | "failed"; failureClass?: DownloadFailureClass; + // The media came from the record's stored URL (release 32 R7). + viaStoredUrl?: boolean; }; // Whether this unit is an auto-captions replacement: the video's only @@ -2272,6 +2279,7 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> { // reads them after `await res.done` resolves (single-threaded → no race). let unitStatus: DownloadOutcomeStatus | undefined; let unitFailureClass: DownloadFailureClass | undefined; + let unitStored: StoredUrlAttempt | null = null; const res = await runManagedFunction({ kind: AUTO_DOWNLOAD_UNIT_KIND, @@ -2312,6 +2320,7 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> { }); unitStatus = record.status; unitFailureClass = record.failureClass; + unitStored = storedUrlAttemptOf(record); // Land a failed download as a failed JOB (red row) rather than a silent // "done"; the runner reads the captured status/class regardless. A // short-audio download kept its file (so it won't be re-queued) but @@ -2353,6 +2362,16 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> { if (unitStatus === "corrupt-full-source") return { outcome: "skipped" }; // A success whose SUBTITLE fetch alone answered 429 says so: the runner // defers the video's subtitles and leaves the platform alone (release 17). + // Set inside the child job's fn; TS cannot see the assignment from here. + const stored = unitStored as StoredUrlAttempt | null; + if (unitStatus && unitStatus.startsWith("ok") && stored) { + // From the stored media URL (release 32 R7): after a rate-limited page + // lookup the platform backs off as for any 429; otherwise (`only`, held) + // the platform was not asked and is not settled clean. + return stored.why === "rate-limited" + ? { outcome: "transcribed", failureClass: "rate_limit" } + : { outcome: "transcribed", viaStoredUrl: true }; + } if (unitStatus && unitStatus.startsWith("ok")) { return unitFailureClass === "subs_rate_limit" ? { outcome: "transcribed", failureClass: "subs_rate_limit" } diff --git a/common/jobs/unitOutcome.test.ts b/common/jobs/unitOutcome.test.ts @@ -300,3 +300,26 @@ test("a hold reached through network failures alone is worded as failing, not ra applyUnitOutcome(s, unit("r", { failureClass: "rate_limit" }), 20, noJitter, pacing); assert.equal(s.platformHolds.youtube.rateLimited, true); }); + +// Release 32 R7: a download through the record's stored media URL asked the +// CDN, not the platform — it retires the video and settles nothing. +test("viaStoredUrl: a success retires the video and leaves the platform's backoff and hold alone", () => { + const s = empty(); + const now = 5_000_000; + s.platformBackoff.odysee = { until: now + 60_000, fails: 3 }; + s.platformHolds.odysee = { since: now - 1, probeAt: now + 60_000, rateLimited: true }; + const r = applyUnitOutcome( + s, + unit("v9", { platform: "odysee", outcome: "transcribed", viaStoredUrl: true }), + now, + noJitter, + ); + assert.equal(r.markCompleted, true); + assert.deepEqual(s.platformBackoff.odysee, { until: now + 60_000, fails: 3 }); + assert.ok(s.platformHolds.odysee); + assert.match(r.line ?? "", /downloaded from its stored media URL; odysee is not settled clean/); + // Without the flag the same success clears both. + applyUnitOutcome(s, unit("v10", { platform: "odysee", outcome: "transcribed" }), now, noJitter); + assert.equal(s.platformBackoff.odysee, undefined); + assert.equal(s.platformHolds.odysee, undefined); +}); diff --git a/common/jobs/unitOutcome.ts b/common/jobs/unitOutcome.ts @@ -17,6 +17,10 @@ // - anything else retires it; a success (`transcribed`) also clears the // platform's cooldown. // - every branch prunes lapsed deferrals, keeping the map bounded. +// - a success through the record's stored media URL (release 32 R7, +// `viaStoredUrl`) retires the video and settles nothing: the platform was +// not asked. One whose page lookup was rate-limited first comes in as a +// `rate_limit` and backs the platform off like any other. // // Release 17, slice RL (see platformBackoff.ts, "The adaptive pace"): // - `rate_limit` also doubles the platform's pace, and a backoff that has @@ -66,6 +70,9 @@ export type FinishedUnit = { channelSlug: string; outcome: "transcribed" | "skipped" | "failed"; failureClass?: DownloadFailureClass; + // Release 32 R7: the media came from the record's stored URL (its CDN), not + // the platform — a success that is not a clean probe of the platform. + viaStoredUrl?: boolean; }; export type UnitOutcomeEffect = { @@ -143,6 +150,14 @@ export function applyUnitOutcome( line: `Auto-download: ${unit.videoId} downloaded; its subtitles were rate-limited (${d.count}×) — ${left}. ${pf ?? "the platform"} is not backed off.`, }; } + if (pf !== null && unit.outcome === "transcribed" && unit.viaStoredUrl) { + // The CDN answered, the platform was not asked: its backoff, hold and + // pace stay as they are. + return { + markCompleted: true, + line: `Auto-download: ${unit.videoId} downloaded from its stored media URL; ${pf} is not settled clean by it.`, + }; + } if (pf !== null && unit.outcome === "transcribed") { const fx = settlePlatformClean(state, pf, { baseSeconds: staticSleepRequestsSeconds(pf), 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.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 34); + assert.equal(CHANNEL_CONFIG_KEYS.length, 35); assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); 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. The player's page is opened first. + | "stored-url-ranged"; export type AudioCheckProbeVerdict = "clean" | "partial" | "malformed"; @@ -103,6 +109,23 @@ 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; + // How many times the player's page was opened first (Odysee's CDN serves a + // file only after a player opened its page; ytdlp/storedUrlPageOpen.ts). + pageOpens?: number; }; // ONE RETRY OF A corrupt-full-source VIDEO (release 30, lane Q), appended to @@ -178,3 +201,17 @@ export type DownloadOutcomeRecord = { }; export const DOWNLOAD_OUTCOME_FILENAME = "download-outcome.json"; + +// The stored-URL attempt a download ended with (release 32 R7), or null. +export function storedUrlAttemptOf(record: Pick<DownloadOutcomeRecord, "attempts">): StoredUrlAttempt | null { + const last = record.attempts.at(-1); + return last?.kind === "stored-url-ranged" ? (last.storedUrl ?? null) : null; +} + +// Did the download ask the PLATFORM anything (a page, its API, yt-dlp)? A +// stored-URL download asked only its CDN — `only`, a held platform, or `only` +// with no stored URL at all asks nothing. A run whose downloads asked the +// platform nothing says nothing about it: it must not settle it clean. +export function askedPlatform(record: Pick<DownloadOutcomeRecord, "attempts">): boolean { + return record.attempts.some((a) => a.kind !== "stored-url-ranged"); +} 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 @@ -71,6 +71,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,35 @@ +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; + unlocks: number; + unlock(): 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; + requireUnlock?: boolean; + unlockBytes?: number; +}): Promise<FakeRangedCdn>; diff --git a/common/testing/web/fakeRangedCdn.mjs b/common/testing/web/fakeRangedCdn.mjs @@ -0,0 +1,120 @@ +// 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. +// - opts.requireUnlock (2026-10-17's finding): every read answers 429 until +// `cdn.unlock()` — what a player opening the video's page does — and, with +// opts.unlockBytes, the unlock lapses after that many bytes are served. + +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; + let unlockedBudget = opts.requireUnlock ? 0 : 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 (unlockedBudget !== null && unlockedBudget <= 0) { + return end(429, { "content-type": "text/plain" }, "Too Many Requests"); + } + 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); + if (unlockedBudget !== null && unlockedBudget !== Infinity) last = Math.min(last, from + unlockedBudget - 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; + if (unlockedBudget !== null && unlockedBudget !== Infinity) unlockedBudget -= 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; + }, + unlocks: 0, + unlock() { + this.unlocks++; + unlockedBudget = typeof opts.unlockBytes === "number" ? opts.unlockBytes : Infinity; + }, + 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/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -104,6 +104,24 @@ import { type SourceVideoQuality, } from "./downloadFormat"; import { DOWNLOAD_PROGRESS_TEMPLATE } from "../jobs/progressParsers"; +import { + resolveStoredUrlMode, + STORED_URL_NEW_FILE_GAP_MS, + storedUrlGapKey, + storedUrlWhyText, + type StoredMediaUrl, + type StoredUrlMode, + type StoredUrlWhy, +} from "../lib/storedMediaUrl"; +import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import type { DownloadFailureClass } from "../lib/availability"; +import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; +import { + storedUrlDownload, + type StoredUrlDownloadDeps, + type StoredUrlDownloadResult, +} from "./storedUrlDownload"; +import { openPlayerPage, PAGE_OPEN_PLATFORMS, type PageOpener } from "./storedUrlPageOpen"; // The `--print` archive marker below implies `--quiet`, which otherwise @@ -203,6 +221,26 @@ export type ManagedDownloadOpts = { // Test seam: how the corrupt-source refetch measures a file's decodable // seconds (ytdlp/corruptRefetch.ts). Every production caller passes none. corruptRefetchDeps?: CorruptRefetchDeps; + // THE STORED MEDIA URL (release 32 R7, ytdlp/storedUrlDownload.ts): a full + // download may read the media URL the record's metadata.info.json already + // stores, the way the platform's player does — `never` | `fallback` (the page + // first; on its rate limit, the stored URL) | `only` (no page request). + // Absent = the channel's `storedUrlDownloads`, else never. Transcribe + // handling, STORED_URL_PLATFORMS only. + storedUrl?: StoredUrlMode; + // The platform is HELD and the caller's door let this run through as + // `only` (the log and the attempt say "held" rather than "only"). + storedUrlHeld?: boolean; + // Test seam: the CDN fetch, the chunk, the audio check's knobs, and the gap + // between two stored-URL files (default STORED_URL_NEW_FILE_GAP_MS) with + // its sleep. Every production caller passes none. + storedUrlDeps?: StoredUrlDownloadDeps & { + // The player-page opener (storedUrlPageOpen.ts). Absent = the real one for + // a platform in PAGE_OPEN_PLATFORMS; null = no page open. Tests inject one. + openPage?: PageOpener | null; + gapMs?: number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; + }; }; // When `reuseInfoJson` is true, the real download reuses the metadata the @@ -779,6 +817,30 @@ async function runManagedDownload( // (e.g. lbry -> odysee), which is the authoritative signal. let resolvedPlatform: Platform | null = opts.channelConfig.platform ?? detectPlatform(opts.videoUrl); + // ---------- The stored media URL (release 32 R7) ---------- + // Read BEFORE the prefetch rewrites metadata.info.json: a prefetch the + // platform refused writes nothing useful, and the stored URL is the record's. + const storedMode = resolveStoredUrlMode(opts.storedUrl, opts.channelConfig.storedUrlDownloads); + const storedDir = canonicalId ? path.join(channelDir, "data", canonicalId) : null; + const stored = + storedMode !== "never" && opts.channelConfig.handling === "transcribe" && storedDir + ? await storedMediaUrl(storedDir) + : null; + if (storedMode === "only" && canonicalId && storedDir) { + if (stored) { + return runStoredUrlDownload(opts, { + videoDir: storedDir, + videoId: canonicalId, + channelDir, + startedAt, + stored, + why: opts.storedUrlHeld ? "held" : "only", + attempts, + }); + } + return noStoredUrlOutcome(opts, storedDir, canonicalId, startedAt, attempts); + } + if (canonicalId && !opts.signal.aborted) { const videoDir = path.join(channelDir, "data", canonicalId); // In "always" mode the prefetch (like every other invocation) carries the @@ -890,6 +952,22 @@ async function runManagedDownload( classifyDownloadFailure(lastFullTail, lastPrefetch.availabilityClass) === "rate_limit" ) { + if (stored && storedMode === "fallback") { + opts.onLog( + `Metadata prefetch for ${canonicalId} was rate-limited by the source; ` + + `downloading from the stored media URL instead (the platform still backs off).\n`, + ); + return runStoredUrlDownload(opts, { + videoDir, + videoId: canonicalId, + channelDir, + startedAt, + stored, + why: "rate-limited", + attempts, + lastFullTail, + }); + } opts.onLog( `Metadata prefetch for ${canonicalId} was rate-limited by the source; ` + `not attempting the download (the platform backs off instead).\n`, @@ -1428,6 +1506,34 @@ async function runManagedDownload( } } + // A RATE-LIMITED DOWNLOAD FALLS BACK TO THE STORED URL (release 32 R7): the + // measured case — yt-dlp's own fetch of Odysee's original file answered 429 + // while the player's ranged reads of it answered 206. + if ( + !lastSucceeded && + stored && + storedMode === "fallback" && + canonicalId && + storedDir && + !opts.signal.aborted && + classifyDownloadFailure(lastFullTail, attempts.at(-1)?.availabilityClass) === "rate_limit" + ) { + opts.onLog( + `The download of ${canonicalId} was rate-limited by the source; ` + + `downloading from the stored media URL instead (the platform still backs off).\n`, + ); + return runStoredUrlDownload(opts, { + videoDir: storedDir, + videoId: canonicalId, + channelDir, + startedAt, + stored, + why: "rate-limited", + attempts, + lastFullTail, + }); + } + const videoDir = audioCheckVideoDir ?? path.join(channelDir, "data", canonicalId ?? "unknown"); @@ -1450,35 +1556,7 @@ async function runManagedDownload( // livestreams (unreliable durations), short videos, and unmeasurable files // (probe failure -> null -> no false positive). The file is left on disk; the // caller marks the download failed-short-audio so it isn't transcribed. - const probeShortAudio = async (): Promise< - NonNullable<DownloadOutcomeRecord["shortAudio"]> | null - > => { - const meta = await loadRawMetadataFromDir(videoDir); - const expected = meta?.duration; - if ( - !meta || - isLivestreamMetadata(meta) || - typeof expected !== "number" || - expected < INCOMPLETE_TRANSCRIPT_MIN_DURATION_SEC - ) { - return null; - } - const audioDurationSec = await probeMediaDurationSec({ - ffprobeBin: opts.paths.ffprobeBin, - file: path.join(videoDir, `audio.${fmt}`), - signal: opts.signal, - onLog: opts.onLog, - }); - if (!isShortAudio(audioDurationSec, expected, { isLivestream: false })) { - return null; - } - const a = audioDurationSec as number; - return { - audioDurationSec: Math.round(a * 10) / 10, - expectedDurationSec: expected, - coverage: Math.round((a / expected) * 1000) / 1000, - }; - }; + const probeShortAudio = () => probeShortAudioIn(opts, videoDir, fmt); // ---------- App-side extraction (transcribe handling) ---------- // After a successful non-audio-check transcribe download in app mode, produce @@ -1799,6 +1877,9 @@ async function writeOutcome( shortAudio?: DownloadOutcomeRecord["shortAudio"]; // The subtitle fetch alone answered 429 and the download went on. subsRateLimited?: boolean; + // A failure's class when the caller knows it better than the tail does + // (the stored-URL download: a 403 from the CDN is its rate limit). + failureClass?: DownloadFailureClass; }, ): Promise<DownloadOutcomeRecord> { const { status, attempts } = o; @@ -1810,7 +1891,7 @@ async function writeOutcome( // its caller defers the subtitles (release 17, slice RL). const isFailure = status === "failed" || status === "failed-corrupt-source"; const failureClass = isFailure - ? classifyDownloadFailure(o.lastFullTail, attempts.at(-1)?.availabilityClass) + ? (o.failureClass ?? classifyDownloadFailure(o.lastFullTail, attempts.at(-1)?.availabilityClass)) : o.subsRateLimited && status.startsWith("ok") ? ("subs_rate_limit" as const) : undefined; @@ -1868,3 +1949,273 @@ async function writeOutcome( return record; } + +// Download-time duration guard: probe the produced audio.<fmt> and compare its +// actual length to the metadata duration. A large shortfall means the source +// served a truncated stream (e.g. a CDN-truncated HLS rung) even though yt-dlp +// exited 0. Returns the shortfall metrics when tripped, else null. Skips +// livestreams (unreliable durations), short videos, and unmeasurable files +// (probe failure -> null -> no false positive). The file is left on disk; the +// caller marks the download failed-short-audio so it isn't transcribed. +async function probeShortAudioIn( + opts: ManagedDownloadOpts, + videoDir: string, + fmt: AudioFormat, +): Promise<NonNullable<DownloadOutcomeRecord["shortAudio"]> | null> { + const meta = await loadRawMetadataFromDir(videoDir); + const expected = meta?.duration; + if ( + !meta || + isLivestreamMetadata(meta) || + typeof expected !== "number" || + expected < INCOMPLETE_TRANSCRIPT_MIN_DURATION_SEC + ) { + return null; + } + const audioDurationSec = await probeMediaDurationSec({ + ffprobeBin: opts.paths.ffprobeBin, + file: path.join(videoDir, `audio.${fmt}`), + signal: opts.signal, + onLog: opts.onLog, + }); + if (!isShortAudio(audioDurationSec, expected, { isLivestream: false })) { + return null; + } + const a = audioDurationSec as number; + return { + audioDurationSec: Math.round(a * 10) / 10, + expectedDurationSec: expected, + coverage: Math.round((a / expected) * 1000) / 1000, + }; +} + +// ---------- The stored media URL's whole-file download (release 32 R7) ---------- + +// What a stored-URL download ended as, for the outcome record. +function storedUrlStatus( + r: StoredUrlDownloadResult, + audioCheck: boolean, +): { status: DownloadOutcomeStatus; failureClass?: DownloadFailureClass } { + switch (r.kind) { + case "ok": + return { status: audioCheck ? "ok-audio-checked" : "ok" }; + case "failed-corrupt-source": + return { status: "failed-corrupt-source", failureClass: "unknown" }; + case "corrupt-full-source": + return { status: "corrupt-full-source" }; + case "rate-limited": + return { status: "failed", failureClass: "rate_limit" }; + case "network": + return { status: "failed", failureClass: "network" }; + case "http-error": + return { + status: "failed", + failureClass: r.httpStatus !== undefined && r.httpStatus >= 500 ? "network" : "per_video", + }; + case "aborted": + case "extract-failed": + return { status: "failed", failureClass: "unknown" }; + } +} + +// The archive line the yt-dlp run would have printed (`%(extractor)s %(id)s`), +// read off the record's metadata. +async function storedArchiveLine(videoDir: string): Promise<string | null> { + try { + const info = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as Record< + string, + unknown + >; + const extractor = + typeof info.extractor === "string" + ? info.extractor + : typeof info.extractor_key === "string" + ? info.extractor_key.toLowerCase() + : null; + const id = typeof info.id === "string" ? info.id : null; + return extractor && id ? `${extractor} ${id}` : null; + } catch { + return null; + } +} + +async function runStoredUrlDownload( + opts: ManagedDownloadOpts, + ctx: { + videoDir: string; + videoId: string; + channelDir: string; + startedAt: string; + stored: StoredMediaUrl; + why: StoredUrlWhy; + attempts: DownloadAttempt[]; + lastFullTail?: string; + }, +): Promise<DownloadOutcomeRecord> { + const { stored, why, attempts, videoDir, videoId } = ctx; + const deps = opts.storedUrlDeps; + const key = storedUrlGapKey(stored.platform); + const gapMs = deps?.gapMs ?? STORED_URL_NEW_FILE_GAP_MS; + const fmt: AudioFormat = opts.audioFormatOverride ?? opts.channelConfig.audioFormat ?? "mp3"; + // Keyed on the PAGE url, as every download path's check is. + const audioCheck = audioCheckApplies(opts.channelConfig, opts.videoUrl); + opts.onLog( + `Downloading ${videoId} from the stored media URL (${stored.host}) ` + + `${storedUrlWhyText(why, stored.platform)}.\n`, + ); + const attemptBase = { + n: 1, + kind: "stored-url-ranged" as const, + handling: opts.channelConfig.handling, + usedCookies: false, + }; + // ONE NEW FILE PER PLATFORM PER REST: the gap since the last stored-URL + // download on this platform, waited out here, so a batch waits rather than + // 429s. Set again when this one ends. + try { + await waitForPlatformGap({ + label: `A download from the stored media URL (${stored.platform})`, + remainingMs: () => platformGapRemainingMs(key), + signal: opts.signal, + onLog: (line) => opts.onLog(`${line}\n`), + ...(deps?.sleep ? { sleep: deps.sleep } : {}), + }); + } catch { + attempts.push({ + ...attemptBase, + ytdlpExitCode: 1, + error: "cancelled while waiting for the gap between stored-URL files", + storedUrl: { host: stored.host, why, bytes: 0 }, + }); + return writeOutcome(opts, videoDir, { + videoId, + status: "failed", + startedAt: ctx.startedAt, + attempts, + lastFullTail: "", + failureClass: "unknown", + }); + } + notePlatformGap(key, gapMs); + let r: StoredUrlDownloadResult; + try { + r = await storedUrlDownload({ + paths: opts.paths, + videoDir, + stored, + channelConfig: opts.channelConfig, + audioFormat: fmt, + audioCheck, + // Opened before the first read, and again on a mid-file refusal. + pageUrl: opts.videoUrl, + openPage: + deps?.openPage !== undefined + ? deps.openPage + : PAGE_OPEN_PLATFORMS.includes(stored.platform) + ? openPlayerPage + : null, + onLog: opts.onLog, + signal: opts.signal, + ...(deps ? { deps } : {}), + }); + } finally { + notePlatformGap(key, gapMs); + } + if (gapMs > 0) { + opts.onLog( + `The next download from ${stored.platform}'s stored media URLs waits ${Math.round(gapMs / 60_000)} min ` + + `(one new file per rest).\n`, + ); + } + const ok = r.kind === "ok"; + attempts.push({ + ...attemptBase, + ytdlpExitCode: ok ? 0 : 1, + ...(r.error ? { error: r.error } : {}), + ...(audioCheck + ? { + audioCheck: { + checkpoints: r.checkpoints.length, + rollbacks: r.rollbacks, + restarts: r.restarts, + ...(r.finalProbeVerdict ? { finalProbeVerdict: r.finalProbeVerdict } : {}), + }, + } + : {}), + storedUrl: { + host: stored.host, + why, + bytes: r.bytes, + ...(r.totalBytes !== null ? { totalBytes: r.totalBytes } : {}), + ...(r.resumedFrom > 0 ? { resumedFrom: r.resumedFrom } : {}), + ...(r.httpStatus !== undefined ? { httpStatus: r.httpStatus } : {}), + ...(r.pageOpens > 0 ? { pageOpens: r.pageOpens } : {}), + }, + }); + let { status, failureClass } = storedUrlStatus(r, audioCheck); + let shortAudio: DownloadOutcomeRecord["shortAudio"]; + if (ok && !opts.signal.aborted) { + const short = await probeShortAudioIn(opts, videoDir, fmt); + if (short) { + shortAudio = short; + status = "failed-short-audio"; + failureClass = undefined; + opts.onLog( + `Short audio for ${videoId}: ${short.audioDurationSec}s of ${short.expectedDurationSec}s ` + + `(${Math.round(short.coverage * 100)}% of the video). Keeping the file and flagging it.\n`, + ); + } + } + if (status.startsWith("ok") && opts.appendArchive !== false) { + const line = await storedArchiveLine(videoDir); + if (line) { + try { + await appendArchiveLine(ctx.channelDir, line); + } catch (err) { + opts.onLog(`Archive append failed (${line}): ${(err as Error).message}\n`); + } + } + } + return writeOutcome(opts, videoDir, { + videoId, + status, + startedAt: ctx.startedAt, + attempts, + lastFullTail: r.error ?? ctx.lastFullTail ?? "", + shortAudio, + ...(failureClass ? { failureClass } : {}), + }); +} + +// `only`, and the record stores no media URL the allowlist trusts (or the +// channel is not transcribe handling): nothing is asked of anyone. A per-video +// failure, so a batch goes on to the next video. +async function noStoredUrlOutcome( + opts: ManagedDownloadOpts, + videoDir: string, + videoId: string, + startedAt: string, + attempts: DownloadAttempt[], +): Promise<DownloadOutcomeRecord> { + const why = + opts.channelConfig.handling !== "transcribe" + ? "a stored-URL download is for transcribe handling" + : "the record stores no media URL on its platform's CDN"; + opts.onLog(`No download for ${videoId} (stored URL only): ${why}. Nothing was requested.\n`); + attempts.push({ + n: 1, + kind: "stored-url-ranged", + handling: opts.channelConfig.handling, + usedCookies: false, + ytdlpExitCode: 1, + error: `stored URL only: ${why}`, + }); + return writeOutcome(opts, videoDir, { + videoId, + status: "failed", + startedAt, + attempts, + lastFullTail: "", + failureClass: "per_video", + }); +} 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/managedDownloadsSleep.test.ts b/common/ytdlp/managedDownloadsSleep.test.ts @@ -304,3 +304,59 @@ test("a subtitle 429 on a success is recorded as a subtitle deferral, and the ba assert.deepEqual(r.deferred, ["c/s1"]); assert.deepEqual(r.slept, [30_000]); }); + +// Release 32 R7: a download from the stored media URL. After a rate-limited +// page lookup, its success still backs the platform off; a run of `only` +// downloads asked the platform nothing and does not settle it clean. +const STORED = (why: "rate-limited" | "only"): DownloadAttempt => ({ + n: 1, + kind: "stored-url-ranged", + handling: "transcribe", + usedCookies: false, + ytdlpExitCode: 0, + storedUrl: { host: "player.odycdn.com", why, bytes: 10 }, +}); + +async function storedRun(outcomes: DownloadOutcomeRecord[]): Promise<{ backoffs: string[]; cleans: number }> { + const backoffs: string[] = []; + let cleans = 0; + let i = 0; + const channelConfig = { handling: "transcribe", url: "https://odysee.com/@c:1" } as never; + const requestCounter = { n: 0 }; + await runManagedDownloads( + { + channelSlug: "c", + mode: "download-missing" as never, + channelConfig, + paths: getPaths(), + onLog: () => {}, + signal: new AbortController().signal, + abortOnError: false, + requestCounter, + onPlatformBackoff: (c) => { + backoffs.push(c); + }, + }, + outcomes.map((_, n) => `https://odysee.com/s:${String(n).padStart(40, "0")}`), + channelConfig, + undefined, + { downloadOne: async () => outcomes[i++], sleep: async () => {} }, + ); + // runYtdlpMode settles clean only when requests were made and nothing backed off. + if (requestCounter.n > 0 && backoffs.length === 0) cleans++; + return { backoffs, cleans }; +} + +test("stored URL after a rate-limited lookup: the success backs the platform off", async () => { + const r = await storedRun([ + outcome("ok-audio-checked", [{ ...PREFETCH, handling: "transcribe", ytdlpExitCode: 1 }, STORED("rate-limited")]), + ]); + assert.deepEqual(r.backoffs, ["rate_limit"]); + assert.equal(r.cleans, 0); +}); + +test("stored URL only: the platform was not asked — no backoff and no clean settle", async () => { + const r = await storedRun([outcome("ok-audio-checked", [STORED("only")]), outcome("ok", [STORED("only")])]); + assert.deepEqual(r.backoffs, []); + assert.equal(r.cleans, 0, "a run that asked the platform nothing is not a clean probe"); +}); diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -33,8 +33,11 @@ import { } from "../lib/availability"; import { DOWNLOAD_OUTCOME_FILENAME, + askedPlatform, + storedUrlAttemptOf, type DownloadOutcomeRecord, } from "../lib/downloadOutcome"; +import type { StoredUrlMode } from "../lib/storedMediaUrl"; import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; import { alwaysCookies, @@ -191,6 +194,11 @@ export type RunYtdlpOpts = { // backoff and any hold clear; release 17 review H2). Returns a line for the // log, or null. onPlatformClean?: () => Promise<string | null>; + // Release 32 R7: the stored-media-URL mode for every managed download in + // the run (downloadOneManaged's `storedUrl`; absent = the channel's), and + // whether the door let a held platform through as `only`. + storedUrl?: StoredUrlMode; + storedUrlHeld?: boolean; // Internal: how many requests this run made of the source (a listing, a // per-video download, a raw spawn). Set by runYtdlpMode and shared through // every `{...opts}` copy by reference; a run that asked nothing is not clean @@ -1175,6 +1183,8 @@ export async function runManagedDownloads( extractImmediately: opts.extractImmediately, audioFormatOverride: opts.audioFormatOverride, downloadFormatPreset, + ...(opts.storedUrl ? { storedUrl: opts.storedUrl } : {}), + ...(opts.storedUrlHeld ? { storedUrlHeld: true } : {}), onFilterRejected: (id, entry) => { filterRejections[id] = entry; }, @@ -1192,6 +1202,20 @@ export async function runManagedDownloads( /* shared-state write is best-effort */ } } + // A DOWNLOAD FROM THE STORED MEDIA URL (release 32 R7). Its CDN answered, + // not the platform: a success after the page lookup was rate-limited + // still backs the platform off, and a download that asked the + // platform nothing (`only`, a held platform) is not a request of it — + // a run of those must not settle the platform clean. + const storedAttempt = storedUrlAttemptOf(outcome); + if (storedAttempt?.why === "rate-limited" && outcome.status.startsWith("ok")) { + try { + await opts.onPlatformBackoff?.("rate_limit"); + } catch { + /* shared-state write is best-effort */ + } + } + if (opts.requestCounter && !askedPlatform(outcome)) opts.requestCounter.n--; if (outcome.status === "skipped-filtered") { skippedCount++; } else if (outcome.status === "chat-only") { diff --git a/common/ytdlp/storedUrlDownload.test.ts b/common/ytdlp/storedUrlDownload.test.ts @@ -0,0 +1,494 @@ +// 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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, + pageUrl: PAGE, + openPage: null, + 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 }); + } +}); + +// The orchestrator's finding (2026-10-17): the CDN serves a file only after a +// player opened its page. The opener is injected; no browser here. +function fakeOpener(cdn: { unlock(): void }, calls: string[]) { + return async ({ pageUrl, cdnHost }: { pageUrl: string; cdnHost: string }) => { + calls.push(`${pageUrl} ${cdnHost}`); + cdn.unlock(); + return { ok: true, mediaStatuses: [206] }; + }; +} + +test("the player's page is opened before the first read; a locked CDN then serves the file", { skip: !FF }, async () => { + const { root, videoDir } = await setup(); + const { clean } = await recording(root); + const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, requireUnlock: true }); + const calls: string[] = []; + try { + const r = await storedUrlDownload({ + paths, + videoDir, + stored: storedFor(cdn.url(FILE_PATH)), + channelConfig: { ...config, keepSourceVideo: true }, + audioFormat: "mp3", + audioCheck: true, + pageUrl: PAGE, + openPage: fakeOpener(cdn, calls), + onLog: () => {}, + signal: new AbortController().signal, + deps: { fetch: cdn.fetch, chunkBytes: 16 * 1024, knobs: EVERY_CHUNK }, + }); + assert.equal(r.kind, "ok"); + assert.equal(r.pageOpens, 1); + assert.deepEqual(calls, [`${PAGE} player.odycdn.com`]); + assert.ok(cdn.requests.every((q) => q.status === 206), "no read before the open"); + assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); + } finally { + await cdn.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +test("an unlock that lapses mid-file: the page is opened again and the read goes on", { skip: !FF }, async () => { + const { root, videoDir } = await setup(); + const { clean } = await recording(root); + const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, requireUnlock: true, unlockBytes: 24 * 1024 }); + const calls: string[] = []; + try { + let log = ""; + const r = await storedUrlDownload({ + paths, + videoDir, + stored: storedFor(cdn.url(FILE_PATH)), + channelConfig: { ...config, keepSourceVideo: true }, + audioFormat: "mp3", + audioCheck: true, + pageUrl: PAGE, + openPage: fakeOpener(cdn, calls), + 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.pageOpens >= 3, `opened ${r.pageOpens}×`); + assert.match(log, /HTTP Error 429 at \d+ bytes after \d+ served since the page was opened; opening it again/); + assert.deepEqual(await readFile(path.join(videoDir, "audio.mp4")), clean); + } finally { + await cdn.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +test("an open that does not unlock: one open, then rate-limited — no loop of opens", async () => { + const { root, videoDir } = await setup(); + const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: Buffer.alloc(64 * 1024, 3) }, requireUnlock: true }); + let opens = 0; + try { + const r = await storedUrlDownload({ + paths, + videoDir, + stored: storedFor(cdn.url(FILE_PATH)), + channelConfig: config, + audioFormat: "mp3", + audioCheck: false, + pageUrl: PAGE, + openPage: async () => { + opens++; + return { ok: false, mediaStatuses: [429], error: "the player's media requests were not served" }; + }, + onLog: () => {}, + signal: new AbortController().signal, + deps: { fetch: cdn.fetch, chunkBytes: 8 * 1024 }, + }); + assert.equal(r.kind, "rate-limited"); + assert.equal(opens, 1); + assert.equal(r.pageOpens, 1); + } 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,618 @@ +// 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"; +import type { PageOpener } from "./storedUrlPageOpen"; + +// 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; + // How many times the player's page was opened (storedUrlPageOpen.ts). + pageOpens: number; +}; + +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; + // THE PLAYER'S PAGE IS OPENED FIRST (storedUrlPageOpen.ts): Odysee's CDN + // serves a file only after a player opened its page. Null: no page open + // (a platform that does not need one). Opened before the first read of a + // run, and again on a refusal that follows reads it served — given up when + // a refusal comes straight after an open. + pageUrl: string; + openPage: PageOpener | null; + 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, + }; + + // ---- The player's page ---- + let pageOpens = 0; + // Bytes read since the last open: a refusal with none means the open did + // not unlock the file, and a second open will not either. + let bytesSinceOpen = 0; + const openPage = async (): Promise<void> => { + if (!opts.openPage || signal.aborted) return; + pageOpens++; + bytesSinceOpen = 0; + const r = await opts.openPage({ pageUrl: opts.pageUrl, cdnHost: stored.host, signal, onLog }); + if (!r.ok) onLog(`The page open did not show the player served (${r.error ?? "no media request"}); reading anyway.\n`); + }; + + // ---- 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, + pageOpens, + }); + + // 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`, + ); + + await openPage(); + + // ---- 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(() => {}); + // The unlock may have lapsed: open the page again and ask once more — + // unless nothing was read since the last open. + if (opts.openPage && bytesSinceOpen > 0 && !signal.aborted) { + onLog( + `HTTP Error ${res.status} at ${offset} bytes after ${bytesSinceOpen} served since the page was opened; ` + + `opening it again.\n`, + ); + await openPage(); + continue; + } + 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; + bytesSinceOpen += 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"); +} diff --git a/common/ytdlp/storedUrlManaged.test.ts b/common/ytdlp/storedUrlManaged.test.ts @@ -0,0 +1,310 @@ +// downloadOneManaged with a stored media URL (release 32 R7): `only`, +// `fallback` after a rate-limited prefetch or download, no stored URL, the gap +// between two files, a mid-file 429, and the corrupt-full-source refetch. A +// fake yt-dlp (a shell script) and a fake CDN on loopback; real ffmpeg for the +// probes and extraction (skipped without it). No real network. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs"; +import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { askedPlatform, storedUrlAttemptOf } from "../lib/downloadOutcome"; +import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap"; +import { storedUrlGapKey } from "../lib/storedMediaUrl"; +import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged"; + +const FF = hasFfmpeg(); +const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; +const FILE_PATH = `/v6/streams/${CLAIM}/a1b2c3.mp4`; +const PAGE = `https://odysee.com/synthetic-stream:${CLAIM}`; +const FAST = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 }; + +type Fixture = { + root: string; + channelsDir: string; + channelDir: string; + videoDir: string; + ytdlpLog: string; + paths: Paths; + cdn: FakeRangedCdn; + clean: Buffer; +}; + +// A fake yt-dlp: logs its argv; `prefetch` / `download` say how each pass ends. +async function fixture(opts: { + prefetch?: "ok" | "429"; + download?: "ok" | "429"; + formats?: unknown[]; + cdn?: Parameters<typeof startFakeRangedCdn>[0]; +} = {}): Promise<Fixture> { + const root = await mkdtemp(path.join(os.tmpdir(), "stored-managed-")); + const channelsDir = path.join(root, "channels"); + const channelDir = path.join(channelsDir, "c"); + const videoDir = path.join(channelDir, "data", CLAIM); + await mkdir(videoDir, { recursive: true }); + const clean = FF ? await readFile(makeToneFile(path.join(root, "src.mp4"), { duration: 60, faststart: true })) : Buffer.alloc(1); + const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean }, ...(opts.cdn ?? {}) }); + await writeFile( + path.join(videoDir, "metadata.info.json"), + JSON.stringify({ + id: CLAIM, + extractor: "lbry", + extractor_key: "LBRY", + title: "A synthetic stream", + webpage_url: PAGE, + duration: 60, + formats: opts.formats ?? [{ url: cdn.url(FILE_PATH), protocol: "https", ext: "mp4" }], + }), + ); + const ytdlpLog = path.join(root, "ytdlp.log"); + const bin = path.join(root, "fake-ytdlp.sh"); + const line429 = `echo "WARNING: [lbry] ${CLAIM}: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; echo "ERROR: [lbry] ${CLAIM}: No video formats found!" >&2; exit 1`; + await writeFile( + bin, + `#!/bin/sh\necho "$@" >> ${JSON.stringify(ytdlpLog)}\n` + + `case "$*" in *--skip-download*) ${opts.prefetch === "429" ? line429 : "exit 0"} ;; esac\n` + + `${opts.download === "429" ? line429 : "exit 0"}\n`, + ); + await chmod(bin, 0o755); + const paths = { channelsDir, ytdlpBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; + return { root, channelsDir, channelDir, videoDir, ytdlpLog, paths, cdn, clean }; +} + +async function ytdlpCalls(f: Fixture): Promise<string[]> { + return (await readFile(f.ytdlpLog, "utf8").catch(() => "")).split("\n").filter(Boolean); +} + +function run(f: Fixture, over: Partial<ManagedDownloadOpts> = {}, log: { s: string } = { s: "" }) { + return downloadOneManaged({ + channelSlug: "c", + channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth:1", audioFormat: "mp3" } as ChannelConfig, + paths: f.paths, + videoUrl: PAGE, + onLog: (s) => (log.s += s), + signal: new AbortController().signal, + storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, openPage: null }, + ...over, + }); +} + +async function done(f: Fixture) { + clearPlatformGaps(); + await f.cdn.close(); + await rm(f.root, { recursive: true, force: true }); +} + +async function readOutcome(dir: string): Promise<DownloadOutcomeRecord> { + return JSON.parse(await readFile(path.join(dir, "download-outcome.json"), "utf8")); +} + +test("only: the whole file from the stored URL — no yt-dlp, the audio check, the archive line, the sidecar", { skip: !FF }, async () => { + const f = await fixture(); + try { + const log = { s: "" }; + const record = await run(f, { storedUrl: "only" }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.deepEqual(await ytdlpCalls(f), [], "yt-dlp was never run"); + assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"]); + const st = storedUrlAttemptOf(record); + assert.equal(st?.why, "only"); + assert.equal(st?.host, "player.odycdn.com"); + assert.equal(st?.bytes, f.clean.length); + assert.equal(record.attempts[0].audioCheck?.finalProbeVerdict, "clean"); + assert.equal(askedPlatform(record), false); + assert.match(log.s, /from the stored media URL \(player\.odycdn\.com\) \(asked: only\)/); + assert.equal((await readOutcome(f.videoDir)).status, "ok-audio-checked"); + assert.equal(await readFile(path.join(f.channelDir, "archive"), "utf8"), `lbry ${CLAIM}\n`); + const entries = await readdir(f.videoDir); + assert.ok(entries.includes("audio.mp3")); + assert.ok(!entries.includes("audio.mp4"), "the container is not kept"); + } finally { + await done(f); + } +}); + +test("the channel's storedUrlDownloads is the default; a request's storedUrl overrides it", { skip: !FF }, async () => { + const f = await fixture(); + try { + const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "only" } as ChannelConfig; + const a = await run(f, { channelConfig: cfg }); + assert.equal(storedUrlAttemptOf(a)?.why, "only"); + assert.deepEqual(await ytdlpCalls(f), []); + const b = await run(f, { channelConfig: cfg, storedUrl: "never" }); + assert.ok((await ytdlpCalls(f)).length > 0, "never: the page, as always"); + assert.equal(storedUrlAttemptOf(b), null); + } finally { + await done(f); + } +}); + +test("fallback: a rate-limited prefetch goes to the stored URL; the record says why", { skip: !FF }, async () => { + const f = await fixture({ prefetch: "429" }); + try { + const log = { s: "" }; + const record = await run(f, { storedUrl: "fallback" }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.deepEqual(record.attempts.map((a) => a.kind), ["metadata-prefetch", "stored-url-ranged"]); + assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited"); + assert.equal(askedPlatform(record), true); + assert.equal((await ytdlpCalls(f)).length, 1, "only the prefetch asked the platform"); + assert.match(log.s, /odysee lookup rate-limited/); + // The metadata the prefetch could not refresh is the one the URL came from. + const info = JSON.parse(await readFile(path.join(f.videoDir, "metadata.info.json"), "utf8")); + assert.equal(info.id, CLAIM); + } finally { + await done(f); + } +}); + +test("fallback: a download yt-dlp got 429 on goes to the stored URL (the audio check off: it stays off)", { skip: !FF }, async () => { + const f = await fixture({ download: "429" }); + try { + const cfg = { + handling: "transcribe", + url: "https://odysee.com/@synth:1", + audioCheck: { enabled: false }, + } as ChannelConfig; + const record = await run(f, { channelConfig: cfg, storedUrl: "fallback" }); + assert.equal(record.status, "ok"); + assert.deepEqual(record.attempts.map((a) => a.kind), ["metadata-prefetch", "primary", "stored-url-ranged"]); + assert.equal(record.attempts.at(-1)?.audioCheck, undefined); + assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited"); + } finally { + await done(f); + } +}); + +test("fallback with no rate limit: the page download stands, the stored URL is never read", async () => { + const f = await fixture(); + try { + const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", audioCheck: { enabled: false } } as ChannelConfig; + const record = await run(f, { channelConfig: cfg, storedUrl: "fallback" }); + assert.equal(storedUrlAttemptOf(record), null); + assert.equal(f.cdn.requests.length, 0); + } finally { + await done(f); + } +}); + +test("only, and the record stores no trusted media URL: a per-video failure, nothing asked", async () => { + const f = await fixture({ + formats: [ + { url: "https://player.odycdn.com/a.mp4", protocol: "https" }, + { url: "https://player.odycdn.com/b.mp4", protocol: "https" }, + ], + }); + try { + const log = { s: "" }; + const record = await run(f, { storedUrl: "only" }, log); + assert.equal(record.status, "failed"); + assert.equal(record.failureClass, "per_video"); + assert.deepEqual(record.attempts.map((a) => a.kind), ["stored-url-ranged"]); + assert.equal(askedPlatform(record), false); + assert.deepEqual(await ytdlpCalls(f), []); + assert.equal(f.cdn.requests.length, 0); + assert.match(log.s, /Nothing was requested/); + } finally { + await done(f); + } +}); + +test("a 429 from the CDN mid-file: failed, rate_limit, the partial kept for the next run", { skip: !FF }, async () => { + const f = await fixture({ cdn: { refuseAfterBytes: 40 * 1024 } }); + try { + const record = await run(f, { storedUrl: "only" }); + assert.equal(record.status, "failed"); + assert.equal(record.failureClass, "rate_limit"); + assert.equal(storedUrlAttemptOf(record)?.httpStatus, 429); + const entries = await readdir(f.videoDir); + assert.ok(entries.includes("audio.mp4.stored.part")); + // After the rest, the next run resumes and finishes. + f.cdn.allowAgain(); + const again = await run(f, { storedUrl: "only" }); + assert.equal(again.status, "ok-audio-checked"); + assert.ok((storedUrlAttemptOf(again)?.resumedFrom ?? 0) > 0); + } finally { + await done(f); + } +}); + +test("one new file per rest: the second stored-URL download on a platform waits out the gap", { skip: !FF }, async () => { + const f = await fixture(); + try { + const waits: number[] = []; + const sleep = async (ms: number) => { + waits.push(ms); + clearPlatformGaps(); + }; + const deps = { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 60_000, sleep, openPage: null }; + const log = { s: "" }; + await run(f, { storedUrl: "only", storedUrlDeps: deps }, log); + assert.deepEqual(waits, [], "the first asks no gap"); + assert.ok(platformGapRemainingMs(storedUrlGapKey("odysee")) > 55_000, "the gap is set when it ends"); + await run(f, { storedUrl: "only", storedUrlDeps: deps }, log); + assert.equal(waits.length, 1); + assert.ok(waits[0] > 55_000 && waits[0] <= 60_000); + assert.match(log.s, /A download from the stored media URL \(odysee\) asks for a gap between videos: waiting \d+s/); + } finally { + await done(f); + } +}); + +test("a corrupt full source refetched from the stored URL: clean, the kept file goes, the history says so", { skip: !FF }, async () => { + const f = await fixture(); + try { + await writeFile(path.join(f.videoDir, "audio.mp4"), "OLD-MALFORMED"); + const previous: DownloadOutcomeRecord = { + videoId: CLAIM, + webpageUrl: PAGE, + status: "corrupt-full-source", + startedAt: "2026-10-15T00:00:00.000Z", + finishedAt: "2026-10-15T01:00:00.000Z", + attempts: [{ n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }], + }; + await writeFile(path.join(f.videoDir, "download-outcome.json"), JSON.stringify(previous)); + const record = await run(f, { + storedUrl: "only", + corruptRefetchDeps: { measure: async () => null }, + }); + assert.equal(record.status, "ok-audio-checked"); + const disk = await readOutcome(f.videoDir); + assert.equal(disk.corruptRefetches?.at(-1)?.result, "clean"); + const entries = await readdir(f.videoDir); + assert.ok(entries.includes("audio.mp3")); + assert.ok(!entries.some((e) => e.endsWith(".corrupt-kept")), "the kept file is gone"); + } finally { + await done(f); + } +}); + +test("the managed download opens the player's page (the injected opener) and records it", { skip: !FF }, async () => { + const f = await fixture({ cdn: { requireUnlock: true } }); + try { + const pages: string[] = []; + const record = await run(f, { + storedUrl: "only", + storedUrlDeps: { + fetch: f.cdn.fetch, + chunkBytes: 16 * 1024, + knobs: FAST, + gapMs: 0, + openPage: async ({ pageUrl }) => { + pages.push(pageUrl); + f.cdn.unlock(); + return { ok: true, mediaStatuses: [206] }; + }, + }, + }); + assert.equal(record.status, "ok-audio-checked"); + assert.deepEqual(pages, [PAGE], "the PAGE url, once"); + assert.equal(storedUrlAttemptOf(record)?.pageOpens, 1); + } finally { + await done(f); + } +}); diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts @@ -0,0 +1,98 @@ +// OPEN THE PLAYER'S PAGE FIRST (release 32 R7, the orchestrator's live finding +// of 2026-10-17): Odysee's CDN serves a stream's original file to a connection +// only AFTER a player has opened that video's page. Cold ranged reads with the +// player's headers got 429 (four windows, 20–40 minutes apart); right after a +// headless Chromium page view of the same video — the odysee.com page, ~10 s, +// play, ~8 s — the player's own requests got 200/206 and the ranged cut landed. +// How long the unlock lasts is unknown. +// +// So a stored-URL download opens the page before its first ranged read, and +// once more on a refusal mid-file before giving up (storedUrlDownload.ts). The +// opener is a named, injected step: tests pass a fake (never a browser), the +// managed download passes `openPlayerPage` for a platform in +// PAGE_OPEN_PLATFORMS. No cookies, a fresh context each time. + +import { importPlaywright } from "../social/playwrightRuntime"; + +export const PAGE_OPEN_PLATFORMS: readonly string[] = ["odysee"]; + +// What the measured open did: let the page load, press play, let it play. +export const PAGE_OPEN_SETTLE_MS = 10_000; +export const PAGE_OPEN_PLAY_MS = 8_000; +export const PAGE_OPEN_GOTO_TIMEOUT_MS = 45_000; + +export type PageOpenResult = { + ok: boolean; + // The statuses of the player's own requests of the platform's CDN, in order. + mediaStatuses: number[]; + error?: string; +}; + +export type PageOpener = (opts: { + pageUrl: string; + // The CDN host whose responses say whether the player was served. + cdnHost: string; + signal: AbortSignal; + onLog: (s: string) => void; +}) => Promise<PageOpenResult>; + +function abortableWait(ms: number, signal: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal.aborted) return resolve(); + const t = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + resolve(); + }; + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + +// The real opener: headless Chromium (the workspace's Playwright), the video's +// page, a click on play, a few seconds of playing. Never throws: a page that +// could not be opened is `ok: false` with the reason, and the caller reads on +// regardless (the CDN may serve it anyway). +export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onLog }) => { + const mediaStatuses: number[] = []; + let browser: { close: () => Promise<void> } | null = null; + try { + const { chromium } = await importPlaywright(); + const b = await chromium.launch({ headless: true }); + browser = b; + const ctx = await b.newContext({}); + const page = await ctx.newPage(); + page.on("response", ((r: { url: () => string; status: () => number }) => { + try { + if (new URL(r.url()).hostname === cdnHost) mediaStatuses.push(r.status()); + } catch { + /* not a URL */ + } + }) as never); + onLog(`Opening the player's page first (${pageUrl}).\n`); + await page.goto(pageUrl, { waitUntil: "domcontentloaded", timeout: PAGE_OPEN_GOTO_TIMEOUT_MS }).catch(() => {}); + await abortableWait(PAGE_OPEN_SETTLE_MS, signal); + if (!signal.aborted) { + await page + .evaluate( + `(() => { const b = document.querySelector(".vjs-big-play-button, [aria-label*='Play']"); if (b) { b.click(); return; } const v = document.querySelector("video"); if (v) { v.muted = true; v.play().catch(() => {}); } })()`, + ) + .catch(() => {}); + await abortableWait(PAGE_OPEN_PLAY_MS, signal); + } + const served = mediaStatuses.some((s) => s === 200 || s === 206); + onLog( + `The player's page was open ${Math.round((PAGE_OPEN_SETTLE_MS + PAGE_OPEN_PLAY_MS) / 1000)}s; ` + + `its media requests answered ${mediaStatuses.length ? mediaStatuses.join(",") : "nothing"}.\n`, + ); + return { ok: served, mediaStatuses, ...(served ? {} : { error: "the player's media requests were not served" }) }; + } catch (err) { + const error = (err as Error).message; + onLog(`Could not open the player's page: ${error}\n`); + return { ok: false, mediaStatuses, error }; + } finally { + await browser?.close().catch(() => {}); + } +}; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -5,6 +5,7 @@ - **The Inbox reads on a phone.** At narrow widths each row wraps: the piece, what and why on top, the count and its action underneath. Before, at about 380 px the rows showed only the count and the button. - **Attach a whole local archive and make playable copies from the channel page.** The Cleanup stage's **Media for the whole channel** has **Attach media from a local archive** (a folder, a .zip or a .7z; only names matching, create records for videos the channel does not hold, replace files already saved) and **Playable copies** (trackers, folder) — what `archilyzer media attach` and `media playable` did for a channel. Each previews first, the run is armed by a preview of the same settings, and the result is said in plain words with the job linked. - **Save a list of videos to the store from the Saved videos page.** **Save these videos** takes one video per line (`channel/video-id` or a video page link), the quality and whether to replace a taller one; **Preview** says what a run would do with each (to download, already saved, no source address, not found) and **Save videos** starts one job per channel and links each — `pnpm ops persist-videos` in the UI. +- **A full Odysee download can read the file the record already stores, the way Odysee's player does.** When Odysee answers yt-dlp with 429, the media URL in the video's `metadata.info.json` (on Odysee's CDN) is read in ranges with the page's Referer and Origin — no yt-dlp, and after opening the video's page in a headless browser for a few seconds, since Odysee's CDN serves a file only once its player has — through the same audio check: probes as it grows, a roll-back on a malformed stretch, the final probe, then the configured audio. A refusal mid-file keeps what came down and the next run picks up from the last clean byte. A channel chooses it on its Configure form (**Stored media URL downloads**: never, fallback — when the page is rate-limited or the platform held — or only), and the video page's download offers it for one video when its record has such a URL; `pnpm ops transcribe-one`, `retry-bucket` and `download-missing` take `"storedUrl"`. Two such downloads on one platform are at least 20 minutes apart (Odysee's CDN allows one new file per rest), and a download this way never counts as Odysee answering cleanly. Needs a restart of the editor. - **A clip window can be cut from the media URL an Odysee record already stores, when Odysee's lookup is rate-limited.** `pnpm ops fetch-windows` takes `"storedUrl"`: `"fallback"` tries the page as before and, when the lookup answers 429, cuts the window from the file the record's `metadata.info.json` names on Odysee's CDN (`*.odycdn.com`) instead; `"only"` goes straight to that file and asks the page nothing. A held or cooling Odysee no longer refuses those windows — only the ones with no stored file are refused or left for a later run. Same queue, same gaps between fetches, the audio check still applies, and the window's provenance says `source: "stored-media-url"` with the host. The default, `"never"`, changes nothing; only Odysee is allowed. Needs a restart of the editor. - **umtool's drafts review is an audition deck: hear the cited moment, then keep it or cut it.** `/projects/<project>/review` shows one card per drafted field still waiting for a verdict: the drafted value large, the cited span of its clip playing (video when a window or saved video holds it, else audio marked "audio only"), and the quote under it lighting word by word as it is spoken. Swipe right, → or `k` keeps it (approves); left, ← or `x` cuts it (rejects — tap a reason chip or write a few words, never required); up, ↑ or `e` edits it on the card (on-screen text, narration, teaser lines and the YouTube title; Enter keeps it as edited); down, ↓ or `s` skips it to the back; space replays the span; `z` undoes the last keep, cut or skip. Tap a word to mark it misheard: the note says so. Every action is also a button (a bar under the thumb on a phone). The next card's media is already loading, and the deck ends with what was cut and skipped. Verdicts are the same `drafts.review.json` as before; **List** (`?view=list`) is the old list, whose reader now plays the span too. No model is needed for any of it. - **Fetch clip wherever a citation is shown in umtool.** When nothing on disk holds a cited span — on the deck, in the list's reader, on an article's evidence panel and its evidence walk — **Fetch clip** asks the editor for those seconds exactly as the MCP's `fetch_clip` does, shows its progress, and plays the window when it lands. A rate limit says the platform is rate-limiting; a window the audio check refused says the source served corrupt audio. The evidence panel plays video first and has **Play span** (from the span's start to its end). diff --git a/editor/app/api/ops/_storedUrl.ts b/editor/app/api/ops/_storedUrl.ts @@ -0,0 +1,17 @@ +import { + isStoredUrlMode, + STORED_URL_MODES, + type StoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { OpsInputError, type OpsBody } from "./_lib"; + +// `storedUrl` on a download body (release 32 R7): "never" | "fallback" | +// "only", checked at the door. Absent = the channel's `storedUrlDownloads`. +export function optStoredUrlMode(body: OpsBody, key = "storedUrl"): StoredUrlMode | undefined { + const v = body[key]; + if (v === undefined || v === null) return undefined; + if (!isStoredUrlMode(v)) { + throw new OpsInputError(`"${key}" must be one of ${STORED_URL_MODES.map((m) => `"${m}"`).join(", ")}`); + } + return v; +} diff --git a/editor/app/api/ops/download-missing/route.ts b/editor/app/api/ops/download-missing/route.ts @@ -1,13 +1,17 @@ import { downloadMissingAction } from "../../../channels/[slug]/pipelineActions"; import { jobResponse, ops, optBool, optString, reqSlug } from "../_lib"; +import { optStoredUrlMode } from "../_storedUrl"; export const dynamic = "force-dynamic"; -// POST { slug, queueKey?, ignoreArchive?, abortOnError? } -> { ok: true, jobId } +// POST { slug, queueKey?, ignoreArchive?, abortOnError?, storedUrl? } -> { ok: true, jobId } +// "storedUrl" (release 32 R7): "never" | "fallback" | "only" for every download +// in the run (absent = the channel's `storedUrlDownloads`); with one, a held +// platform's run goes ahead as "only". export async function POST(request: Request) { return ops( request, - ["slug", "queueKey", "ignoreArchive", "abortOnError"], + ["slug", "queueKey", "ignoreArchive", "abortOnError", "storedUrl"], async (body) => jobResponse( await downloadMissingAction( @@ -15,6 +19,12 @@ export async function POST(request: Request) { optString(body, "queueKey"), optBool(body, "ignoreArchive"), optBool(body, "abortOnError"), + undefined, + undefined, + undefined, + undefined, + undefined, + optStoredUrlMode(body), ), ), ); diff --git a/editor/app/api/ops/retry-bucket/route.test.ts b/editor/app/api/ops/retry-bucket/route.test.ts @@ -43,3 +43,22 @@ test("retry-bucket and transcribe-bucket ids must be in the bucket: a stray is r assert.equal(empty.status, 400); assert.deepEqual(await corpus.listJobIds(), []); }); + +// Release 32 R7: "storedUrl" is checked at the door on all three download routes. +test("storedUrl must be never|fallback|only on retry-bucket, download-missing and transcribe-one; nothing runs", async () => { + const dm = (await import("../download-missing/route")).POST; + const t1 = (await import("../transcribe-one/route")).POST; + const a = await callPost(retry, { slug: SLUG, bucket: "downloadedNoTranscript", storedUrl: "always" }); + assert.equal(a.status, 400); + assert.match(String(a.body.error), /"storedUrl" must be one of "never", "fallback", "only"/); + const b = await callPost(dm, { slug: SLUG, storedUrl: true }); + assert.equal(b.status, 400); + assert.match(String(b.body.error), /"storedUrl" must be one of/); + const c = await callPost(t1, { slug: SLUG, id: "in-bucket-1", storedUrl: "sometimes" }); + assert.equal(c.status, 400); + // With "file" nothing is downloaded, so a stored-URL mode is refused too. + const d = await callPost(t1, { slug: SLUG, id: "in-bucket-1", file: "audio.mp3", storedUrl: "only" }); + assert.equal(d.status, 400); + assert.match(String(d.body.error), /"storedUrl" is for a download/); + assert.deepEqual(await corpus.listJobIds(), []); +}); diff --git a/editor/app/api/ops/retry-bucket/route.ts b/editor/app/api/ops/retry-bucket/route.ts @@ -12,11 +12,17 @@ import { reqSlug, reqString, } from "../_lib"; +import { optStoredUrlMode } from "../_storedUrl"; export const dynamic = "force-dynamic"; // POST { slug, bucket, ids?, queueKey?, abortOnError?, handlingOverride?, -// forceCookies?, replaceAutoSubs? } -> { ok: true, jobId } +// forceCookies?, replaceAutoSubs?, storedUrl? } -> { ok: true, jobId } +// +// "storedUrl" (release 32 R7): "never" | "fallback" | "only" — each download +// reads the media URL its record stores, the way the platform's player does +// (absent = the channel's `storedUrlDownloads`); with one, a held platform's +// retry goes ahead as "only". // // THE BUCKET IS RESOLVED FROM THE SNAPSHOT HERE, and that is not new logic: the // bucket controls in the UI pass `snapshot.buckets[key]` to the same action, and @@ -41,10 +47,12 @@ export async function POST(request: Request) { "handlingOverride", "forceCookies", "replaceAutoSubs", + "storedUrl", ], async (body) => { const slug = reqSlug(body, "slug"); const bucket = reqString(body, "bucket"); + const storedUrl = optStoredUrlMode(body); const snapshot = await readChannelSnapshot(getPaths(), slug); if (!snapshot) { throw new OpsInputError( @@ -78,6 +86,7 @@ export async function POST(request: Request) { !subset && isReplayBucket(bucket) ? bucket : undefined, optBool(body, "forceCookies"), optBool(body, "replaceAutoSubs"), + storedUrl, ), ); }, diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts @@ -3,6 +3,7 @@ import { whisperVideoAction, } from "../../../channels/[slug]/videos/[id]/videoActions"; import { jobResponse, ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib"; +import { optStoredUrlMode } from "../_storedUrl"; export const dynamic = "force-dynamic"; @@ -21,12 +22,20 @@ export const dynamic = "force-dynamic"; // and transcribes what decodes, its gaps recorded (transcribeOne's salvage); // false forbids it; absent, a corrupt-full-source video is salvaged and any // other is not. +// "storedUrl" (release 32 R7): "never" | "fallback" | "only" — with no audio on +// disk, the download reads the media URL the record stores, the way the +// platform's player does (the managed path: the audio check, the outcome +// sidecar). Absent = the channel's `storedUrlDownloads`. Not with "file". export async function POST(request: Request) { - return ops(request, ["slug", "id", "file", "salvage"], async (body) => { + return ops(request, ["slug", "id", "file", "salvage", "storedUrl"], async (body) => { const slug = reqSlug(body, "slug"); const id = reqVideoId(body, "id"); const file = optString(body, "file"); const salvage = optBool(body, "salvage"); + const storedUrl = optStoredUrlMode(body); + if (storedUrl !== undefined && file !== undefined) { + return opsFail(`"storedUrl" is for a download; with "file" nothing is downloaded`); + } // One path segment, checked at the door as reqVideoId checks an id: the // name is joined under the video's directory. if (file !== undefined && (file === "" || /[/\\\0]/.test(file) || file.startsWith("."))) { @@ -35,7 +44,7 @@ export async function POST(request: Request) { return jobResponse( file !== undefined ? await transcribeOneAction(slug, id, file, undefined, salvage) - : await whisperVideoAction(slug, id, undefined, salvage), + : await whisperVideoAction(slug, id, undefined, salvage, storedUrl), ); }); } diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -73,6 +73,10 @@ import { import type { JobSpec, ReplayBucket } from "yt-dlp-transcript-common/jobs/jobSpec"; import { makeTaskTracker } from "yt-dlp-transcript-common/jobs/taskHooks"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; +import { + resolveStoredUrlMode, + type StoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; // Preflight disk-space gate: keep a download job from even starting when free // space is already below the configured floor. Returns an error result to @@ -134,6 +138,10 @@ async function runPipelineAction( // sync only: force the full sweep (whole-listing re-read) regardless of the // configured cadence. Undefined leaves the decision to the cadence gate. forceFullSweep?: boolean; + // download-missing / retry-bucket (release 32 R7): read the record's stored + // media URL (downloadOneManaged's `storedUrl`). Absent = the channel's + // `storedUrlDownloads`. + storedUrl?: StoredUrlMode; // Replay descriptor, forwarded onto the job record so it can be replayed (Retry). spec?: JobSpec; }, @@ -167,13 +175,24 @@ async function runPipelineAction( // clean one lifts the hold (onPlatformClean below). The sentence names the // hold and the next probe. store-playlist stays allowed, as it is under the // downloads pause. + // A HELD PLATFORM WITH A STORED-URL MODE (release 32 R7): a download-missing + // or a retry runs anyway, as `only` — no page request, each video read from + // the media URL its record stores (one new file per rest), a video without + // one failing without asking. The clip-window fetch's door answers the same. + let storedUrlHeld = false; + const storedMode = resolveStoredUrlMode(options?.storedUrl, channelConfig.storedUrlDownloads); if (mode !== "store-playlist") { const held = await heldPlatformRefusal( platform, mode === "sync" ? "Sync" : "This download", paths, ); - if (held) return { ok: false, info: true, error: held }; + if (held) { + const storedOk = + (mode === "download-missing" || mode === "retry-bucket") && storedMode !== "never"; + if (!storedOk) return { ok: false, info: true, error: held }; + storedUrlHeld = true; + } } // A manually clicked Sync RESPECTS the per-platform rate-limit cooldown: if // auto-download (or a prior sync) hit a 429, refuse rather than re-storm the @@ -257,6 +276,11 @@ async function runPipelineAction( keepSourceVideoOverride: options?.keepSourceVideoOverride, extractImmediately: options?.extractImmediately, audioFormatOverride: options?.audioFormatOverride, + ...(storedUrlHeld + ? { storedUrl: "only" as const, storedUrlHeld: true } + : options?.storedUrl + ? { storedUrl: options.storedUrl } + : {}), setProgress, progressBaseline, // On a 429/network failure, record the shared per-platform cooldown so @@ -325,6 +349,8 @@ export async function downloadMissingAction( keepSourceVideoOverride?: boolean, extractImmediately?: boolean, audioFormatOverride?: AudioFormat, + // Release 32 R7: the stored-media-URL mode for every download in the run. + storedUrl?: StoredUrlMode, ): Promise<StreamActionResult> { return runPipelineAction( slug, @@ -339,6 +365,7 @@ export async function downloadMissingAction( keepSourceVideoOverride, extractImmediately, audioFormatOverride, + storedUrl, spec: { kind: "download-missing", slug, @@ -351,6 +378,7 @@ export async function downloadMissingAction( keepSourceVideoOverride, extractImmediately, audioFormatOverride, + ...(storedUrl ? { storedUrl } : {}), }, }, }, @@ -468,6 +496,8 @@ export async function retryBucketAction( // Always paired with handlingOverride "transcribe" (a youtube-handling run // would re-fetch subs instead of audio). replaceAutoSubs?: boolean, + // Release 32 R7: the stored-media-URL mode for every download in the run. + storedUrl?: StoredUrlMode, ): Promise<StreamActionResult> { if (!Array.isArray(bucketIds) || bucketIds.length === 0) { return { ok: false, error: "No video IDs supplied for retry." }; @@ -493,6 +523,7 @@ export async function retryBucketAction( handlingOverride, forceCookies, replaceAutoSubs, + ...(storedUrl ? { storedUrl } : {}), }, } : undefined; @@ -507,6 +538,7 @@ export async function retryBucketAction( abortOnError, forceCookies, replaceAutoSubs, + storedUrl, spec, }, ); diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -13,6 +13,7 @@ import type { ChannelHandling, } from "yt-dlp-transcript-common/lib/channelConfig"; import type { DownloadOutcomeRecord } from "yt-dlp-transcript-common/lib/downloadOutcome"; +import type { StoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import type { TranscriptSalvage } from "yt-dlp-transcript-common/lib/transcribeOutcome"; import { SalvagedTranscriptNotice } from "./SalvagedTranscriptNotice"; import type { SavedVideoPointer } from "yt-dlp-transcript-common/lib/savedVideo"; @@ -79,6 +80,11 @@ type Props = { // This video's saved-video pointer when its source container is persisted to // the store, else null. Drives the Source-video persistence card (Phase 5). savedVideo?: SavedVideoPointer | null; + // The CDN host of the media URL the record stores, when the allowlist + // trusts it (release 32 R7), and the channel's `storedUrlDownloads`: the + // re-download offers the stored URL. + storedMediaHost?: string | null; + channelStoredUrl?: StoredUrlMode; // The effective source-video quality for this channel (channel over global, // resolveSourceVideoQuality): where the persist control's select starts. sourceVideoQuality?: SourceVideoQuality; @@ -126,6 +132,8 @@ export function VideoPanel({ position, vttProvenance = {}, umtoolUrl = null, + storedMediaHost = null, + channelStoredUrl, }: Props) { const audioFiles = files.filter((f) => isAudioFile(f.name)); const transcodeSources = files.filter((f) => isTranscodeSource(f.name)); @@ -274,6 +282,8 @@ export function VideoPanel({ defaultQueueKey={defaultQueueKey} existingQueues={existingQueues} noAudio={noAudio} + storedMediaHost={storedMediaHost} + channelStoredUrl={channelStoredUrl} /> </PipelineStageCard> diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/RedownloadSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/RedownloadSection.tsx @@ -7,6 +7,7 @@ import { DOWNLOAD_FORMAT_LABELS, DOWNLOAD_FORMAT_PRESETS, } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; +import type { StoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { QueueControl } from "../../../../../../components/QueueControl"; import { cancelJobAction } from "../../../../../../jobs/actions"; import { @@ -23,6 +24,8 @@ export function RedownloadSection({ defaultQueueKey, existingQueues, noAudio, + storedMediaHost = null, + channelStoredUrl, }: { slug: string; videoId: string; @@ -30,11 +33,19 @@ export function RedownloadSection({ defaultQueueKey: string; existingQueues: string[]; noAudio: boolean; + // Release 32 R7: the stored media URL's host (null: the record stores none + // the allowlist trusts) and the channel's `storedUrlDownloads`. + storedMediaHost?: string | null; + channelStoredUrl?: StoredUrlMode; }) { const [mode, setMode] = useState<DownloadMode>("pipeline"); const [queueKey, setQueueKey] = useState(defaultQueueKey); // "" = inherit the channel/global default; otherwise a DownloadFormatPreset. const [downloadFormat, setDownloadFormat] = useState(""); + // "" = inherit the channel's storedUrlDownloads; otherwise a StoredUrlMode. + const [storedUrl, setStoredUrl] = useState<"" | StoredUrlMode>(""); + const offerStored = storedMediaHost !== null && handling === "transcribe"; + const stored = offerStored && storedUrl ? storedUrl : undefined; const desc = (() => { if (mode === "whisper") { @@ -62,13 +73,14 @@ export function RedownloadSection({ : "Running pipeline…"; const actionLabel = `${verb} for ${videoId}`; const trigger = mode === "whisper" - ? () => whisperVideoAction(slug, videoId, queueKey) + ? () => whisperVideoAction(slug, videoId, queueKey, undefined, stored) : () => downloadVideoPipelineAction( slug, videoId, queueKey, downloadFormat || undefined, + stored, ); return ( @@ -104,6 +116,22 @@ export function RedownloadSection({ </select> </label> )} + {offerStored && ( + <label className="flex items-center gap-2 text-sm"> + Stored media URL + <select + value={storedUrl} + onChange={(e) => setStoredUrl(e.target.value as "" | StoredUrlMode)} + aria-label="stored media URL" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="">Inherit (channel: {channelStoredUrl ?? "never"})</option> + <option value="never">Never — the page</option> + <option value="fallback">Fallback — when the page is rate-limited</option> + <option value="only">Only — {storedMediaHost}, no page request</option> + </select> + </label> + )} <StreamActionLog trigger={trigger} cancelAction={cancelJobAction} diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -50,6 +50,7 @@ import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server"; import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails"; import { VideoMediaTools } from "./components/VideoMediaTools"; import { loadAudioIntegrity } from "yt-dlp-transcript-common/lib/audioIntegrity-server"; +import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server"; import { describeIntegrity, integrityMatches, @@ -171,6 +172,9 @@ export default async function VideoDetailPage({ // The audio audit's verdict on this video's held audio (release 31 lane // A's audio-integrity.json; shown since release 32). const audioIntegrity = await loadAudioIntegrity(videoDir); + // The media URL the record stores, when the allowlist trusts it (release + // 32 R7): the re-download offers to read it. + const storedMediaHost = (await storedMediaUrl(videoDir))?.host ?? null; // The windows another tool asked this editor to fetch. One readdir of // data/<id>/clips/ plus a stat per file — and no per-CHANNEL count anywhere, // because that would be a walk of every video dir to draw one number. @@ -231,6 +235,7 @@ export default async function VideoDetailPage({ wayback, audioCopy, audioIntegrity, + storedMediaHost, clipWindows, vttProvenance, coverage, @@ -264,6 +269,7 @@ export default async function VideoDetailPage({ wayback, audioCopy, audioIntegrity, + storedMediaHost, clipWindows, vttProvenance, coverage, @@ -401,6 +407,8 @@ export default async function VideoDetailPage({ provenance: w.provenance, }))} coverage={coverage} + storedMediaHost={storedMediaHost} + channelStoredUrl={config.storedUrlDownloads} /> <TagsPanel view={tagsView} /> diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -115,6 +115,15 @@ import { sourceFetchFailure, } from "yt-dlp-transcript-common/ytdlp/downloadOneManaged"; import { runYtdlp } from "yt-dlp-transcript-common/ytdlp/runYtdlp"; +import { + isStoredUrlMode, + resolveStoredUrlMode, + type StoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { + storedUrlAttemptOf, + type DownloadOutcomeRecord, +} from "yt-dlp-transcript-common/lib/downloadOutcome"; import { runRefreshMetadataJob } from "yt-dlp-transcript-common/controller/refreshVideoMetadataJob"; import { runManagedFunction, @@ -230,6 +239,10 @@ export async function downloadVideoPipelineAction( videoId: string, queueKey?: string, downloadFormat?: string, + // Release 32 R7: read the record's stored media URL ("never" | "fallback" | + // "only"); anything else, or nothing, inherits the channel's + // `storedUrlDownloads`. + storedUrl?: string, ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -264,7 +277,7 @@ export async function downloadVideoPipelineAction( kind: "download", }); try { - await downloadOneManaged({ + const record = await downloadOneManaged({ channelSlug: slug, channelConfig: r.config, paths, @@ -280,7 +293,9 @@ export async function downloadVideoPipelineAction( global: settings.downloadFormat, }), appendArchive: true, + ...(isStoredUrlMode(storedUrl) ? { storedUrl } : {}), }); + await recordStoredUrlBackoff(record, url, paths); safeRevalidate([ `/channels/${slug}/videos/${videoId}`, `/channels/${slug}`, @@ -292,6 +307,27 @@ export async function downloadVideoPipelineAction( }); } +// A single-video download that read the stored media URL (release 32 R7) +// backs the platform off on a refusal — its CDN's, or the page lookup's before +// it — as a batch does. Best-effort. +async function recordStoredUrlBackoff( + record: DownloadOutcomeRecord, + url: string, + paths: Paths, +): Promise<void> { + const st = storedUrlAttemptOf(record); + if (!st) return; + const refused = + record.failureClass === "rate_limit" || + (st.why === "rate-limited" && record.status.startsWith("ok")); + if (!refused) return; + try { + await recordDownloadBackoff(detectPlatform(url) ?? "unknown", paths, "rate_limit"); + } catch { + /* shared-state write is best-effort */ + } +} + // "Refresh metadata": re-read this one video's metadata.info.json from its // source — no subtitles, no media — for a source that changed after the first // fetch (a livestream VOD gaining its processed formats and captions). The job @@ -463,6 +499,12 @@ export async function whisperVideoAction( queueKey?: string, // See transcribeOneAction's `salvage`. salvage?: boolean, + // Release 32 R7: how the audio is downloaded when there is none. Anything + // but "never" (this, else the channel's `storedUrlDownloads`) downloads + // through the managed path with that stored-URL mode — the audio check, the + // outcome sidecar, the corrupt-source refetch — instead of the plain + // one-video download. + storedUrl?: StoredUrlMode, ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -518,17 +560,46 @@ export async function whisperVideoAction( "Could not determine the video URL: no metadata.info.json and the playlist does not contain a matching entry.", ); } - onLog(`No audio on disk for ${videoId}; downloading…`); - await runYtdlp({ - channelSlug: slug, - mode: "download-one-audio", - channelConfig: r.config, - paths, - onLog, - signal, - singleVideoUrl: url, - audioFormatOverride: audioFormat, - }); + const storedMode = resolveStoredUrlMode(storedUrl, r.config.storedUrlDownloads); + if (storedMode !== "never") { + onLog(`No audio on disk for ${videoId}; downloading (stored media URL: ${storedMode})…`); + const settings = getSettings(); + const record = await downloadOneManaged({ + channelSlug: slug, + channelConfig: r.config, + paths, + videoUrl: url, + onLog, + signal, + cookiePolicy: resolveCookiePolicy(settings, r.config), + globalSkipLiveDownloads: settings.skipLiveDownloads, + audioFormatOverride: audioFormat, + appendArchive: true, + storedUrl: storedMode, + }); + await recordStoredUrlBackoff(record, url, paths); + if (!record.status.startsWith("ok")) { + const why = record.attempts.at(-1)?.error?.trim(); + throw new Error( + `The download of ${videoId} ended ${record.status}` + + (record.failureClass ? ` (${record.failureClass})` : "") + + (why ? `: ${why}` : "") + + "; nothing to transcribe.", + ); + } + } else { + onLog(`No audio on disk for ${videoId}; downloading…`); + await runYtdlp({ + channelSlug: slug, + mode: "download-one-audio", + channelConfig: r.config, + paths, + onLog, + signal, + singleVideoUrl: url, + audioFormatOverride: audioFormat, + }); + } } else { onLog(`Audio already on disk for ${videoId}; skipping download.`); } diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -717,6 +717,32 @@ export function ChannelForm({ state={state} defaultOn={AUDIO_CHECK_PLATFORMS.includes(platform || detectPlatform(url) || "")} /> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium"> + Stored media URL downloads{" "} + <span className="text-muted-foreground font-normal"> + (transcribe only, Odysee) + </span> + </span> + <SeededSelect + state={state} + name="storedUrlDownloads" + initial={c?.storedUrlDownloads ?? ""} + aria-label="stored media URL downloads" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="">Never — download from the page</option> + <option value="fallback"> + Fallback — the stored URL when the page is rate-limited or held + </option> + <option value="only">Only — the stored URL, no page request</option> + </SeededSelect> + <span className="text-xs text-muted-foreground"> + Reads the media file the video's metadata already names, in + ranges as the site's player does, through the audio check. One + new file per 20 minutes on the platform. + </span> + </label> </Section> <Section title="Retention & persistence"> <label className="flex flex-col gap-1 text-sm"> diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -49,6 +49,7 @@ export const CHANNEL_FORM_VALUES = [ "fullSweepIntervalMinutes", "cookiesFromBrowser", "cookieMode", + "storedUrlDownloads", "downloadFilterInclude", "downloadFilterExclude", "downloadFilterRejectedLivestreams", @@ -105,6 +106,7 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { putNum(fd, "fullSweepIntervalMinutes", config.fullSweepIntervalMinutes); put(fd, "cookiesFromBrowser", config.cookiesFromBrowser); put(fd, "cookieMode", config.cookieMode); + put(fd, "storedUrlDownloads", config.storedUrlDownloads); put(fd, "downloadFilterInclude", config.downloadFilter?.include); put(fd, "downloadFilterExclude", config.downloadFilter?.exclude); if (config.downloadFilter?.includeLivestreams) { diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -118,3 +118,21 @@ test("the ops patch keeps an Odysee channel's default, and turns it off with aud assert.equal(back.get("audioCheckEnabled"), null, "the opt-out round-trips unticked"); assert.deepEqual(parseChannelForm(back).config.audioCheck, { enabled: false }); }); + +// Stored-media-URL downloads (release 32 R7): the select writes fallback/only, +// blank (Never) writes nothing, and the ops patch round-trips it. +test("the form writes storedUrlDownloads; Never clears it; the ops patch round-trips", () => { + assert.equal(parseChannelForm(form({ storedUrlDownloads: "only" })).config.storedUrlDownloads, "only"); + assert.equal(parseChannelForm(form({ storedUrlDownloads: "fallback" })).config.storedUrlDownloads, "fallback"); + assert.equal("storedUrlDownloads" in parseChannelForm(form({ storedUrlDownloads: "" })).config, false); + assert.equal("storedUrlDownloads" in parseChannelForm(form({ storedUrlDownloads: "sometimes" })).config, false); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("storedUrlDownloads")); + const fd = channelConfigToFormData({ handling: "transcribe", name: "Synth", url: ODYSEE }); + applyChannelFormPatch(fd, { storedUrlDownloads: "fallback" }); + const set = parseChannelForm(fd).config; + assert.equal(set.storedUrlDownloads, "fallback"); + const back = channelConfigToFormData(set); + assert.equal(back.get("storedUrlDownloads"), "fallback"); + applyChannelFormPatch(back, { storedUrlDownloads: "" }); + assert.equal("storedUrlDownloads" in parseChannelForm(back).config, false); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -1,3 +1,4 @@ +import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; import { AUDIO_CHECK_COPY_TIMEOUT_MAX_SECONDS, @@ -60,6 +61,7 @@ export const CHANNEL_FORM_FIELDS = [ "cookiesFromBrowser", "cookieMode", "audioCheck", + "storedUrlDownloads", "downloadFilter", "recordedDate", "mirror", @@ -221,6 +223,11 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { const cookiesFromBrowser = stringOrUndef(formData, "cookiesFromBrowser"); const cookieModeRaw = String(formData.get("cookieMode") ?? "").trim(); const cookieMode = isCookieMode(cookieModeRaw) ? cookieModeRaw : undefined; + // Stored-media-URL downloads (release 32 R7). Blank = never, the default: + // omitted, so choosing it clears a stored mode. + const storedUrlRaw = String(formData.get("storedUrlDownloads") ?? "").trim(); + const storedUrlDownloads = + isStoredUrlMode(storedUrlRaw) && storedUrlRaw !== "never" ? storedUrlRaw : undefined; // Download filter. Both patterns are regex SOURCES compiled with "i" at // download time, so the form is the place that refuses an unparseable one: @@ -401,6 +408,7 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (cookiesFromBrowser) config.cookiesFromBrowser = cookiesFromBrowser; if (cookieMode) config.cookieMode = cookieMode; if (audioCheck) config.audioCheck = audioCheck; + if (storedUrlDownloads) config.storedUrlDownloads = storedUrlDownloads; if (downloadFilter) config.downloadFilter = downloadFilter; if (recordedDateTitlePattern) { config.recordedDate = { titlePattern: recordedDateTitlePattern }; diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -319,6 +319,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { spec.bucket, Boolean(p.forceCookies), Boolean(p.replaceAutoSubs), + // Release 32 R7: a replay keeps the stored-URL mode it was asked with. + isStoredUrlMode(p.storedUrl) ? p.storedUrl : undefined, ); }, "download-from-playlist": (spec) => { @@ -337,6 +339,7 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { bool(p.keepSourceVideoOverride), bool(p.extractImmediately), str(p.audioFormatOverride) as AudioFormat | undefined, + isStoredUrlMode(p.storedUrl) ? p.storedUrl : undefined, ); }, sync: (spec) => { diff --git a/editor/e2e/stored-url-downloads.spec.ts b/editor/e2e/stored-url-downloads.spec.ts @@ -0,0 +1,98 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { test, expect } from "@playwright/test"; +import { baseUrl } from "./baseUrl"; +import { + channelStage, + generateReport, + readJson, + resetData, + resolvePath, + testPaths, +} from "./helpers"; + +// Release 32 R7: a full download may read the media URL the record stores, the +// way the platform's player does. The UI-without-AI rule: the per-channel +// setting is on the Configure form, and the video page's re-download offers it +// when the record has a stored URL the allowlist trusts. Nothing here starts a +// download — the stored URL's host is a real CDN and no test asks it anything +// (the download itself is covered by common's unit tests against a fake CDN). + +const CHANNEL = "test-transcribe"; +const FIXTURE = "one-transcribe-channel"; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; +const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; + +async function invalidate() { + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); +} + +test("configure: the stored media URL setting saves fallback/only and Never clears it", async ({ page }) => { + await resetData(FIXTURE); + await generateReport(page, CHANNEL); + await page.goto(channelStage(CHANNEL, "configure")); + const select = page.getByLabel("stored media URL downloads"); + await expect(select).toHaveValue(""); + await select.selectOption("only"); + await page.getByRole("button", { name: /save changes/i }).click(); + await expect + .poll(async () => (await readJson<{ storedUrlDownloads?: string }>(`${ROOT}/config.json`)).storedUrlDownloads) + .toBe("only"); + + await page.reload(); + await expect(page.getByLabel("stored media URL downloads")).toHaveValue("only"); + await page.getByLabel("stored media URL downloads").selectOption(""); + await page.getByRole("button", { name: /save changes/i }).click(); + await expect + .poll(async () => "storedUrlDownloads" in (await readJson<Record<string, unknown>>(`${ROOT}/config.json`))) + .toBe(false); +}); + +test("video page: the re-download offers the stored media URL when the record has one", async ({ page }) => { + await resetData(FIXTURE); + const dir = resolvePath(`${ROOT}/data/${CLAIM}`); + await mkdir(dir, { recursive: true }); + await writeFile( + `${dir}/metadata.info.json`, + JSON.stringify({ + id: CLAIM, + extractor: "lbry", + title: "A synthetic stream", + webpage_url: `https://odysee.com/synthetic-stream:${CLAIM}`, + duration: 60, + formats: [ + { url: `https://player.odycdn.com/v6/streams/${CLAIM}/a1b2c3.mp4`, protocol: "https", ext: "mp4" }, + ], + }), + ); + await invalidate(); + await page.goto(`/channels/${CHANNEL}/videos/${CLAIM}`); + const select = page.getByLabel("stored media URL", { exact: true }); + await expect(select).toBeVisible(); + await expect(select).toHaveValue(""); + await expect(select.locator("option")).toHaveText([ + "Inherit (channel: never)", + "Never — the page", + "Fallback — when the page is rate-limited", + "Only — player.odycdn.com, no page request", + ]); + await select.selectOption("only"); + await expect(select).toHaveValue("only"); + // Both download modes carry it. + await page.getByLabel("download mode").selectOption("whisper"); + await expect(page.getByLabel("stored media URL", { exact: true })).toHaveValue("only"); + await expect(page.getByRole("button", { name: "Audio + Whisper" })).toBeEnabled(); + + // A record whose stored URL the allowlist does not trust: no offer. + await writeFile( + `${dir}/metadata.info.json`, + JSON.stringify({ + id: CLAIM, + webpage_url: `https://odysee.com/synthetic-stream:${CLAIM}`, + formats: [{ url: "https://cdn.example/a.mp4", protocol: "https" }], + }), + ); + await invalidate(); + await page.reload(); + await expect(page.getByLabel("download mode")).toBeVisible(); + await expect(page.getByLabel("stored media URL", { exact: true })).toHaveCount(0); +}); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10117,3 +10117,75 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri repeats once, a bad line refuses the whole list with its line number) → `persistVideosAction` exactly as the ops route calls it. +## Release 32 lane R7: a full download from the stored media URL, read the way the player reads it (verified 2026-10-17, branch `r32/odysee-ranged`) + +- **`ytdlp/storedUrlDownload.ts`** `storedUrlDownload({paths, videoDir, stored, channelConfig, audioFormat, audioCheck, + onLog, signal, deps?})`: sequential `Range: bytes=<offset>-<offset+chunk-1>` GETs (`STORED_URL_CHUNK_BYTES` = 8 MiB) + of `stored.url` with `storedMediaHeaders(stored)` (lib/storedMediaUrl.ts: `User-Agent` = `STORED_MEDIA_USER_AGENT`, + which moved there from fetchWindowManaged.ts and is re-exported by it; the pinned `Referer`; its `Origin`; + `Accept: */*`). No cookies, no yt-dlp. 206 + `Content-Range` (the start must equal the offset); 200 = the CDN ignored + the range, read as the whole file from 0; 416 = past the end; **429 and 403 → `rate-limited`** (partial kept); + 404/410/other → `http-error`; a thrown fetch or an empty body → `network`. +- **On disk, in the video dir:** the partial `audio.<ext>.stored.part` (`<ext>` = the URL path's when it is a media + extension, else mp4) and its resume state **`audio.<ext>.stored.part.json`** = `{version: 1, url, totalBytes, + goodBytes, updatedAt}` — `goodBytes` is the last probed-clean byte count (with the audio check off: every byte + written). Both are media-tier SCRATCH (`\.part$`, and the new `\.stored\.part\.json$` rule). A resume truncates the + partial to `goodBytes` when the state's `url` matches; a partial with no state (or another URL's) is deleted. The + finished file is renamed to `audio.<ext>` (the container), the state removed. +- **The audio check over this producer:** `resolveKnobs` (now exported from audioCheckedDownload.ts, taking + `{channelConfig, debugPauseMs?}`) and the AIMD cadence; a probe of the partial between reads once the live interval + has elapsed and it grew past the size gate; clean/partial → `goodBytes` advances (state written); malformed → + truncate to `goodBytes` (`rollback`, or `restart` at 0); more than `maxRollbacks` in a row → `failed-corrupt-source` + (partial kept). New `CheckpointAction` **`skip-not-yet-readable`**: ffmpeg cannot open the container ("Error opening + input" / "moov atom not found" / "Invalid data found") and nothing has probed clean yet — not corruption (an MP4 + whose index is longer than the first reads). Final probe of the whole file; malformed → one re-read from `goodBytes` + (0 when no checkpoint was clean); malformed again → `corrupt-full-source`, the container KEPT. Then + `transcodeAudio` to the channel's format (skipped when the container already is it) and `removeMediaFile` of the + container unless `keepSourceVideo`. +- **`downloadOneManaged({storedUrl?, storedUrlHeld?, storedUrlDeps?})`**: mode = request ?? channel + **`storedUrlDownloads`** (new key, CHANNEL.md) ?? `never` (`resolveStoredUrlMode`). Transcribe handling only; the + stored URL is read with `storedMediaUrl(data/<canonicalId>)` BEFORE the prefetch. `only` → no prefetch, no yt-dlp; + with no trusted stored URL → `failed`, `failureClass: per_video`, one `stored-url-ranged` attempt, nothing requested. + `fallback` → the page as always; a prefetch classified `rate_limit`, or a failed primary/auth retry whose tail + classifies `rate_limit`, goes to the stored URL. Inside the corrupt-source refetch (prepare/settle wrap it as any + download). `audioCheckApplies(config, PAGE url)`. +- **One new file per platform per rest:** `STORED_URL_NEW_FILE_GAP_MS` = 20 min under the platformGap key + **`stored-url:<platform>`** (`storedUrlGapKey`; in memory, process-wide). Waited out (`waitForPlatformGap`) before a + stored-URL download and set at its start and its end. Not shared with the clip cut (`clip-window:<platform>`). + The test seam `storedUrlDeps.gapMs` replaces it (no env knob). +- **THE PLAYER'S PAGE FIRST (the orchestrator's live finding, 2026-10-17):** Odysee's CDN serves a stream's original + file to a connection only AFTER a player has opened that video's page — cold ranged reads with the player's headers + got 429 (four windows, 20–40 min apart); right after a headless Chromium page view (the odysee.com page, ~10 s, + play, ~8 s) the player's requests got 200/206 and the ranged cut landed. How long the unlock lasts is unknown. + `ytdlp/storedUrlPageOpen.ts`: `PageOpener` (`{pageUrl, cdnHost, signal, onLog}` → `{ok, mediaStatuses, error?}`), + the real `openPlayerPage` (Playwright through `social/playwrightRuntime.ts`, headless, a fresh context, no cookies; + `PAGE_OPEN_SETTLE_MS` 10 s, a play click/`video.play()`, `PAGE_OPEN_PLAY_MS` 8 s; never throws), + `PAGE_OPEN_PLATFORMS = ["odysee"]`. `storedUrlDownload` takes `pageUrl` + `openPage` (null = none) and opens before + its first read; a 429/403 that follows bytes served since the last open opens the page again and re-asks the same + range; one straight after an open is `rate-limited` (no loop). The managed download passes the PAGE url and + `openPlayerPage` for PAGE_OPEN_PLATFORMS (`storedUrlDeps.openPage` injects one; tests never launch a browser), inside + the same gap. The attempt records `storedUrl.pageOpens`. Not wired into the clip cut (fetchWindowManaged's ffmpeg + path). +- **The record:** attempt kind **`stored-url-ranged`** (n: 1, `usedCookies: false`, `ytdlpExitCode` 0 = the file came + down whole, else 1) with `storedUrl: {host, why: "rate-limited"|"held"|"only", bytes, totalBytes?, resumedFrom?, + httpStatus?}` and `audioCheck` stats when the check applied. Status `ok-audio-checked` (check on) | `ok` | + `failed-corrupt-source` | `corrupt-full-source` | `failed-short-audio` | `failed`; `failureClass` set by the caller + (`writeOutcome`'s new `failureClass` override): rate_limit (429/403), network (fetch failure, 5xx), per_video (4xx), + unknown (cancel, extraction). The archive line is `<extractor> <id>` from metadata.info.json. Helpers in + lib/downloadOutcome.ts: `storedUrlAttemptOf(record)` (the last attempt's `storedUrl`) and `askedPlatform(record)` + (any attempt that is not `stored-url-ranged`). +- **Never settled clean by a stored-URL success:** `runManagedDownloads` calls `onPlatformBackoff("rate_limit")` for an + `ok*` record whose stored attempt says `rate-limited`, and decrements `requestCounter` for a record that asked the + platform nothing (so a run of `only`/held downloads does not lift a hold). The lane (`autoRunner`): an `ok*` record + with a stored attempt → `{outcome: "transcribed", failureClass: "rate_limit"}` after a rate-limited lookup, else + `viaStoredUrl: true` — `applyUnitOutcome` then retires the video and touches no backoff/hold/pace. The lane still + does not PICK on a held or cooling platform. +- **Editor:** `storedUrl` on the ops bodies of `transcribe-one` (refused with `file`), `retry-bucket` and + `download-missing` (`app/api/ops/_storedUrl.ts` `optStoredUrlMode`), kept in their job specs for Retry. A HELD + platform's `download-missing`/`retry-bucket` with a stored mode (request or channel) runs instead of being refused, + as `storedUrl: "only", storedUrlHeld: true` (`runPipelineAction`). `whisperVideoAction(…, storedUrl?)`: with no audio + and a mode other than never, the download is `downloadOneManaged` (not the raw `download-one-audio` run), a non-`ok*` + record fails the job before transcription; single-video downloads record the platform backoff on a stored + refusal. UI: the Configure form's **Stored media URL downloads** select (`aria-label "stored media URL downloads"`, + Transcription section); the video page's re-download **Stored media URL** select (`aria-label "stored media URL"`) + shown only when the record stores a trusted URL and the channel is transcribe handling. diff --git a/plans/release-32/odysee-ranged.md b/plans/release-32/odysee-ranged.md @@ -0,0 +1,113 @@ +# Release 32 lane R7 — full Odysee downloads read the way the player reads (as shipped) + +Measured (2026-10-16): Odysee answers yt-dlp with 429 — its lookup API and its own fetch of the stored original-file +URL — while the player's ranged GETs of `player.odycdn.com/v6/streams/<claim>/<sd>.mp4` (Referer/Origin odysee.com, a +browser user agent, no cookies) get 206; the CDN allows one new original file after a rest. The clip-window path +already cuts that way (R5); full downloads (transcribe handling, audio) still went through yt-dlp and failed. + +**Found live during the lane (the orchestrator, 2026-10-17):** the CDN serves a stream's original file to a connection +only AFTER a player has opened that video's page. Cold ranged reads with the player's headers got 429 (four windows, +20–40 minutes apart); right after a headless Chromium page view of the same video (the odysee.com page, ~10 s, play, +~8 s) the player's own requests got 200/206 and the ranged cut landed (audio check clean). How long the unlock lasts is +unknown. + +## What + +- **The ranged downloader** (`common/ytdlp/storedUrlDownload.ts`): the WHOLE stored file in sequential 8 MiB Range + requests with the player's headers (`storedMediaHeaders`, `STORED_MEDIA_USER_AGENT` now in lib/storedMediaUrl.ts), + into `audio.<ext>.stored.part` with a resume state `audio.<ext>.stored.part.json` (`{url, totalBytes, goodBytes}`); + resumable from the last probed-clean byte; the abort signal honoured between and during reads; a 429/403 stops + with the partial kept (`rate-limited`). +- **The player's page first** (`common/ytdlp/storedUrlPageOpen.ts`): a named, injected `PageOpener`; the real + `openPlayerPage` is headless Chromium (the workspace's Playwright via `social/playwrightRuntime.ts`, a fresh context, + no cookies) on the video's page for 10 s, a play, 8 s more, never throwing. Odysee only (`PAGE_OPEN_PLATFORMS`). + Opened before the first ranged read of each run, inside the same 20-minute gap; a 429/403 after bytes were served + since the last open opens the page again and re-asks the range; one straight after an open gives up + (`rate-limited`, no loop of opens). The attempt records `pageOpens`. Tests inject a fake opener (the fake CDN's + `requireUnlock` / `unlockBytes` model the lock and its lapse) and never launch a browser. +- **The audio integrity pipeline over it:** the audio check's knobs (`resolveKnobs`, exported) and AIMD cadence, a + probe of the growing partial between reads, a malformed verdict rolling back to the last good byte (a truncate — + this loop is the producer, so no SIGSTOP and no `.good` copy), more than `maxRollbacks` in a row → + failed-corrupt-source; the final probe, one re-read from the last good byte, malformed again → corrupt-full-source + with the file kept; then the configured extraction and the container removed unless `keepSourceVideo`. A partial + ffmpeg cannot open yet, before anything probed clean, is `skip-not-yet-readable` (an MP4 index longer than the + first reads), not corruption. +- **In the managed download** (`downloadOneManaged`): `storedUrl: never | fallback | only` (else the channel's new + `storedUrlDownloads`, else never), transcribe handling, STORED_URL_PLATFORMS only. `only`: no prefetch, no yt-dlp + (no trusted stored URL → a per-video failure, nothing asked). `fallback`: after a rate-limited prefetch, or a + download (primary / auth retry) that ended rate-limited. Outcome sidecar with the new attempt kind + `stored-url-ranged` (`storedUrl: {host, why, bytes, totalBytes?, resumedFrom?, httpStatus?}` + audio-check stats), + the media tier's hook (writeOutcome), the archive line, the short-audio guard, and the corrupt-full-source refetch's + prepare/settle around it exactly as for a yt-dlp download. +- **Paced:** one new stored-URL file per platform per 20 minutes (`STORED_URL_NEW_FILE_GAP_MS`, platformGap key + `stored-url:<platform>`): waited out before, set at the start and the end, so a batch waits rather than 429s. +- **Never a clean settle:** a stored-URL success after a rate-limited lookup backs the platform off (batch and lane); + one that asked the platform nothing (`only`, held) does not count as a request (no clean settle of a manual run) and + the lane retires the video without touching the backoff, hold or pace (`viaStoredUrl`). +- **Editor:** `storedUrl` on `transcribe-one` (not with `file`), `retry-bucket`, `download-missing` (checked at the + door, kept on Retry). A held platform's download-missing / retry with a stored mode runs as `only` (`storedUrlHeld`). + Transcribe (the video page's and `transcribe-one`'s) with a stored mode downloads through the managed path, not the + raw one-video run; a non-ok record fails the job before transcription. +- **UI (the UI-without-AI rule):** the Configure form's **Stored media URL downloads** (never / fallback / only); the + video page's re-download **Stored media URL** select (inherit / never / fallback / only, naming the CDN host), shown + when the record stores a trusted URL, for both download modes. Ops help, COMMANDS.md, CHANNEL.md. + +## Files + +`common/ytdlp/storedUrlDownload.ts` (new), `common/ytdlp/storedUrlPageOpen.ts` (new), `common/ytdlp/downloadOneManaged.ts`, `common/ytdlp/audioCheckedDownload.ts` +(exports), `common/ytdlp/fetchWindowManaged.ts` (the UA constant re-exported), `common/ytdlp/runYtdlp.ts`, +`common/lib/storedMediaUrl.ts`, `common/lib/channelConfig.ts`, `common/lib/channelConfigSchema.ts`, +`common/lib/downloadOutcome.ts`, `common/lib/mediaTier.ts`, `common/jobs/unitOutcome.ts`, +`common/controller/autoRunner.ts`, `common/testing/web/fakeRangedCdn.mjs` (+ `.d.mts`, new), +`common/testing/audio/corruptAudio.mjs` (`faststart`), `editor/app/api/ops/_storedUrl.ts` (new), the +`transcribe-one`, `retry-bucket`, `download-missing` routes, `editor/app/channels/[slug]/pipelineActions.ts`, +`editor/app/channels/[slug]/videos/[id]/videoActions.ts`, `…/[id]/page.tsx`, `…/components/VideoPanel.tsx`, +`…/cards/RedownloadSection.tsx`, `editor/app/channels/components/{ChannelForm.tsx,parseChannelForm.ts,channelConfigToForm.ts}`, +`editor/app/jobs/jobReplayRegistry.ts`, `scripts/archilyzer-ops.mjs`, `COMMANDS.md`, `CHANNEL.md`. +Tests: `common/ytdlp/storedUrlDownload.test.ts` (14), `common/ytdlp/storedUrlManaged.test.ts` (10), +`common/jobs/unitOutcome.test.ts` (+1), `common/ytdlp/managedDownloadsSleep.test.ts` (+2), `common/lib/mediaTier.test.ts` +(+2 rows), `editor/app/api/ops/retry-bucket/route.test.ts` (+1), `editor/app/channels/components/parseChannelForm.test.ts` +(+1), `editor/e2e/stored-url-downloads.spec.ts` (2). + +| Commit | What | +| --- | --- | +| `066702da` | common: the ranged downloader + the audio check over it; `storedUrlDownloads`; `stored-url-ranged`; the fake CDN | +| `e750f34a` | common: the managed download's never/fallback/only, the 20-minute gap, never a clean settle (batch, lane) | +| `9d6d6c6d` | editor: `storedUrl` on the three ops routes and actions, the held door, Transcribe through the managed path; ops help, COMMANDS.md | +| `2689b720` | editor: the Configure field, the video page's option, the e2e spec | +| `01717bf5` | common: the player's page opened first (and again on a refusal after served bytes); the key-count test | +| (this commit) | this record, FACTS, CHANGELOG | + +## Gates + +All through the shared heavy lock, from the worktree root, at `01717bf5`: +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean (0 errors). +- common: 4510 at the branch's start (4507 pass, 2 fail, 1 skipped — that run overlapped my first edits; the two were + this lane's own, the channel-config key count and an undeclared env var, both fixed) → **4537 (4536 pass, 0 fail, + 1 skipped)**. +- editor unit: 331 → **333/333**. +- test:scripts: **1052 (1048 pass + 4 skipped)**, unchanged count (ops help text only). +- mcp: **377/377** (not touched; run once at `2689b720`). +- `docs cli --check`, `docs files --check`, `docs env --check`: clean; `settings example --check` clean at `2689b720` + (no settings change). +- e2e `stored-url-downloads.spec.ts`, foreground: run 1 at `2689b720` 2/2 passed (17.4 s, start-mode build 64 s); run 2 + at `01717bf5` 2/2 passed (11.8 s, rebuild 56 s). + +## Rulings followed + +Opt-in (default never), the allowlist of one platform and its CDN hosts (R5's), one stream with real gaps (one new +file per rest), the audio check keyed on the PAGE url, no model and no live network in any test (a fake CDN on +loopback, a synthetic recording). Records state rulings. + +## Owed + +- The real page opener has never run in a test (by rule); the first live run is its proof. If the unlock turns out + shorter than an 8 MiB read, every chunk would re-open (each open is ~18 s): the log says so. +- The clip cut (fetchWindowManaged's ffmpeg path) does not open the page; `openPlayerPage` is exported for it. + +- The lane does not PICK units on a held or cooling platform even with `storedUrlDownloads: "only"` (the batch door + lets them through; the lane's scheduler is unchanged). +- The clip cut (fetch-windows, `clip-window:<platform>`) and the full download (`stored-url:<platform>`) keep separate + gaps; a cut and a download within 20 minutes of each other are not spaced by this. +- A yt-dlp `audio.<ext>.part` (and `.part.good`) left by a rate-limited audio-checked primary before a `fallback` is + not adopted (its bytes may be of another format); it stays as scratch beside the stored partial. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -954,6 +954,11 @@ export function usage() { ' file with error tolerance and transcribes what decodes, on the', ' recording\'s clock, its gaps recorded (the transcript is listed as', ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false.', + ' "storedUrl": "only" | "fallback" | "never" downloads missing audio from the', + ' media URL the record stores (Odysee\'s CDN), read in ranges as its player', + ' reads it — no page request with "only", the page first with "fallback" —', + ' through the audio check; one new file per platform per 20 min. Absent =', + ' the channel\'s storedUrlDownloads.', "", 'delete-file deletes one file of one video, as its Files list does:', ' {"slug", "id", "file"}. A tiered media file goes with its bytes on the', @@ -991,6 +996,9 @@ export function usage() { ' videos it names are fetched again (recovery from a stale archive);', ' "abortOnError": false carries on past a failure (default: stop at the', ' first that is not one video\'s own). Paced on the platform\'s queue.', + ' "storedUrl": "fallback" | "only" reads each video from the media URL its', + ' record stores when the page is rate-limited (or always), one file per 20', + ' min; with one, a held platform\'s run goes ahead as "only".', "", 'metadata-scan reads every listed video\'s title, date and description', ' into the channel\'s scan file, fetching no media: {"slug"}. Not held by', @@ -1124,6 +1132,8 @@ export function usage() { " with ids is not replayable, as a checkbox selection in the UI is not.", ' "corruptFullSource" downloads again: the kept file is set aside, and comes', " back if the download fails; malformed again, the longer decode stays.", + ' "storedUrl": "fallback" | "only" reads each from the media URL its record', + ' stores, as on download-missing (a held platform\'s retry runs as "only").', ' "corruptHeldAudio" (held audio the audio audit found damaged) is refetched', " the same way, with the audio check on; the new file is audited again.", "",