// LAND ONE FILE AS A VIDEO'S SOURCE — the one landing `import-media` and // `record-live` share (plans/live-capture.md), so a live recording and an // imported file end identically. The rules are lib/mediaImport.ts's header; // this is their I/O: // // 1. ffprobe the file — refused when it cannot be read or holds no audio. // 2. KEEP THE LONGER: over a container already in the store, the new one is // landed only when it is longer (or `replace`); a shorter one is left // where it was found, untouched. // 3. FINALIZE into a staging file beside the store dir, on the store's disk: // attach-media's hashed copy (copyFileHashed; a rename when `move` and the same disk) or a // `-c copy` remux through the heavy slot (preparePlayable.ts // ffmpegRemux). Verified: the bytes for a copy, ffprobe and the length for // a remux. // 4. persistSourceVideo — `source-media.` in the store, the pointer in // data//, `keepReason: "pin"` (never pruned), `origin.requestedBy` the // landing's caller. A replaced container of another name is removed. // 5. `move`: the original is removed only now, after the verify. // 6. audio. (the channel's format, mp3 by default) extracted from the // kept container by transcodeAudio — which runs the media tier's hook — // when there is none, or the one there is shorter than the container. // 7. The channel's `archive` gains the record's line (a record yt-dlp wrote), // so a sync does not download it again; `media-import.json` gains the // entry. // // THE PIPELINE TAKES IT FROM THERE: a video with audio and no transcript is // what the transcription lane draws (held by any pause, never lifted here). // The caller says so in the log (transcriptionHandoffLines). // // GUARDED like attach-media: the store root must exist (an unmounted drive is // never materialised by a mkdir), the store must not be mid-move // (assertSavedVideosStoreWritable), and its disk must have the file's size // plus a margin free. import path from "node:path"; import { appendFile, lstat, mkdir, readFile, readdir, rename, rm, stat } from "node:fs/promises"; import { copyFileHashed } from "../lib/zipReader"; import { execa } from "execa"; import type { AudioFormat, ChannelConfig } from "../lib/channelConfig"; import type { Paths } from "../lib/paths"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; import { removeMediaFile } from "../lib/mediaTier-server"; import { WHISPER_FILENAME } from "../lib/videoStatus"; import { KEEP_LONGER_TOLERANCE_SECONDS, archiveLineFor, chooseKept, finalizeFor, readProbe, type MediaImportEntry, type MediaImportVia, type MediaProbe, } from "../lib/mediaImport"; import { recordMediaImport } from "../lib/mediaImport-server"; import { savedVideoDir, savedVideoPath, savedVideoRoot, type SavedVideoOrigin } from "../lib/savedVideo"; import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { ffmpegRemux } from "./preparePlayable"; import { transcodeAudio } from "./transcode"; import "../lib/childKillGuard"; // Free space the store's disk keeps beyond the file (attach-media's margin). export const LAND_MEDIA_DISK_MARGIN_BYTES = 2 * 1024 ** 3; export type LandMediaDeps = { probe?: (file: string, signal?: AbortSignal) => Promise; remux?: (src: string, dest: string, args: string[], signal?: AbortSignal) => Promise; transcode?: (opts: { videoDir: string; sourcePath: string; sourceFilename: string; fmt: AudioFormat; onLog: (s: string) => void; signal: AbortSignal; }) => Promise; freeBytes?: (dir: string) => Promise; now?: () => Date; }; export type LandMediaOpts = { paths: Paths; slug: string; channelConfig: ChannelConfig; videoId: string; // The file to land (absolute). sourcePath: string; via: MediaImportVia; // Remove the original once the landing verifies. A live recording's staging // file is always moved. move?: boolean; replace?: boolean; // false: the container only, no audio.. audio?: boolean; // The page the file came from, for the provenance. url?: string; // A line for the provenance and the pointer's origin. note?: string; dryRun?: boolean; // A dry run for a record not made yet: no data// to read. recordMayBeMissing?: boolean; onLog: (s: string) => void; signal: AbortSignal; deps?: LandMediaDeps; }; export type LandMediaResult = { dryRun: boolean; kept: "new" | "existing"; newSeconds: number | null; existingSeconds?: number | null; finalized: "copied" | "remuxed"; // The stored container now (absolute), or null on a dry run. container: string | null; audio: MediaImportEntry["audio"]; moved: boolean; lines: string[]; }; export async function probeMedia(paths: Pick, file: string, signal?: AbortSignal): Promise { try { const r = await execa(paths.ffprobeBin, ["-v", "error", "-show_format", "-show_streams", "-of", "json", file], { reject: false, ...(signal ? { cancelSignal: signal } : {}), }); if (r.exitCode !== 0) return null; return readProbe(JSON.parse(String(r.stdout))); } catch { return null; } } async function isDir(p: string): Promise { return stat(p).then((s) => s.isDirectory(), () => false); } // THE STORE'S ROOT, OR WHY NOT. A root that is there is used. The corpus's own // default (`transcripts/saved-videos`) that was never made is made — one // directory, beside the corpus — as the first persist would make it. Anything // else missing is refused: a channel's override root on another drive, or a // relocated store whose link dangles, is an unmounted drive, and a mkdir there // would fill the root filesystem. export async function ensureStoreRoot( paths: Pick, storeRoot: string, what: string, ): Promise { if (await isDir(storeRoot)) return; const present = await lstat(storeRoot).then(() => true, () => false); if (!present && path.resolve(storeRoot) === path.resolve(paths.savedVideosDir) && (await isDir(path.dirname(storeRoot)))) { await mkdir(storeRoot).catch((err: NodeJS.ErrnoException) => { if (err.code !== "EEXIST") throw err; }); return; } throw new Error(`the saved-video store ${storeRoot} is not there (is its drive mounted?) — ${what}`); } function within(child: string, parent: string): boolean { const rel = path.relative(parent, child); return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel); } async function sameDevice(a: string, b: string): Promise { const [x, y] = await Promise.all([stat(a).catch(() => null), stat(b).catch(() => null)]); return x !== null && y !== null && x.dev === y.dev; } async function appendArchiveLine(channelDir: string, line: string, onLog: (s: string) => void): Promise { const file = path.join(channelDir, "archive"); const have = await readFile(file, "utf8").catch(() => ""); const lower = line.toLowerCase(); if (have.split("\n").some((l) => l.trim().toLowerCase() === lower)) return; await appendFile(file, `${line}\n`); onLog(`archive: + ${line}`); } async function readInfo(videoDir: string): Promise | null> { try { const v = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")); return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; } catch { return null; } } // Seconds of the audio file the video holds now, by name: null when none, or // when it cannot be measured. async function heldAudio( videoDir: string, probe: NonNullable, signal: AbortSignal, ): Promise<{ name: string; seconds: number | null } | null> { const entries = await readdir(videoDir).catch(() => [] as string[]); const name = pickPreferredAudio(entries.filter(isRealAudioFile)); if (!name) return null; const p = await probe(path.join(videoDir, name), signal); return { name, seconds: p?.seconds ?? null }; } export async function landMediaFile(opts: LandMediaOpts): Promise { const lines: string[] = []; const say = (s: string) => { lines.push(s); opts.onLog(s.endsWith("\n") ? s : `${s}\n`); }; const probe = opts.deps?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(opts.paths, f, s)); const now = opts.deps?.now ?? (() => new Date()); const channelDir = path.join(opts.paths.channelsDir, opts.slug); const videoDir = path.join(channelDir, "data", opts.videoId); const name = path.basename(opts.sourcePath); const st = await stat(opts.sourcePath).catch(() => null); if (!st?.isFile()) throw new Error(`${opts.sourcePath} is not a file`); if (opts.via === "import-media") { // A file already in the archive is not imported into it. for (const root of [opts.paths.channelsDir, savedVideoRoot(opts.paths, opts.channelConfig)]) { if (within(path.resolve(opts.sourcePath), path.resolve(root))) { throw new Error(`${opts.sourcePath} is inside the archive (${root}); import a file from outside it`); } } } const probed = await probe(opts.sourcePath, opts.signal); if (!probed) throw new Error(`ffprobe cannot read ${opts.sourcePath}: not a media file this can land`); const fin = finalizeFor(name, probed); if ("refused" in fin) throw new Error(fin.refused); if (!(opts.dryRun && opts.recordMayBeMissing) && !(await isDir(videoDir))) { throw new Error(`${opts.slug}/${opts.videoId} has no record (data/${opts.videoId}/)`); } say( `${name}: ${formatBytes(st.size)}, ${probed.formatName}, ${probed.videoCodec ?? "no video"}/${probed.audioCodec}, ` + `${probed.seconds !== null ? `${Math.round(probed.seconds)} s` : "length unknown"} — ${fin.action === "copy" ? "stored" : "remuxed"}: ${fin.reason}`, ); // What the store holds now. const pointer = await loadSavedVideo(videoDir); let existingSeconds: number | null | undefined; if (pointer) { const existingPath = savedVideoPath(pointer); if (await stat(existingPath).then((s) => s.isFile(), () => false)) { existingSeconds = (await probe(existingPath, opts.signal))?.seconds ?? null; } } const kept = chooseKept({ newSeconds: probed.seconds, existingSeconds, ...(opts.replace ? { replace: true } : {}) }); if (existingSeconds !== undefined) { say( `The store holds ${pointer!.file} (${existingSeconds !== null ? `${Math.round(existingSeconds)} s` : "length unknown"}): ` + (kept === "new" ? opts.replace ? "replaced (replace)." : `this one is longer by more than ${KEEP_LONGER_TOLERANCE_SECONDS} s and replaces it.` : "it is as long or longer and stays; this file is not landed."), ); } const fmt: AudioFormat = opts.channelConfig.audioFormat ?? "mp3"; const wantAudio = opts.audio !== false; const audioNow = wantAudio ? await heldAudio(videoDir, probe, opts.signal) : null; const keptSeconds = kept === "new" ? probed.seconds : (existingSeconds ?? null); const extract = wantAudio && (audioNow === null || (kept === "new" && keptSeconds !== null && (audioNow.seconds === null || keptSeconds > audioNow.seconds + KEEP_LONGER_TOLERANCE_SECONDS))); const audio: MediaImportEntry["audio"] = !wantAudio ? "skipped" : extract ? "extracted" : "kept-existing"; say( !wantAudio ? "Audio: not extracted (audio: false)." : extract ? `Audio: audio.${fmt} ${audioNow ? `replaces ${audioNow.name} (${audioNow.seconds !== null ? `${Math.round(audioNow.seconds)} s` : "length unknown"})` : "extracted"} from the stored container.` : `Audio: ${audioNow!.name} stays (${audioNow!.seconds !== null ? `${Math.round(audioNow!.seconds)} s` : "length unknown"}).`, ); const storeRoot = savedVideoRoot(opts.paths, opts.channelConfig); const storeDir = savedVideoDir(opts.paths, opts.channelConfig, opts.slug, opts.videoId); if (opts.move && kept === "existing") say(`Not moved: ${opts.sourcePath} stays where it is (nothing was landed from it).`); if (opts.dryRun) { return { dryRun: true, kept, newSeconds: probed.seconds, ...(existingSeconds !== undefined ? { existingSeconds } : {}), finalized: fin.action === "copy" ? "copied" : "remuxed", container: null, audio, moved: false, lines, }; } let containerPath: string | null = pointer ? savedVideoPath(pointer) : null; let moved = false; if (kept === "new") { await ensureStoreRoot(opts.paths, storeRoot, "nothing landed"); await assertSavedVideosStoreWritable(opts.paths, storeDir); const free = await (opts.deps?.freeBytes ?? getFreeBytes)(storeRoot); if (free < st.size + LAND_MEDIA_DISK_MARGIN_BYTES) { throw new Error( `the store's disk has ${formatBytes(free)} free; ${name} needs ${formatBytes(st.size)} plus ${formatBytes(LAND_MEDIA_DISK_MARGIN_BYTES)}`, ); } const slugDir = path.dirname(storeDir); await mkdir(slugDir, { recursive: true }); const staging = path.join(slugDir, `.${opts.videoId}.land-${process.pid}.part`); await rm(staging, { force: true }); let sha256: string | undefined; try { if (fin.action === "copy") { if (opts.move && (await sameDevice(opts.sourcePath, slugDir))) { await rename(opts.sourcePath, staging); moved = true; say(`Moved ${opts.sourcePath} into the store's staging (same disk).`); } else { // attach-media's copy of a directory entry: bytes counted, sha256'd. const copied = await copyFileHashed(opts.sourcePath, staging, { signal: opts.signal }); if (copied.bytes !== st.size) { throw new Error(`the copy of ${name} is ${copied.bytes} bytes, the file ${st.size}`); } sha256 = copied.sha256; } } else { const remux = opts.deps?.remux ?? ((s: string, d: string, a: string[], sig?: AbortSignal) => ffmpegRemux(opts.paths, s, d, a, sig)); say(`Remuxing (stream copy, the heavy slot) …`); await remux(opts.sourcePath, staging, fin.remuxArgs ?? [], opts.signal); } if (opts.signal.aborted) throw new Error("Cancelled"); const check = await probe(staging, opts.signal); if (!check) throw new Error(`the landed copy of ${name} cannot be read by ffprobe`); if ( probed.seconds !== null && check.seconds !== null && Math.abs(check.seconds - probed.seconds) > Math.max(KEEP_LONGER_TOLERANCE_SECONDS, probed.seconds * 0.005) ) { throw new Error(`the landed copy is ${Math.round(check.seconds)} s, the file ${Math.round(probed.seconds)} s`); } const at = now().toISOString(); // An imported file carries attach-media's provenance (the directory, the // entry, the bytes' sha256 when copied — `kind: "local-archive"`), so the // video page says where it came from the same way; a live recording // names only who made it. const origin: SavedVideoOrigin = { requestedBy: opts.via, requestedAt: at, reason: opts.note ?? (opts.via === "record-live" ? "a live recording" : `imported from ${opts.sourcePath}`), ...(opts.via === "import-media" ? { kind: "local-archive" as const, archive: path.dirname(opts.sourcePath), entry: name, attachedAt: at, ...(sha256 ? { sha256 } : {}), } : {}), }; const landed = await persistSourceVideo({ videoDir, sourceFilename: `source-media.${fin.ext}`, sourcePath: staging, storeDir, keepReason: "pin", origin, ...(sha256 ? { sha256 } : {}), paths: opts.paths, }); containerPath = savedVideoPath(landed); if (pointer && savedVideoPath(pointer) !== containerPath) { await rm(savedVideoPath(pointer), { force: true }); say(`The replaced container ${pointer.file} removed.`); } say(`Stored ${containerPath} (${formatBytes(landed.bytes)}).`); } catch (err) { // A move by rename put the original in staging: put it back. if (moved) await rename(staging, opts.sourcePath).catch(() => {}); await rm(staging, { force: true }).catch(() => {}); throw err; } if (opts.move && !moved) { await rm(opts.sourcePath, { force: true }); moved = true; say(`Removed the original ${opts.sourcePath} (the landed copy verified).`); } } if (extract && containerPath) { const transcode = opts.deps?.transcode ?? ((o: Parameters>[0]) => transcodeAudio({ paths: opts.paths, videoDir: o.videoDir, sourceFilename: o.sourceFilename, sourcePath: o.sourcePath, targetFormat: o.fmt, onLog: o.onLog, signal: o.signal, })); await transcode({ videoDir, sourcePath: containerPath, sourceFilename: path.basename(containerPath), fmt, onLog: opts.onLog, signal: opts.signal, }); // The shorter audio it replaces, when that had another name. if (audioNow && audioNow.name !== `audio.${fmt}`) { await removeMediaFile(videoDir, audioNow.name); say(`Removed the shorter ${audioNow.name}.`); } } const info = await readInfo(videoDir); const line = info ? archiveLineFor(info) : null; if (line) await appendArchiveLine(channelDir, line, (s) => say(s)); const entry: MediaImportEntry = { at: now().toISOString(), via: opts.via, source: { path: opts.sourcePath, name, bytes: st.size, ...(moved ? { moved: true } : {}), ...(opts.url ? { url: opts.url } : {}), }, finalized: fin.action === "copy" ? "copied" : "remuxed", container: { file: containerPath ? path.basename(containerPath) : "", seconds: kept === "new" ? probed.seconds : (existingSeconds ?? null), bytes: containerPath ? ((await stat(containerPath).catch(() => null))?.size ?? 0) : 0, }, kept, ...(existingSeconds !== undefined ? { existingSeconds } : {}), audio, ...(opts.note ? { note: opts.note } : {}), }; await recordMediaImport(videoDir, entry); return { dryRun: false, kept, newSeconds: probed.seconds, ...(existingSeconds !== undefined ? { existingSeconds } : {}), finalized: entry.finalized, container: containerPath, audio, moved, lines, }; } // --- the hand-off to the pipeline --------------------------------------------- export type HandoffFacts = { // The worker pool's live pause (never the stored flag: lib/pauseGates.ts). workersPaused: boolean; // `autoQueue.transcription`: on, held, and whether a rule names the channel. laneEnabled: boolean; laneHeld: boolean; ruleCoversChannel: boolean; // The channel's tier for the transcription lane is "paused". channelPaused: boolean; // This app's transcript (transcript.json) is on disk already. hasTranscript: boolean; // The request asked for a transcribe-one job. transcribeJob: boolean; }; // WHAT HAPPENS TO THE LANDED AUDIO NEXT, in the log's words. Never lifts a // pause or a hold: a job asked for waits behind them, and the lane draws the // video by its own rules when it runs. export function transcriptionHandoffLines(f: HandoffFacts): string[] { if (f.hasTranscript) { return ["Transcription: a transcript is already on disk; nothing is queued for this video."]; } const holds: string[] = []; if (f.workersPaused) holds.push("the transcription workers are paused"); if (f.laneHeld) holds.push("the transcription lane is held"); if (f.channelPaused) holds.push("this channel is paused for transcription"); const behind = holds.length ? ` It waits behind the pause (${holds.join("; ")}); nothing here lifts it.` : ""; if (f.transcribeJob) return [`Transcription: a transcribe-one job is asked for this video.${behind}`]; if (f.laneEnabled && f.ruleCoversChannel) { return [`Transcription: the transcription lane's rules take this channel; it draws this video in its order.${behind}`]; } return [ "Transcription: the transcription lane does not take this channel" + (f.laneEnabled ? " (no rule names it)" : " (the lane is off)") + ` — transcribe it from the video page, or land it with transcribe: true.${behind}`, ]; } // The facts above, read from the running editor's settings and worker pool. export async function readHandoffFacts(opts: { slug: string; channelConfig: ChannelConfig; videoDir: string; transcribeJob: boolean; }): Promise { const { getSettings } = await import("../lib/settings"); const { getWorkerPool } = await import("../jobs/workerPool"); const { flattenLeaves, matchesChannel } = await import("../jobs/autoQueuePolicy"); const { isChannelPaused } = await import("../lib/channelPriority"); const settings = getSettings(); const policy = settings.autoQueue?.transcription; const platform = opts.channelConfig.platform ?? null; let ruleCoversChannel = false; try { ruleCoversChannel = policy?.root ? flattenLeaves(policy.root).some((l) => matchesChannel(l.match, { slug: opts.slug, platform } as never)) : false; } catch { ruleCoversChannel = false; } return { workersPaused: getWorkerPool().isPaused(), laneEnabled: policy?.enabled === true, laneHeld: policy?.held === true, ruleCoversChannel, channelPaused: settings.channelPriority ? isChannelPaused(settings.channelPriority, opts.slug, "transcription") : false, hasTranscript: await stat(path.join(opts.videoDir, WHISPER_FILENAME)).then((s) => s.isFile(), () => false), transcribeJob: opts.transcribeJob, }; }