// 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//.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..stored.part` in the video's dir; // - resumable: `audio..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; // - A DROPPED CONNECTION IS THE SAME FILE, NOT A NEW ONE (release 32 R10, // measured 2026-10-17: a 3.3 GB file's ranged reads ended `fetch failed` at // 344 MB, and again 100 MB into the resume). Within one run a mid-file // network failure — the fetch throwing (ECONNRESET, socket hang up, // ETIMEDOUT), the body ending early, a 2xx with no bytes — and a 429/403 // that follows bytes served since the last page open, are CONTINUATIONS: // the next probe is brought forward (the bytes down so far are judged // now), the resume state saved, a pause (STORED_URL_DROP_PAUSE_MS), the // player's page opened again, and the read goes on from the last clean // byte. At most STORED_URL_MAX_DROPS continuations since the last // progress (the resume point passing its furthest so far); the next one // gives up with the partial kept. A 429 straight after an open still gives // up at once. The caller's new-file rest is not waited out between // continuations (they are inside this one call), and the whole run is one // attempt on the record however many continuations it took; // - 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 { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; 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 { abortableWait, type PageOpener } from "./storedUrlPageOpen"; import { jitterMs } from "../lib/jitter"; // 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; // A CONTINUATION (release 32 R10): the pause before the page is reopened and // the read resumed after a dropped connection (or a refusal after served // bytes), and how many continuations in a row may make no progress before the // run gives up. export const STORED_URL_DROP_PAUSE_MS = 45_000; export const STORED_URL_MAX_DROPS = 6; 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.`). container: string; // How many times the player's page was opened (storedUrlPageOpen.ts). pageOpens: number; // How many times the read went on after a dropped connection or a refusal // that followed served bytes (release 32 R10). continuations: 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; chunkBytes?: number; // Overrides of the audio check's resolved knobs (tests: a 0 ms interval, a // small size gate). knobs?: Partial; now?: () => number; // A continuation's pause (default STORED_URL_DROP_PAUSE_MS) and how it is // waited (default an abortable timer). Tests pass 0. dropPauseMs?: number; sleep?: (ms: number, signal?: AbortSignal) => Promise; // Continuations in a row without progress (default STORED_URL_MAX_DROPS). maxDrops?: 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.` 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 { try { const raw = JSON.parse(await readFile(file, "utf8")) as Partial; 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 { try { return (await stat(file)).size; } catch { return null; } } async function truncateTo(file: string, bytes: number): Promise { 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"; } // undici's "fetch failed" / "terminated" with the socket's reason when it has // one (ECONNRESET, "other side closed", UND_ERR_SOCKET, ETIMEDOUT). function errorText(err: unknown): string { const e = err as Error & { cause?: { code?: string; message?: string } }; const msg = e?.message ?? String(err); const cause = e?.cause; const why = cause ? (cause.code ?? cause.message ?? "") : ""; return why && !msg.includes(why) ? `${msg} (${why})` : msg; } export async function storedUrlDownload( opts: StoredUrlDownloadOpts, ): Promise { 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; // The default pause is stretched by up to pacing.jitter (lib/jitter.mjs); a // pause a caller passes (the tests) is waited exactly. const dropPauseMs = opts.deps?.dropPauseMs !== undefined ? Math.max(0, opts.deps.dropPauseMs) : jitterMs(STORED_URL_DROP_PAUSE_MS); const maxDrops = Math.max(0, opts.deps?.maxDrops ?? STORED_URL_MAX_DROPS); const sleep = opts.deps?.sleep ?? ((ms: number, s?: AbortSignal) => abortableWait(ms, s ?? signal)); 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, storedMediaUserAgent()); 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; let continuations = 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 => { 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 => { 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, continuations, }); // A stop that keeps the partial for a resume: the good bytes recorded. const keepPartial = async ( kind: StoredUrlDownloadKind, extra: { httpStatus?: number; error?: string } = {}, ): Promise => { 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`, ); }; const tooManyRollbacks = (): StoredUrlDownloadResult => { onLog( `More than ${knobs.maxRollbacks} rollbacks in a row: the source keeps serving malformed audio. ` + `The partial is kept at ${goodBytes} bytes.\n`, ); return result("failed-corrupt-source", { error: "the source served malformed audio at every attempt" }); }; // ---- A continuation of the same file (release 32 R10) ---- // A dropped connection, or a refusal after bytes served since the last open: // judge what came down, pause, reopen the page, read on. Null = go on from // `offset`; a result = give up with it. let dropsSinceProgress = 0; // The furthest resume point of this run: a continuation that does not pass // it made no progress. let furthestResume = offset; const continueSameFile = async (cause: { kind: "network" | "rate-limited"; error: string; httpStatus?: number; // What happened, e.g. "Connection dropped at 343932928 bytes". what: string; // The verb of the log line: "reopening the page and resuming". verb: string; }): Promise => { // The next probe brought forward, so the read resumes from a clean byte. // Under the size gate, or before the container can be opened at all, the // bytes stay unjudged (as between any two checkpoints) and the next probe // judges them. if (opts.audioCheck && offset > goodBytes && (await sizeOf(partFile)) !== null) { const c = await checkpoint(); if (signal.aborted) return keepPartial("aborted", { error: "cancelled" }); if (c === "too-many") return tooManyRollbacks(); } if (!opts.audioCheck) goodBytes = offset; if ((await sizeOf(partFile)) !== null) await saveState().catch(() => {}); if (offset > furthestResume) { furthestResume = offset; dropsSinceProgress = 0; } dropsSinceProgress++; const extra = { error: cause.error, ...(cause.httpStatus !== undefined ? { httpStatus: cause.httpStatus } : {}) }; if (dropsSinceProgress > maxDrops) { onLog( `${cause.what} — ${maxDrops} continuation${maxDrops === 1 ? "" : "s"} since the last progress; ` + `giving up with the partial kept at ${offset} bytes: ${cause.error}\n`, ); return keepPartial(cause.kind, extra); } continuations++; onLog( `${cause.what} — ${cause.verb} (${dropsSinceProgress} of ${maxDrops}): ${cause.error}. ` + `Pausing ${Math.round(dropPauseMs / 1000)} s; resuming from ${offset} bytes` + (opts.audioCheck && offset === goodBytes ? " (the last probed-clean byte)" : "") + ".\n", ); await sleep(dropPauseMs, signal); if (signal.aborted) return keepPartial("aborted", { error: "cancelled" }); await openPage(); windowStartAt = now(); windowStartBytes = offset; return null; }; const dropped = (error: string): Promise => continueSameFile({ kind: "network", error, what: `Connection dropped at ${offset} bytes`, verb: opts.openPage ? "reopening the page and resuming" : "resuming", }); 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" }); const stop = await dropped(`the ranged read at ${offset} failed: ${errorText(err)}`); if (stop) return stop; continue; } 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) { const stop = await continueSameFile({ kind: "rate-limited", httpStatus: res.status, error: `HTTP Error ${res.status} from ${stored.host} at ${offset} bytes`, what: `HTTP Error ${res.status} at ${offset} bytes after ${bytesSinceOpen} served since the page was opened`, verb: "opening it again and resuming", }); if (stop) return stop; 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"); // A write that fails (the disk) is not a dropped connection: no retry. let writeError: Error | null = null; let readError: unknown = null; try { if (res.body) { for await (const chunk of res.body as unknown as AsyncIterable) { if (signal.aborted) break; try { await fh.write(chunk); } catch (err) { writeError = err as Error; break; } offset += chunk.byteLength; bytesSinceOpen += chunk.byteLength; progress(); } } } catch (err) { readError = err; } await fh.close().catch(() => {}); if (signal.aborted || (readError !== null && isAbort(readError, signal))) { return keepPartial("aborted", { error: "cancelled" }); } if (writeError) { return keepPartial("network", { error: `writing ${names.part} at ${offset} failed: ${writeError.message}` }); } if (readError !== null) { const stop = await dropped(`the read at ${before} ended early at ${offset}: ${errorText(readError)}`); if (stop) return stop; continue; } if (whole && total === null) total = offset; if (offset === before) { const stop = await dropped(`the CDN sent no bytes at ${offset}`); if (stop) return stop; continue; } 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") return tooManyRollbacks(); 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"); }