VR-MEDIA / src /lib /detection /thumbnail.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
7.55 kB
// Thumbnail generator + background-color auto-detector.
//
// Given a video id, we (1) refresh the provider stream URL, (2) grab a single
// frame from the middle of the video with ffmpeg and write a JPEG to
// THUMBNAIL_DIR/<id>.jpg, and (3) sample a 32x32 downscale of that frame to
// guess the dominant *background* color (green/blue/black/white/…), writing a
// sidecar THUMBNAIL_DIR/<id>.color.json used by the passthrough color resolver.
//
// TeraBox and Blomp thumbnails are extracted through our authenticated
// /api/stream proxy because ffmpeg cannot send their cookies/auth headers.
//
// Everything is cached on disk. Generation is idempotent and cheap on repeat
// hits (we just read the cached JPEG). ffmpeg is preinstalled in the container.
import { spawn, execSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync, readFileSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { db } from "../db";
import {
detectionStreamUrl,
normalizeSource,
pickFreshUrl,
refreshVideoStreamUrls,
} from "../sources";
const THUMB_DIR = process.env.THUMBNAIL_DIR || "/data/thumbnails";
function ensureDir() {
try { if (!existsSync(THUMB_DIR)) mkdirSync(THUMB_DIR, { recursive: true }); } catch {}
}
export function thumbnailPath(id: string): string {
return join(THUMB_DIR, `${id}.jpg`);
}
function colorSidecarPath(id: string): string {
return join(THUMB_DIR, `${id}.color.json`);
}
function ffmpegAvailable(): boolean {
try { execSync("which ffmpeg", { stdio: "ignore" }); return true; } catch { return false; }
}
export function hasCachedThumbnail(id: string): boolean {
try { return existsSync(thumbnailPath(id)) && statSync(thumbnailPath(id)).size > 0; } catch { return false; }
}
/** Extract a middle frame to a JPEG. Returns true on success. */
function extractFrame(url: string, durationSec: number | null, outPath: string): Promise<boolean> {
return new Promise((resolve) => {
const seekTo = durationSec && durationSec > 6 ? (durationSec / 2).toFixed(2) : "2";
const args = [
"-y",
"-ss", seekTo,
"-i", url,
"-frames:v", "1",
// For SBS/OU/fisheye sources we still grab the whole frame; a 640px-wide
// thumbnail keeps cards light. crop the left eye for stereo would be nicer
// but full frame is safe across all projections.
"-vf", "scale=640:-2",
"-q:v", "4",
"-update", "1",
outPath,
];
const proc = spawn("ffmpeg", args, { timeout: 20000 });
proc.on("error", () => resolve(false));
proc.on("close", (code) => resolve(code === 0 && existsSync(outPath)));
});
}
/** Downscale the JPEG to 32x32 raw RGB and guess the dominant background color. */
function detectBackgroundColor(jpgPath: string): Promise<void> {
return new Promise((resolve) => {
const rawPath = join(tmpdir(), `thumbc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.rgb`);
const args = ["-y", "-i", jpgPath, "-vf", "scale=32:32", "-f", "rawvideo", "-pix_fmt", "rgb24", rawPath];
const proc = spawn("ffmpeg", args, { timeout: 8000 });
proc.on("error", () => resolve());
proc.on("close", (code) => {
try {
if (code !== 0 || !existsSync(rawPath)) return resolve();
const buf = readFileSync(rawPath);
const n = Math.floor(buf.length / 3);
if (n === 0) return resolve();
// Tally pixels into coarse background buckets.
const buckets = { green: 0, blue: 0, cyan: 0, magenta: 0, red: 0, yellow: 0, black: 0, white: 0, other: 0 };
let sumR = 0, sumG = 0, sumB = 0;
for (let i = 0; i < n; i++) {
const r = buf[i * 3], g = buf[i * 3 + 1], b = buf[i * 3 + 2];
sumR += r; sumG += g; sumB += b;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
if (max < 45) { buckets.black++; continue; }
if (min > 210) { buckets.white++; continue; }
const sat = max === 0 ? 0 : (max - min) / max;
if (sat < 0.25) { buckets.other++; continue; }
if (g > r + 25 && g > b + 25) buckets.green++;
else if (b > r + 25 && b > g + 25) buckets.blue++;
else if (g > r + 15 && b > r + 15) buckets.cyan++;
else if (r > g + 25 && b > g + 25) buckets.magenta++;
else if (r > g + 25 && r > b + 25) buckets.red++;
else if (r > b + 25 && g > b + 25) buckets.yellow++;
else buckets.other++;
}
const named: Record<string, string> = {
green: "#00ff00", blue: "#0000ff", cyan: "#00ffff", magenta: "#ff00ff",
red: "#ff0000", yellow: "#ffff00", black: "#000000", white: "#ffffff",
};
// Pick the dominant chroma bucket (ignore "other") that also covers a
// meaningful share of the frame (>= 30%).
let best = ""; let bestCount = 0;
for (const [k, c] of Object.entries(buckets)) {
if (k === "other") continue;
if (c > bestCount) { bestCount = c; best = k; }
}
const share = bestCount / n;
let payload: Record<string, unknown>;
if (best && share >= 0.3) {
payload = { name: best, hex: named[best], share: Math.round(share * 100) / 100, source: "auto-frame" };
} else {
// Fall back to the average color of the frame.
const avg = `#${[sumR, sumG, sumB].map((s) => Math.round(s / n).toString(16).padStart(2, "0")).join("")}`;
payload = { name: avg, hex: avg, share: Math.round(share * 100) / 100, source: "auto-frame-avg" };
}
writeFileSync(colorSidecarPath(basename(jpgPath)), JSON.stringify(payload));
} catch {}
resolve();
});
});
}
function basename(jpgPath: string): string {
const b = jpgPath.split("/").pop() || jpgPath;
return b.replace(/\.jpg$/, "");
}
/**
* Ensure a thumbnail exists for the given video id. Returns the JPEG path on
* success, or null if it could not be generated (caller should serve a
* placeholder). Cached results are returned immediately.
*/
export async function ensureThumbnail(id: string): Promise<string | null> {
ensureDir();
const out = thumbnailPath(id);
if (hasCachedThumbnail(id)) return out;
if (!ffmpegAvailable()) return null;
const v = await db.video.findUnique({ where: { id } });
if (!v) return null;
// Get a fresh, playable stream URL from the provider. TeraBox/Blomp are
// handled by the proxy itself (it attaches the required auth headers).
let streamUrl: string | null = v.streamUrl || null;
if (normalizeSource(v.source) !== "terabox") {
try {
const refreshed = await refreshVideoStreamUrls(v);
streamUrl = pickFreshUrl(refreshed, v) ?? streamUrl;
} catch {
// Keep the stored URL as a fallback.
}
}
const probeUrl = await detectionStreamUrl({ ...v, streamUrl });
if (!probeUrl) return null;
const ok = await extractFrame(probeUrl, v.duration ?? null, out);
if (!ok) return null;
// Best-effort background color detection (non-blocking failure).
try { await detectBackgroundColor(out); } catch {}
return out;
}
/** Read the cached thumbnail bytes, or null. */
export function readThumbnail(id: string): Buffer | null {
try {
if (!hasCachedThumbnail(id)) return null;
return readFileSync(thumbnailPath(id));
} catch {
return null;
}
}