// A FILE MADE INTO A NORMAL TRANSCRIBED ITEM — the pure half of the landing // shared by `import-media` and `record-live` (controller/landMedia.ts, // plans/live-capture.md). // // A file from outside — a recording made by hand, an external archive's copy, // a live recording this app made — lands exactly like a persisted source // video: `source-media.` in the saved-video store with a pointer in // `data//saved-video.json`, `audio.` beside the record (the tier hook // after it), and the channel's pipeline takes it from there. What is its own: // // - FINALIZED, NEVER RE-ENCODED. A file ffprobe cannot read is refused. An // MPEG-TS stream (a live recording, a yt-dlp `.part`), an FLV or anything // else not a stored container is remuxed with `-c copy` (mp4 +faststart, // else mkv when mp4 cannot hold its codecs); an mp4/mkv/webm/mov is // copied as it is. // - THE LONGER RECORDING STAYS. Over a container already in the store, the // new one replaces it only when it is longer (KEEP_LONGER_TOLERANCE_SECONDS // of slack, a tie keeps what is there) — unless `replace`. Which was kept, // and both lengths, go in the provenance. // - PROVENANCE: `media-import.json` beside the record, one entry per landing, // newest last: where the file came from, its original name, when, how it // was finalized, what was kept. import path from "node:path"; export const MEDIA_IMPORT_FILENAME = "media-import.json"; // Who landed a file. export type MediaImportVia = "import-media" | "record-live"; // Two recordings of one stream within this many seconds are the same length: // the one in the store stays. export const KEEP_LONGER_TOLERANCE_SECONDS = 2; // How many entries media-import.json keeps (the oldest go first). export const MEDIA_IMPORT_MAX_ENTRIES = 50; export type MediaImportEntry = { at: string; via: MediaImportVia; source: { // Absolute path of the file landed (a live recording: its staging file). path: string; // The file's own name, as it was. name: string; bytes: number; // The original was removed once the copy verified (`move`). moved?: boolean; // The page it was recorded from or describes, when there is one. url?: string; }; // How the container was made from it. finalized: "copied" | "remuxed"; container: { file: string; seconds: number | null; bytes: number }; // What the store holds now: this landing's container ("new") or the one that // was there ("existing", longer), with that one's length. kept: "new" | "existing"; existingSeconds?: number | null; // What became of audio.: extracted from the kept container, the one // there kept (as long or longer), or none (`audio: false`). audio: "extracted" | "kept-existing" | "skipped"; note?: string; }; // A later download of a landed video, and which recording stayed // (ytdlp/landedGuard.ts). export type MediaImportChallenge = { at: string; by: "download"; what: "audio" | "container"; newSeconds: number | null; landedSeconds: number | null; // Audio: the copy kept. A container: the ACTIVE copy — the other one is // kept too, as `alternate` in the store (ytdlp/savedAlternates.ts). kept: "landed" | "download"; alternate?: string; explicit?: boolean; }; export type MediaImportRecord = { entries: MediaImportEntry[]; challenges?: MediaImportChallenge[] }; export function coerceMediaImport(raw: unknown): MediaImportRecord | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const entries = (raw as { entries?: unknown }).entries; if (!Array.isArray(entries)) return null; const challenges = (raw as { challenges?: unknown }).challenges; return { ...(Array.isArray(challenges) ? { challenges: challenges.filter( (c): c is MediaImportChallenge => !!c && typeof c === "object" && typeof (c as MediaImportChallenge).at === "string", ), } : {}), entries: entries.filter( (e): e is MediaImportEntry => !!e && typeof e === "object" && typeof (e as MediaImportEntry).at === "string" && ((e as MediaImportEntry).via === "import-media" || (e as MediaImportEntry).via === "record-live"), ), }; } export function appendMediaImportEntry(prev: MediaImportRecord | null, entry: MediaImportEntry): MediaImportRecord { const entries = [...(prev?.entries ?? []), entry]; return { ...(prev?.challenges ? { challenges: prev.challenges } : {}), entries: entries.slice(-MEDIA_IMPORT_MAX_ENTRIES) }; } // KEEP THE LONGER. `existingSeconds` undefined = nothing in the store; // null = something there that could not be measured (kept: an unreadable // length is not evidence it is shorter). `replace` lands the new one always. export function chooseKept(opts: { newSeconds: number | null; existingSeconds?: number | null; replace?: boolean; }): "new" | "existing" { if (opts.replace) return "new"; if (opts.existingSeconds === undefined) return "new"; if (opts.existingSeconds === null) return "existing"; if (opts.newSeconds === null) return "existing"; return opts.newSeconds > opts.existingSeconds + KEEP_LONGER_TOLERANCE_SECONDS ? "new" : "existing"; } // --- what ffprobe said ------------------------------------------------------------ export type MediaProbe = { formatName: string; seconds: number | null; videoCodec: string | null; audioCodec: string | null; }; // ffprobe's `-show_format -show_streams -of json`, read. Null when it holds no // format at all (not media). export function readProbe(json: unknown): MediaProbe | null { if (!json || typeof json !== "object") return null; const j = json as { format?: { format_name?: unknown; duration?: unknown }; streams?: unknown }; const formatName = typeof j.format?.format_name === "string" ? j.format.format_name : null; if (!formatName) return null; const d = Number.parseFloat(String(j.format?.duration ?? "")); const streams = Array.isArray(j.streams) ? (j.streams as { codec_type?: unknown; codec_name?: unknown }[]) : []; const codec = (type: string) => { const s = streams.find((x) => x.codec_type === type && typeof x.codec_name === "string"); return s ? String(s.codec_name) : null; }; return { formatName, seconds: Number.isFinite(d) && d > 0 ? Math.round(d * 1000) / 1000 : null, videoCodec: codec("video"), audioCodec: codec("audio"), }; } // Codecs an mp4 holds (a stream copy into mp4 of anything else fails). const MP4_VIDEO = new Set(["h264", "hevc", "av1", "mpeg4", "vp9"]); const MP4_AUDIO = new Set(["aac", "mp3", "ac3", "eac3", "opus", "alac", "flac"]); // An mp4 can hold these codecs (null: no such stream). export function mp4CanHold(videoCodec: string | null, audioCodec: string | null): boolean { return (videoCodec === null || MP4_VIDEO.has(videoCodec)) && (audioCodec === null || MP4_AUDIO.has(audioCodec)); } // A file's extension, without a trailing `.part` (a yt-dlp partial names the // container it was to become). export function sourceExt(name: string): string { const base = name.replace(/\.part$/i, ""); return path.extname(base).slice(1).toLowerCase(); } export type LandingFinalize = { action: "copy" | "remux"; // The stored container's extension. ext: string; // Remux: the output format and its extra args. remuxArgs?: string[]; reason: string; }; // HOW A PROBED FILE BECOMES A STORED CONTAINER. Never a re-encode. export function finalizeFor(name: string, probe: MediaProbe): LandingFinalize | { refused: string } { if (!probe.videoCodec && !probe.audioCodec) return { refused: `${name} holds no audio or video stream` }; if (!probe.audioCodec) return { refused: `${name} holds no audio stream: nothing to transcribe` }; const ext = sourceExt(name); const partial = /\.part$/i.test(name); const fmt = probe.formatName; const isMp4 = /(^|,)(mov|mp4)(,|$)/.test(fmt); const isMkv = /(^|,)(matroska|webm)(,|$)/.test(fmt); if (!partial && isMp4 && ["mp4", "m4v", "mov"].includes(ext)) { return { action: "copy", ext, reason: `${fmt} as it is` }; } if (!partial && isMkv && ["mkv", "webm"].includes(ext)) { return { action: "copy", ext, reason: `${fmt} as it is` }; } const mp4Ok = mp4CanHold(probe.videoCodec, probe.audioCodec); if (mp4Ok) { return { action: "remux", ext: "mp4", remuxArgs: ["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-movflags", "+faststart", "-f", "mp4"], reason: `${fmt}${partial ? " (a partial)" : ""} → mp4, stream copy`, }; } return { action: "remux", ext: "mkv", remuxArgs: ["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-f", "matroska"], reason: `${fmt} (${probe.videoCodec ?? "no video"}/${probe.audioCodec}) → mkv, stream copy`, }; } // --- the request ------------------------------------------------------------------ export const IMPORT_MEDIA_BODY_KEYS = [ "slug", "path", "url", "id", "meta", "move", "replace", "audio", "transcribe", "doNotClean", "note", "dryRun", ] as const; // A record described by hand, for a file with no source page. export type ManualMeta = { title: string; // YYYY-MM-DD (or YYYYMMDD). date?: string; duration?: number; description?: string; // A URL the file is a copy of, recorded as the record's `webpage_url` only // when it is not a page yt-dlp would be asked about. sourceNote?: string; }; export type ImportMediaRequest = { slug: string; path: string; url?: string; id?: string; meta?: ManualMeta; move?: boolean; replace?: boolean; // false: land the container only, no audio.. audio?: boolean; // true: hand the video to a transcribe-one job once landed (held by any // pause like every transcription). Absent: the channel's lanes take it by // their policy. transcribe?: boolean; // Set the video's "Do not clean" marker once landed, with `note`. doNotClean?: boolean; // Why: the marker's note, and the provenance entry's. note?: string; dryRun?: boolean; }; // One path segment that a data dir may be named. export function isRecordId(id: string): boolean { return /^[\w.-]+$/.test(id) && id !== "." && id !== ".."; } // An id for a file with no source page and no id given: its name, lowercased, // [a-z0-9_-] only, at most 64 characters. export function importIdFromFilename(name: string): string { const stem = name.replace(/\.part$/i, "").replace(/\.[^.]+$/, ""); const id = stem .toLowerCase() .replace(/[^a-z0-9_-]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 64) .replace(/-+$/g, ""); return id || "import"; } function normalDate(raw: string | undefined): string | null { if (!raw) return null; const d = raw.trim().replace(/-/g, ""); return /^\d{8}$/.test(d) ? d : null; } // Validates a request body. The error is the sentence the caller answers. export function parseImportRequest(body: Record): ImportMediaRequest | { error: string } { const str = (k: string) => (typeof body[k] === "string" ? (body[k] as string).trim() : undefined); const slug = str("slug"); const p = str("path"); if (!slug) return { error: '"slug" is required' }; if (!p) return { error: '"path" is required (an absolute path to a file, a directory, a .zip or a .7z)' }; if (!path.isAbsolute(p)) return { error: `"path" must be absolute: ${p}` }; const url = str("url"); const id = str("id"); let meta: ManualMeta | undefined; if (body.meta !== undefined) { const m = body.meta as Record | null; if (!m || typeof m !== "object" || Array.isArray(m)) return { error: '"meta" is {title, date?, duration?, description?}' }; const title = typeof m.title === "string" ? m.title.trim() : ""; if (!title) return { error: '"meta.title" is required' }; if (m.date !== undefined && (typeof m.date !== "string" || normalDate(m.date) === null)) { return { error: '"meta.date" is YYYY-MM-DD' }; } if (m.duration !== undefined && (typeof m.duration !== "number" || !(m.duration > 0))) { return { error: '"meta.duration" is a number of seconds' }; } meta = { title, ...(typeof m.date === "string" ? { date: m.date } : {}), ...(typeof m.duration === "number" ? { duration: m.duration } : {}), ...(typeof m.description === "string" && m.description.trim() ? { description: m.description.trim() } : {}), }; } if (url && meta) return { error: 'Give "url" (the source page) or "meta" (a record by hand), not both' }; if (id !== undefined && !isRecordId(id)) return { error: `"${id}" is not a record id (one path segment)` }; if (url && !/^https?:\/\//i.test(url)) return { error: `"url" must be an http(s) URL: ${url}` }; if (!url && !id && !meta) { return { error: 'Say which record the file is: "url" (its source page), "id" (a record already here) or "meta" ({title, date?})' }; } const flag = (k: string) => { const v = body[k]; if (v === undefined) return undefined; if (typeof v !== "boolean") throw new Error(`"${k}" must be true or false`); return v; }; try { const move = flag("move"); const replace = flag("replace"); const audio = flag("audio"); const transcribe = flag("transcribe"); const doNotClean = flag("doNotClean"); const dryRun = flag("dryRun"); const note = str("note"); return { ...(doNotClean !== undefined ? { doNotClean } : {}), ...(note ? { note } : {}), slug, path: p, ...(url ? { url } : {}), ...(id ? { id } : {}), ...(meta ? { meta } : {}), ...(move !== undefined ? { move } : {}), ...(replace !== undefined ? { replace } : {}), ...(audio !== undefined ? { audio } : {}), ...(transcribe !== undefined ? { transcribe } : {}), ...(dryRun !== undefined ? { dryRun } : {}), }; } catch (err) { return { error: (err as Error).message }; } } // THE RECORD FOR A FILE WITH NO SOURCE PAGE: the fields every reader needs // (id, title, upload_date, duration), and `extractor: "import"` so nothing // mistakes it for a page yt-dlp could re-read. export function manualRecordInfo(opts: { id: string; meta: ManualMeta; seconds: number | null; fileName: string; }): Record { const date = normalDate(opts.meta.date); const duration = opts.meta.duration ?? opts.seconds; return { id: opts.id, title: opts.meta.title, ...(opts.meta.description ? { description: opts.meta.description } : {}), ...(date ? { upload_date: date } : {}), ...(typeof duration === "number" && duration > 0 ? { duration: Math.round(duration * 100) / 100 } : {}), extractor: "import", extractor_key: "Import", live_status: "not_live", imported_from: opts.fileName, }; } // The `archive` file's line for a record yt-dlp wrote (` `, the // shape downloadOneManaged prints with ARCHIVE_MARKER), or null for one it did // not (a record by hand). export function archiveLineFor(meta: Record): string | null { const ex = typeof meta.extractor === "string" ? meta.extractor : null; const id = typeof meta.id === "string" ? meta.id : null; if (!ex || !id || ex === "import") return null; return `${ex} ${id}`; }