// PARTS OF ONE LIVE RECORDING JOINED INTO ONE FILE — record-live's landing // (controller/recordLive.ts), when no single part holds the stream but two or // more together hold more than the longest alone: a from-start part that // stopped short and a live-edge part (a fallback, the insurance recorder), or // live-edge parts a restart left one after the other. // // WHERE EACH PART SITS IN THE STREAM. A from-start part begins at the // stream's second 0. A live-edge part begins about (its startedAt − the // stream's start) in, by the clock — and the live edge lags the clock, so its // real place is found BY CONTENT: its first PROBE_SECONDS of sound (8 kHz, // lib/recordingClock.mjs locate) searched in the part before it, from // SEARCH_BEFORE_S before its clock place to SEARCH_AFTER_S after; a match // must score ≥ MIN_SCORE and stand MIN_PEAK_RATIO above any other peak, and a // second anchor near where the join will be must agree within LAG_TOLERANCE_S. // // overlap the next part is cut where the one before ends (`-c copy`, which // starts at the keyframe at or before the cut: those seconds are // heard twice, `duplicatedSeconds`); the joined file's timeline is // the stream's from the first part's start // gap the next part begins after the one before ends (or overlaps it // too little to align): joined as it is, the gap stated by the // clock (`basis: "clock"`, about N s). The joined file's timeline // is NOT the stream's after it — live-joins.json maps each segment. // // NOTHING IS TRUSTED UNTIL PROVEN. The joined file is written under a scratch // name (no reader takes it for a part) and kept only when its duration is the // segments' sum within max(1 s, 0.2 %) and, at every join, the sound 5–25 s // before matches the segment before and 5–25 s after matches the segment // after (and its head matches the first part). Anything else — a failed // check, codecs or sizes that differ (a stream copy cannot join them, and a // re-encode of hours is not done here), a part with no known place — and the // joined file is removed: the landing lands the longest and keeps the rest, // as before. The parts themselves are never touched here; the landing // removes a joined part only after the joined file has landed. import path from "node:path"; import { rename, rm, writeFile } from "node:fs/promises"; import { execa } from "execa"; import { locate } from "../lib/recordingClock.mjs"; import { decodeExcerpt } from "../lib/recordingClock-server"; import type { LiveJoin, LiveJoinSegment } from "../lib/liveCapture"; import "../lib/childKillGuard"; export const JOIN_SAMPLE_RATE = 8000; export const JOIN_PROBE_SECONDS = 20; export const JOIN_SEARCH_BEFORE_S = 180; export const JOIN_SEARCH_AFTER_S = 60; export const JOIN_MIN_SCORE = 0.35; export const JOIN_MIN_PEAK_RATIO = 1.15; export const JOIN_LAG_TOLERANCE_S = 0.25; // An overlap shorter than this (by the clock) is not aligned: a gap join. export const JOIN_MIN_OVERLAP_S = 25; // A part that adds less than this past the union's end is not joined. export const JOIN_MIN_GAIN_S = 30; export const JOIN_MAX_PARTS = 4; // A part shorter than this is never joined (the checks need its sound). export const JOIN_MIN_PART_S = 60; // A cut whose stream copy starts this much after the point asked leaves a hole; // one that starts more than JOIN_MAX_EARLY_CUT_S before it is not a keyframe // snap (REVIEW-1 1.5 of live-guard-2). export const JOIN_CUT_LATE_TOLERANCE_S = 0.25; export const JOIN_MAX_EARLY_CUT_S = 30; // Two frames (32x18 grey) are the same picture when they differ by at most // this on average (0-255): a re-mux decodes the same frame, a frame or two off // still matches, another moment does not. export const JOIN_FRAME_MAX_DIFF = 12; // Frames compared across an overlap, and how much more the same frames one // second apart must differ for the picture to prove the alignment. export const JOIN_PICTURE_SAMPLES = 4; export const JOIN_PICTURE_MARGIN = 4; export type JoinStreams = { seconds: number | null; videoCodec: string | null; audioCodec: string | null; width: number | null; height: number | null; sampleRate: number | null; channels: number | null; }; export type JoinDeps = { // Mono float samples at `rate` of [from, from + seconds) of `file`. decode: (file: string, from: number, seconds: number, rate: number) => Promise; // `file` from `from` seconds to its end, stream-copied into `out`; returns // where the copy really starts (the keyframe at or before `from`). cut: (file: string, from: number, out: string) => Promise; // The files one after the other, stream-copied into `out`. concat: (files: string[], out: string) => Promise; probe: (file: string) => Promise; // A small grey frame of the picture at `at` seconds (null: no picture // decoded there). frame: (file: string, at: number) => Promise; // The packets' timestamps (seconds) of [from, from + seconds) of `file`, // video and audio (null: cannot be read). timestamps: (file: string, from: number, seconds: number) => Promise<{ video: number[]; audio: number[] } | null>; }; export function frameDiff(a: Uint8Array, b: Uint8Array): number { if (a.length !== b.length || a.length === 0) return Infinity; let d = 0; for (let i = 0; i < a.length; i++) d += Math.abs(a[i]! - b[i]!); return d / a.length; } export type JoinPart = { stem: string; file: string; seconds: number; fromStart: boolean; // When its recorder started (ISO). startedAt: string | null; }; export type JoinResult = | { ok: true; file: string; seconds: number; joins: LiveJoin[]; segments: LiveJoinSegment[]; stems: string[] } | { ok: false; why: string }; type Seg = { part: JoinPart; file: string; fileFrom: number; streamFrom: number; streamFromBasis: "start" | "content" | "clock" }; function matchAt( probe: Float32Array, search: Float32Array, searchStart: number, expected: number | null, ): { at: number; score: number; ok: boolean; why?: string } { const hit = locate(probe, search, { guard: Math.round(0.25 * JOIN_SAMPLE_RATE) }); if (!hit) return { at: NaN, score: 0, ok: false, why: "silent" }; const at = searchStart + hit.lag / JOIN_SAMPLE_RATE; const ratio = hit.second > 1e-9 ? hit.score / hit.second : 99; if (hit.score < JOIN_MIN_SCORE) return { at, score: hit.score, ok: false, why: `weak (${hit.score.toFixed(2)})` }; if (ratio < JOIN_MIN_PEAK_RATIO) return { at, score: hit.score, ok: false, why: `ambiguous (${ratio.toFixed(2)})` }; if (expected !== null && Math.abs(at - expected) > JOIN_LAG_TOLERANCE_S) { return { at, score: hit.score, ok: false, why: `off by ${(at - expected).toFixed(2)} s` }; } return { at, score: hit.score, ok: true }; } const r3 = (x: number) => Math.round(x * 1000) / 1000; export type JoinOpts = { parts: JoinPart[]; streamStartedAt: string | null; // `` for the joined file (its scratch name is `.temp.`). outStem: string; deps: JoinDeps; say: (s: string) => void; }; // Every scratch file the join writes is removed however it ends — a refusal, // a proof that fails, or a tool that throws (REVIEW-1 1.6 of live-guard-2). // Only the proven joined file, renamed out of its scratch name, stays. export async function joinLiveParts(o: JoinOpts): Promise { const scratch: string[] = []; try { return await joinInner(o, scratch); } finally { for (const f of scratch) await rm(f, { force: true }).catch(() => {}); } } async function joinInner(o: JoinOpts, scratch: string[]): Promise { const { deps, say } = o; const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN; const usable = o.parts.filter((p) => p.seconds >= JOIN_MIN_PART_S); const fromStart = usable.filter((p) => p.fromStart).sort((a, b) => b.seconds - a.seconds); const base = fromStart[0] ?? [...usable].filter((p) => p.startedAt).sort((a, b) => Date.parse(a.startedAt!) - Date.parse(b.startedAt!))[0]; if (!base) return { ok: false, why: "no part long enough to join" }; // A part's place by the clock, in the stream (from-start base) or after // the base's start (a live-edge base). const clockPlace = (p: JoinPart): number | null => { if (!p.startedAt) return null; const t = Date.parse(p.startedAt); if (base.fromStart) return Number.isFinite(startMs) ? (t - startMs) / 1000 : null; return (t - Date.parse(base.startedAt!)) / 1000; }; const others = usable .filter((p) => p !== base && !p.fromStart) .map((p) => ({ p, place: clockPlace(p) })) .filter((x): x is { p: JoinPart; place: number } => x.place !== null) .sort((a, b) => a.place - b.place); if (!others.length) return { ok: false, why: "no other part with a known place in the stream" }; const probes = new Map(); for (const p of [base, ...others.map((x) => x.p)]) { const s = await deps.probe(p.file); if (!s) return { ok: false, why: `${path.basename(p.file)} cannot be read` }; probes.set(p.stem, s); } const b0 = probes.get(base.stem)!; const same = (s: JoinStreams) => s.videoCodec === b0.videoCodec && s.audioCodec === b0.audioCodec && s.width === b0.width && s.height === b0.height && s.sampleRate === b0.sampleRate && s.channels === b0.channels; const segs: Seg[] = [{ part: base, file: base.file, fileFrom: 0, streamFrom: 0, streamFromBasis: base.fromStart ? "start" : "clock" }]; const joins: LiveJoin[] = []; const cleanup = async () => { for (const f of scratch) await rm(f, { force: true }); }; let unionEnd = base.seconds; const rate = JOIN_SAMPLE_RATE; let stopWhy: string | null = null; // Per join: did the two parts' pictures prove it (REVIEW-2 2.1)? const provenByPicture: boolean[] = []; for (const { p, place } of others) { if (segs.length >= JOIN_MAX_PARTS) break; if (place + p.seconds < unionEnd + JOIN_MIN_GAIN_S) continue; if (!same(probes.get(p.stem)!)) { say(`${path.basename(p.file)} is not joined: its codecs or picture size differ from ${path.basename(base.file)} (a stream copy cannot join them).`); continue; } const last = segs[segs.length - 1]!; // Stream second → seconds into the last segment's file. const inLast = (t: number) => t - last.streamFrom + last.fileFrom; const lastFileEnd = inLast(unionEnd); if (place < unionEnd - JOIN_MIN_OVERLAP_S) { // OVERLAP: where does this part's start sit in the last one? const from = Math.max(last.fileFrom, inLast(place) - JOIN_SEARCH_BEFORE_S); const to = Math.min(lastFileEnd, inLast(place) + JOIN_SEARCH_AFTER_S + JOIN_PROBE_SECONDS); if (to - from < JOIN_PROBE_SECONDS * 1.5) { stopWhy = `${path.basename(p.file)}: too little of the part before it to search; not joined.`; say(stopWhy); break; } const probeA = await deps.decode(p.file, 0, JOIN_PROBE_SECONDS, rate); const search = await deps.decode(last.file, from, to - from, rate); const m1 = matchAt(probeA, search, from, null); if (!m1.ok) { stopWhy = `${path.basename(p.file)}: its start is not found in ${path.basename(last.file)} (${m1.why}); not joined — the longest lands, the rest are kept.`; say(stopWhy); break; } // m1.at: seconds into the last file where this part's second 0 is. const streamAt = m1.at - last.fileFrom + last.streamFrom; const cutAt = unionEnd - streamAt; // seconds into this part // The second anchor, just before where the join will be. const a2 = Math.max(0, cutAt - JOIN_PROBE_SECONDS - 5); const probeB = await deps.decode(p.file, a2, JOIN_PROBE_SECONDS, rate); const expect2 = m1.at + a2; const from2 = Math.max(last.fileFrom, expect2 - 3); const search2 = await deps.decode(last.file, from2, Math.min(lastFileEnd, expect2 + JOIN_PROBE_SECONDS + 3) - from2, rate); const m2 = matchAt(probeB, search2, from2, expect2); if (!m2.ok) { stopWhy = `${path.basename(p.file)}: the second check near the join does not agree (${m2.why}); not joined — the longest lands, the rest are kept.`; say(stopWhy); break; } // THE PICTURE ACROSS THE OVERLAP (REVIEW-2 2.1): the two SOURCE parts // compared with each other at matching stream times, spread over the // overlap; and the same frames one second apart, which must differ // for the picture to prove anything (a static scene cannot). let pictureProves = false; if (b0.videoCodec) { const lo = streamAt + 2; const hi = unionEnd - 2; const match: number[] = []; const off: number[] = []; for (let k = 0; k < JOIN_PICTURE_SAMPLES && hi > lo; k++) { const t = lo + ((hi - lo) * (k + 0.5)) / JOIN_PICTURE_SAMPLES; const [x, y, z] = await Promise.all([deps.frame(last.file, inLast(t)), deps.frame(p.file, t - streamAt), deps.frame(p.file, t - streamAt + 1)]); if (!x || !y || !z) continue; match.push(frameDiff(x, y)); off.push(frameDiff(x, z)); } if (match.some((d) => d > JOIN_FRAME_MAX_DIFF)) { stopWhy = `${path.basename(p.file)}: its picture is not ${path.basename(last.file)}'s at the same stream times across the overlap (difference up to ${Math.max(...match).toFixed(1)}); not joined.`; say(stopWhy); break; } const mean = (v: number[]) => v.reduce((n, x) => n + x, 0) / (v.length || 1); pictureProves = match.length >= 2 && mean(off) > 2 * mean(match) + JOIN_PICTURE_MARGIN; } provenByPicture.push(pictureProves); const segFile = `${o.outStem}.seg${segs.length}.temp${path.extname(p.file) || ".mkv"}`; scratch.push(segFile); const realFrom = await deps.cut(p.file, cutAt, segFile); if (realFrom > cutAt + JOIN_CUT_LATE_TOLERANCE_S) { stopWhy = `${path.basename(p.file)}: its stream copy starts ${(realFrom - cutAt).toFixed(2)} s after the cut point — a hole of seconds in neither part; not joined.`; say(stopWhy); break; } if (cutAt - realFrom > JOIN_MAX_EARLY_CUT_S) { stopWhy = `${path.basename(p.file)}: its stream copy starts ${(cutAt - realFrom).toFixed(2)} s before the cut point (not a keyframe's snap); not joined.`; say(stopWhy); break; } // The seconds heard twice: where the copy really starts, against where // it was asked to (both recorded). const dup = cutAt - realFrom; joins.push({ at: 0, // set below, once the segments' lengths are known kind: "overlap", seconds: r3(unionEnd - streamAt), duplicatedSeconds: r3(dup), cutAt: r3(cutAt), cutFrom: r3(realFrom), basis: "content", score: r3(Math.min(m1.score, m2.score)), parts: [last.part.stem, p.stem], }); segs.push({ part: p, file: segFile, fileFrom: realFrom, streamFrom: streamAt, streamFromBasis: "content" }); unionEnd = streamAt + p.seconds; } else { // GAP (or too little overlap to align): joined as it is, stated. const gap = Math.max(0, place - unionEnd); joins.push({ at: 0, kind: "gap", seconds: r3(gap), basis: "clock", parts: [last.part.stem, p.stem] }); provenByPicture.push(false); segs.push({ part: p, file: p.file, fileFrom: 0, streamFrom: Math.max(place, unionEnd), streamFromBasis: "clock" }); unionEnd = Math.max(place, unionEnd) + p.seconds; } } if (segs.length < 2) { await cleanup(); return { ok: false, why: stopWhy ?? "nothing could be joined" }; } // Each segment's length in the joined file, and where each join falls. const lengths: number[] = []; for (let i = 0; i < segs.length; i++) { const s = segs[i]!; const total = i === 0 ? s.part.seconds : (await deps.probe(s.file))?.seconds ?? null; if (total === null) { await cleanup(); return { ok: false, why: `the cut of ${path.basename(s.part.file)} cannot be read` }; } lengths.push(i === 0 ? total : total); } const ext = segs.every((s) => /\.ts$/i.test(s.part.file)) ? ".ts" : ".mkv"; const temp = `${o.outStem}.temp${ext}`; const final = `${o.outStem}${ext}`; scratch.push(temp); try { await deps.concat( segs.map((s) => s.file), temp, ); } catch (err) { await cleanup(); return { ok: false, why: `the join failed: ${(err as Error).message.split("\n")[0]}` }; } // PROVEN, or nothing. const joined = await deps.probe(temp); const sum = lengths.reduce((n, l) => n + l, 0); const tol = Math.max(1, sum * 0.002); if (!joined?.seconds || Math.abs(joined.seconds - sum) > tol) { await cleanup(); return { ok: false, why: `the joined file is ${joined?.seconds ?? "?"} s, its parts ${r3(sum)} s: not proven` }; } const check = async (segFile: string, segAt: number, joinedAt: number, what: string): Promise => { const probe = await deps.decode(segFile, segAt, JOIN_PROBE_SECONDS, rate); const from = Math.max(0, joinedAt - 3); const search = await deps.decode(temp, from, JOIN_PROBE_SECONDS + 6, rate); const m = matchAt(probe, search, from, joinedAt); return m.ok ? null : `${what}: ${m.why}`; }; const fails: string[] = []; const head = await check(segs[0]!.file, 5, 5, "the head"); if (head) fails.push(head); let at = 0; for (let i = 0; i < segs.length; i++) { const s = segs[i]!; const len = lengths[i]!; // The segment file's own clock: the base whole, a cut from 0, a gap part whole. if (i > 0) { joins[i - 1]!.at = r3(at); const before = segs[i - 1]!; const beforeLen = lengths[i - 1]!; const b = await check(before.file, beforeLen - 25, at - 25, `before join ${i}`); const a = await check(s.file, 5, at + 5, `after join ${i}`); if (b) fails.push(b); if (a) fails.push(a); } at += len; } // The tail: the joined file ends with its last segment. { const lastSeg = segs[segs.length - 1]!; const lastLen = lengths[lengths.length - 1]!; const tail = await check(lastSeg.file, lastLen - 25, sum - 25, "the tail"); if (tail) fails.push(tail); } // THE PICTURE (REVIEW-1 1.5): on both sides of every join, at the head and // at the tail, the joined file's frame is the segment's. if (b0.videoCodec) { const pic = async (segFile: string, segAt: number, joinedAt: number, what: string) => { const [x, y] = await Promise.all([deps.frame(segFile, segAt), deps.frame(temp, joinedAt)]); if (!x || !y) return `${what}: no picture decoded`; const d = frameDiff(x, y); return d <= JOIN_FRAME_MAX_DIFF ? null : `${what}: the picture differs (${d.toFixed(1)})`; }; const checks: Promise[] = [pic(segs[0]!.file, 5, 5, "the head's picture")]; let pAt = 0; for (let i = 0; i < segs.length; i++) { if (i > 0) { checks.push(pic(segs[i - 1]!.file, lengths[i - 1]! - 10, pAt - 10, `the picture before join ${i}`)); checks.push(pic(segs[i]!.file, 10, pAt + 10, `the picture after join ${i}`)); } pAt += lengths[i]!; } checks.push(pic(segs[segs.length - 1]!.file, lengths[lengths.length - 1]! - 10, sum - 10, "the tail's picture")); for (const r of await Promise.all(checks)) if (r) fails.push(r); } // THE TIMESTAMPS ACROSS EACH JOIN (REVIEW-2 2.1): in the joined file, // video (and audio) packets 5 s either side of every join go on with no // jump larger than a frame (a packet) interval. A join the pictures did // not prove needs this; when it cannot be read either, no join. { let jAt = 0; for (let i = 1; i < segs.length; i++) { jAt += lengths[i - 1]!; const ts = await deps.timestamps(temp, Math.max(0, jAt - 5), 10).catch(() => null); const jumps = (v: number[]) => { const d = [...v].sort((a, b) => a - b).slice(1).map((x, k) => x - [...v].sort((a, b) => a - b)[k]!); if (d.length < 3) return null; const med = [...d].sort((a, b) => a - b)[Math.floor(d.length / 2)]!; return Math.max(...d) > med * 1.5 + 0.001 ? Math.max(...d) : 0; }; const v = ts && (b0.videoCodec ? jumps(ts.video) : 0); const a = ts && jumps(ts.audio); const established = ts !== null && v !== null && a !== null; if (established && ((v ?? 0) > 0 || (a ?? 0) > 0)) { fails.push(`join ${i}: the timestamps jump by ${Math.max(v ?? 0, a ?? 0).toFixed(3)} s`); } else if (!established && !provenByPicture[i - 1]) { fails.push(`join ${i}: neither the picture (a static scene, or none) nor the timestamps can prove it`); } } } if (fails.length) { await cleanup(); return { ok: false, why: `the joined file does not hold its parts where it should (${fails.join("; ")}): not proven` }; } await rename(temp, final); for (const f of scratch) if (f !== temp) await rm(f, { force: true }); let joinedFrom = 0; const segments: LiveJoinSegment[] = segs.map((s, i) => { const len = lengths[i]!; const seg: LiveJoinSegment = { stem: s.part.stem, streamFrom: r3(s.streamFrom + 0), streamFromBasis: s.streamFromBasis, fileFrom: r3(s.fileFrom), fileTo: r3(s.fileFrom + len), joinedFrom: r3(joinedFrom), joinedTo: r3(joinedFrom + len), }; joinedFrom += len; return seg; }); return { ok: true, file: final, seconds: joined.seconds, joins, segments, stems: segs.map((s) => s.part.stem) }; } // --- the real tools: ffmpeg/ffprobe ----------------------------------------------- // `run`: how ffmpeg's cut and concat are run (record-live: the heavy slot, // controller/recordLive.ts runFfmpegHeavy); default, ffmpeg directly. export function ffmpegJoinDeps( bins: { ffmpegBin: string; ffprobeBin: string; run?: (args: string[]) => Promise }, signal?: AbortSignal, ): JoinDeps { const opt = signal ? { cancelSignal: signal } : {}; const ffmpeg = bins.run ?? (async (args: string[]) => void (await execa(bins.ffmpegBin, args, opt))); return { decode: (file, from, seconds, rate) => decodeExcerpt({ ffmpegBin: bins.ffmpegBin, file, from, seconds, sampleRate: rate, ...(signal ? { signal } : {}) }), cut: async (file, from, out) => { await ffmpeg(["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-ss", from.toFixed(3), "-i", file, "-map", "0", "-c", "copy", "-avoid_negative_ts", "make_zero", out]); // Where the copy starts: its length against the whole's. const whole = await probeJoinStreams(bins.ffprobeBin, file); const part = await probeJoinStreams(bins.ffprobeBin, out); if (!whole?.seconds || !part?.seconds) throw new Error(`the cut of ${path.basename(file)} cannot be read`); return Math.max(0, whole.seconds - part.seconds); }, concat: async (files, out) => { const list = `${out}.list.txt`; await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n"); try { const mkv = /\.mkv$/i.test(out); await ffmpeg(["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-map", "0", "-c", "copy", ...(mkv ? ["-f", "matroska"] : ["-f", "mpegts"]), out]); } finally { await rm(list, { force: true }); } }, probe: (file) => probeJoinStreams(bins.ffprobeBin, file), timestamps: async (file, from, seconds) => { const read = async (sel: string) => { const r = await execa( bins.ffprobeBin, ["-v", "error", "-select_streams", sel, "-read_intervals", `${Math.max(0, from).toFixed(3)}%+${seconds.toFixed(3)}`, "-show_entries", "packet=pts_time", "-of", "csv=p=0", file], { reject: false, timeout: 60_000, ...opt }, ); if (r.exitCode !== 0) return null; return String(r.stdout) .split("\n") .map((l) => Number(l.trim().replace(/,$/, ""))) .filter((x) => Number.isFinite(x) && x >= from && x < from + seconds); }; const [video, audio] = await Promise.all([read("v:0"), read("a:0")]); return video && audio ? { video, audio } : null; }, frame: async (file, at) => { const r = await execa( bins.ffmpegBin, ["-v", "error", "-nostdin", "-ss", Math.max(0, at).toFixed(3), "-i", file, "-frames:v", "1", "-vf", "scale=32:18,format=gray", "-f", "rawvideo", "pipe:1"], { encoding: "buffer", reject: false, timeout: 60_000, ...opt }, ); const buf = Buffer.from((r.stdout ?? new Uint8Array()) as Uint8Array); return r.exitCode === 0 && buf.length === 32 * 18 ? new Uint8Array(buf) : null; }, }; } export async function probeJoinStreams(ffprobeBin: string, file: string): Promise { const r = await execa(ffprobeBin, ["-v", "error", "-show_format", "-show_streams", "-of", "json", file], { reject: false }); if (r.exitCode !== 0) return null; try { const j = JSON.parse(String(r.stdout)) as { format?: { duration?: string }; streams?: { codec_type?: string; codec_name?: string; width?: number; height?: number; sample_rate?: string; channels?: number }[]; }; const v = j.streams?.find((s) => s.codec_type === "video"); const a = j.streams?.find((s) => s.codec_type === "audio"); const d = Number(j.format?.duration); return { seconds: Number.isFinite(d) ? d : null, videoCodec: v?.codec_name ?? null, audioCodec: a?.codec_name ?? null, width: v?.width ?? null, height: v?.height ?? null, sampleRate: a?.sample_rate ? Number(a.sample_rate) : null, channels: a?.channels ?? null, }; } catch { return null; } }