// THE COMBO COUNTER's PRINTS (post-combo.mjs): what each post item's // attachment IS, read from disk -- its X media id and sha256 from the // capture's record (capture.json, the project's copy beside the file, else // the corpus's `channels//posts-media//`), the file hashed when // no record vouches for it, and (opt-in) its sound's fingerprint. Each // file's print is CACHED by its path, size and mtime: in memory, and on disk // under UMTOOL_PRINTS_CACHE (default ~/.cache/umtool/media-prints), so a // second look at a cut hashes nothing. // // attachmentPrints(manifest, dir, o) { ":": print } // projectCombos(dir, manifest, o) the groups and each item's combo (post-combo.mjs), one call // // Plain ESM, node only: the build, the CLI and umtool's server import it. import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { COMBO_DEFAULTS, comboCounts, comboItems, comboKnobs, repeatGroups, tiersOf, xMediaIdOf } from "./post-combo.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** Where the prints are kept: UMTOOL_PRINTS_CACHE, else ~/.cache/umtool/media-prints (XDG_CACHE_HOME honoured). */ export function printsCacheDir(env = process.env) { if (env.UMTOOL_PRINTS_CACHE) return env.UMTOOL_PRINTS_CACHE; return path.join(/* turbopackIgnore: true */ env.XDG_CACHE_HOME || path.join(/* turbopackIgnore: true */ os.homedir(), ".cache"), "umtool", "media-prints"); } const memo = new Map(); const MEMO_MAX = 4000; /** A file's cached print fields (`sha256`, `audio`), keyed by its path and signature. */ async function cached(file, sig, cacheDir, field, make) { // No cache asked for (null): made every time. if (cacheDir === null) return make(); const key = createHash("sha1").update(file).digest("hex"); let rec = memo.get(key); if (!rec || rec.sig !== sig) { rec = cacheDir ? await readFile(path.join(cacheDir, `${key}.json`), "utf8").then((t) => JSON.parse(t), () => null) : null; if (!rec || rec.sig !== sig) rec = { sig, file }; } if (!(field in rec)) { rec[field] = await make(); if (cacheDir) { await mkdir(cacheDir, { recursive: true }).catch(() => {}); const tmp = tmpPathFor(path.join(cacheDir, `.${key}`)); await writeFile(tmp, JSON.stringify(rec), "utf8").then(() => rename(tmp, path.join(cacheDir, `${key}.json`)), () => {}); } } if (memo.size >= MEMO_MAX) memo.delete(memo.keys().next().value); memo.set(key, rec); return rec[field]; } /** A file's sha256, streamed. */ export function sha256File(file) { return new Promise((resolve, reject) => { const h = createHash("sha256"); createReadStream(file).on("data", (b) => h.update(b)).on("end", () => resolve(h.digest("hex"))).on("error", reject); }); } /** * The sound's fingerprint: chromaprint's raw print (`fpcalc -raw`, its first * 30 s), else the coarse hash -- ffmpeg's 8 kHz mono, each 1/8 s its energy * and its zero crossings against the one before (2 bits), 16 steps to a word. * Null for a file with no sound, or when neither tool runs. * * @returns {Promise<{ kind: "chromaprint"|"energy", bits: number, words: number[], seconds: number } | null>} */ export async function audioPrintOf(file, { fpcalc = process.env.FPCALC_BIN ?? "fpcalc", ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", exec = execFileP } = {}) { try { const r = await exec(fpcalc, ["-raw", "-json", "-length", "30", file], { maxBuffer: 1 << 24 }); const j = JSON.parse(String(r.stdout)); if (Array.isArray(j?.fingerprint) && j.fingerprint.length) return { kind: "chromaprint", bits: 32, words: j.fingerprint.map((v) => v >>> 0), seconds: Number(j.duration) || 0 }; } catch { // no fpcalc, or no sound it can read: the coarse hash } try { const r = await exec(ffmpeg, ["-nostdin", "-v", "error", "-t", "30", "-i", file, "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { encoding: "buffer", maxBuffer: 1 << 26 }); return energyPrint(Buffer.from(r.stdout)); } catch { return null; } } /** The coarse hash of 8 kHz mono s16le samples (audioPrintOf's fallback), pure. Null when silent or too short. */ export function energyPrint(buf, rate = 8000) { const n = Math.floor(buf.length / 2); const block = Math.round(rate / 8); const blocks = Math.floor(n / block); if (blocks < 4) return null; const e = []; const z = []; for (let b = 0; b < blocks; b += 1) { let s = 0; let c = 0; let prev = 0; for (let i = 0; i < block; i += 1) { const v = buf.readInt16LE((b * block + i) * 2); s += v * v; if (i && (v >= 0) !== (prev >= 0)) c += 1; prev = v; } e.push(Math.sqrt(s / block)); z.push(c); } if (Math.max(...e) < 30) return null; const bitsOut = []; for (let b = 1; b < blocks; b += 1) bitsOut.push(e[b] > e[b - 1] ? 1 : 0, z[b] > z[b - 1] ? 1 : 0); const words = []; for (let i = 0; i + 16 <= bitsOut.length; i += 16) { let w = 0; for (let j = 0; j < 16; j += 1) w = (w << 1) | bitsOut[i + j]; words.push(w >>> 0); } return words.length ? { kind: "energy", bits: 16, words, seconds: n / rate } : null; } /** The capture record a project file came from: beside it in the project, else the corpus's (`posts-media///`). */ async function captureRecordOf(dir, src, entry, channelsDir) { const name = path.basename(src); const m = /^posts-media\/([^/]+)\/([^/]+)\/[^/]+$/.exec(src); const tries = [path.join(dir, path.dirname(src), "capture.json")]; if (channelsDir && m) tries.push(path.join(channelsDir, m[1], "posts-media", m[2], "capture.json")); const [slug, postId] = typeof entry?.post === "string" ? entry.post.split("/") : []; if (channelsDir && slug && postId && !(m && m[1] === slug && m[2] === postId)) tries.push(path.join(channelsDir, slug, "posts-media", postId, "capture.json")); for (const f of tries) { const cap = await readFile(f, "utf8").then((t) => JSON.parse(t), () => null); const rec = Array.isArray(cap?.media) ? cap.media.find((x) => x?.name === name) : null; if (rec) return rec; } return null; } /** * EVERY ATTACHMENT's PRINT in the cut: `{ ":": { mediaId, sha256, * audio?, via } }` -- the media id from the capture's url, the sha256 from its * record when the bytes agree (`via: "capture"`), else the file's own (`via: * "hashed"`), the sound's print when `match` is "audio" and it is a video with * sound. A file not on disk has no print (it cannot be told apart). * * @param {Record} manifest * @param {string} dir the project's folder (the manifest's) * @param {{ channelsDir?: string|null, match?: string, cacheDir?: string|null, audioPrint?: typeof audioPrintOf }} [o] */ export async function attachmentPrints(manifest, dir, { channelsDir = null, match = null, cacheDir = printsCacheDir(), audioPrint = audioPrintOf } = {}) { const tiers = tiersOf(match ?? comboKnobs(manifest?.render).match ?? COMBO_DEFAULTS.match); const out = {}; for (const e of comboItems(manifest?.timeline)) { for (const [i, m] of e.media.entries()) { if (!isObj(m) || typeof m.src !== "string") continue; const file = path.resolve(dir, m.src); const st = await stat(file).catch(() => null); if (!st?.isFile()) continue; const sig = `${st.size}|${Math.round(st.mtimeMs)}`; const rec = await captureRecordOf(dir, m.src, e, channelsDir); const p = { mediaId: xMediaIdOf(rec?.url), sha256: null, via: null }; if (tiers.includes("sha256")) { if (typeof rec?.sha256 === "string" && /^[0-9a-f]{64}$/.test(rec.sha256) && rec.bytes === st.size) { p.sha256 = rec.sha256; p.via = "capture"; } else { p.sha256 = await cached(file, sig, cacheDir, "sha256", () => sha256File(file)); p.via = "hashed"; } } if (tiers.includes("audio") && m.kind === "video" && m.audio !== false) { p.audio = await cached(file, sig, cacheDir, "audio", () => audioPrint(file)); } out[`${e.id}:${i}`] = p; } } return out; } /** * THE CUT's COMBOS in one call: the repeat groups (post-combo.mjs * repeatGroups) over the prints, and each item's combo (comboCounts). * * @param {string} dir * @param {Record} manifest * @param {{ channelsDir?: string|null, match?: string|null, cacheDir?: string|null, audioPrint?: typeof audioPrintOf }} [o] */ export async function projectCombos(dir, manifest, o = {}) { const match = o.match ?? comboKnobs(manifest?.render).match; const prints = await attachmentPrints(manifest, dir, { ...o, match }); const groups = repeatGroups(manifest?.timeline, (id, i) => prints[`${id}:${i}`], { match }); return { match, groups, combos: comboCounts(manifest?.timeline, groups, manifest?.render), prints }; } /** * THE REPEATS THE CUT DOES NOT SHOW YET: a post item with no attachment in * the cut whose capture holds one (captured after the item went in -- its * media was never copied). Its capture is looked for under its own channel, * then every channel the cut's posts come from (a reply captured under the * replies channel). `{ : [{ name, slug, tree, mediaId, sha256, url }] }`. * * `channelsDirs`: the channels trees to look in, in order (the project's own first, then the archive behind it: * sources.mjs channelsLayersFor) -- the first tree that holds the post's capture wins, and each file says which * (`tree`). Read only: nothing is written into any of them. * * @param {Record} manifest * @param {{ channelsDir?: string|null, channelsDirs?: string[]|null }} [o] */ export async function captureOnlyMedia(manifest, { channelsDir = null, channelsDirs = null } = {}) { const trees = (Array.isArray(channelsDirs) && channelsDirs.length ? channelsDirs : [channelsDir]).filter((d) => typeof d === "string" && d); if (!trees.length) return {}; const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter((c) => c && c !== "." && c !== ".." && !/[\\\0]/.test(c)))]; const out = {}; for (const e of tl) { if (e?.type !== "post" || typeof e.post !== "string" || (Array.isArray(e.media) && e.media.length)) continue; const [own, postId] = e.post.split("/"); if (!own || !postId) continue; // A post id of dots is no folder of a capture: never joined into a tree's path. if ([own, postId].some((v) => v === "." || v === ".." || /[\\\0]/.test(v))) continue; found: for (const tree of trees) { for (const slug of [own, ...channels.filter((c) => c !== own)]) { const dirOf = path.join(tree, slug, "posts-media", postId); const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null); const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : []; if (!media.length) continue; out[e.id] = media.map((m) => ({ name: m.name, slug, tree, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null })); break found; } } } return out; }