video-keyframes / core.js
Ghongha007's picture
video-keyframes 3af4fc5 from GitHub
5dba712 verified
Raw History Blame Contribute Delete
5.59 kB
// video-keyframes core: pure functions, no browser APIs. A classic script (window.KF) that Node can also require().
(function (root) {
"use strict";
// Luminance (Rec. 601) of RGBA pixel data, as a Float32Array of width*height values 0-255.
function gray(rgba) {
const n = rgba.length / 4, g = new Float32Array(n);
for (let i = 0, j = 0; i < n; i++, j += 4) g[i] = 0.299 * rgba[j] + 0.587 * rgba[j + 1] + 0.114 * rgba[j + 2];
return g;
}
// How different two small grey thumbnails are: mean absolute difference, 0 (same) to 1.
function frameDiff(a, b) {
if (!a || !b || a.length !== b.length) return 1;
let s = 0;
for (let i = 0; i < a.length; i++) s += Math.abs(a[i] - b[i]);
return s / a.length / 255;
}
// Sharpness: variance of the Laplacian (a common focus measure). Higher is sharper; blur and motion lower it.
function sharpness(g, w, h) {
let n = 0, mean = 0, m2 = 0;
for (let y = 1; y < h - 1; y++)
for (let x = 1; x < w - 1; x++) {
const i = y * w + x;
const v = 4 * g[i] - g[i - 1] - g[i + 1] - g[i - w] - g[i + w];
n++; const d = v - mean; mean += d / n; m2 += d * (v - mean);
}
return n > 1 ? m2 / (n - 1) : 0;
}
// Mean brightness 0-255: lets us skip black or white transition frames.
function brightness(g) { let s = 0; for (let i = 0; i < g.length; i++) s += g[i]; return g.length ? s / g.length : 0; }
// Sensitivity 1 (only hard cuts) .. 10 (small changes) -> difference threshold.
function thresholdFor(sensitivity) {
const s = Math.min(10, Math.max(1, sensitivity));
return 0.25 * Math.pow(0.03 / 0.25, (s - 1) / 9); // 0.25 at 1, about 0.10 at 5, 0.03 at 10 (log scale)
}
// Pick keyframes from samples [{t, diff, sharp, bright}] taken in time order.
// A new shot starts where diff (to the previous sample) passes the threshold, at least minGap seconds after the last one.
// From each shot's first `window` samples, keep the sharpest one that is not almost black or white.
function pickScenes(samples, opts) {
const o = Object.assign({ threshold: 0.12, minGap: 1, window: 3 }, opts || {});
const starts = [];
samples.forEach((s, i) => {
if (i === 0 || (s.diff >= o.threshold && s.t - samples[starts[starts.length - 1]].t >= o.minGap)) starts.push(i);
});
return starts.map((st, k) => {
const end = Math.min(k + 1 < starts.length ? starts[k + 1] : samples.length, st + o.window);
let best = st, bestScore = -1;
for (let i = st; i < end; i++) {
const s = samples[i], usable = s.bright > 12 && s.bright < 245;
const score = (usable ? 1 : 0.001) * s.sharp;
if (score > bestScore) { bestScore = score; best = i; }
}
return best;
});
}
// Sample times: every `step` seconds from 0 to duration, at most maxSamples (the step grows for long videos).
function sampleTimes(duration, step, maxSamples) {
if (!(duration > 0)) return [];
const st = Math.max(step, duration / maxSamples), out = [];
for (let t = 0; t < duration - 0.05; t += st) out.push(Math.round(t * 1000) / 1000);
return out;
}
// 00:01:23.450
function fmtTime(t) {
const ms = Math.round(t * 1000), h = Math.floor(ms / 3600000), m = Math.floor(ms / 60000) % 60, s = Math.floor(ms / 1000) % 60;
const p = (x, n = 2) => String(x).padStart(n, "0");
return `${p(h)}:${p(m)}:${p(s)}.${p(ms % 1000, 3)}`;
}
// ---- a store-only ZIP writer (no compression; PNG/JPEG are already compressed)
const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
function crc32(u8) { let c = 0xFFFFFFFF; for (let i = 0; i < u8.length; i++) c = CRC[(c ^ u8[i]) & 255] ^ (c >>> 8); return (c ^ 0xFFFFFFFF) >>> 0; }
function zip(files) { // files: [{name, data: Uint8Array}] -> Uint8Array
const enc = new TextEncoder(), parts = [], central = [];
let offset = 0;
const u16 = (v) => [v & 255, (v >>> 8) & 255], u32 = (v) => [v & 255, (v >>> 8) & 255, (v >>> 16) & 255, (v >>> 24) & 255];
for (const f of files) {
const name = enc.encode(f.name), crc = crc32(f.data), size = f.data.length;
const local = new Uint8Array([...u32(0x04034b50), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(0), ...u16(0x21),
...u32(crc), ...u32(size), ...u32(size), ...u16(name.length), ...u16(0)]);
parts.push(local, name, f.data);
central.push(new Uint8Array([...u32(0x02014b50), ...u16(20), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(0), ...u16(0x21),
...u32(crc), ...u32(size), ...u32(size), ...u16(name.length), ...u16(0), ...u16(0), ...u16(0), ...u16(0), ...u32(0), ...u32(offset)]), name);
offset += local.length + name.length + size;
}
const cdSize = central.reduce((s, p) => s + p.length, 0);
const end = new Uint8Array([...u32(0x06054b50), ...u16(0), ...u16(0), ...u16(files.length), ...u16(files.length), ...u32(cdSize), ...u32(offset), ...u16(0)]);
const all = [...parts, ...central, end], out = new Uint8Array(all.reduce((s, p) => s + p.length, 0));
let p = 0; for (const a of all) { out.set(a, p); p += a.length; }
return out;
}
const KF = { gray, frameDiff, sharpness, brightness, thresholdFor, pickScenes, sampleTimes, fmtTime, crc32, zip };
root.KF = KF;
if (typeof module !== "undefined" && module.exports) module.exports = KF;
})(typeof window !== "undefined" ? window : globalThis);