// video-keyframes page. Plain script (no modules, no fetch of our own files except the optional sample),
// so it works offline and inside sandboxed frames. Uses KF from core.js.
(function () {
"use strict";
const $ = (id) => document.getElementById(id);
const video = $("video"), SMALL_W = 64, SMALL_H = 36, SHARP_W = 192, SHARP_H = 108;
const small = document.createElement("canvas"), sharpC = document.createElement("canvas");
small.width = SMALL_W; small.height = SMALL_H; sharpC.width = SHARP_W; sharpC.height = SHARP_H;
const sctx = small.getContext("2d", { willReadFrequently: true }), hctx = sharpC.getContext("2d", { willReadFrequently: true });
let fileName = "video", frames = [], stopFlag = false, busy = false, objectUrl = null, bigUrl = null;
function status(t, kind = "") { $("status").textContent = t; $("status").className = "status " + kind; }
function load(src, name) {
if (objectUrl) URL.revokeObjectURL(objectUrl);
objectUrl = src.startsWith("blob:") ? src : null;
fileName = (name || "video").replace(/\.[^.]+$/, "").replace(/[^\w.-]+/g, "_").slice(0, 60) || "video";
$("go").disabled = true; $("grab").disabled = true;
status("Opening the video…");
// a web address (the sample) must be loaded with CORS, or the canvas would be "tainted" in sandboxed frames
if (src.startsWith("blob:")) video.removeAttribute("crossorigin"); else video.crossOrigin = "anonymous";
video.src = src;
}
video.addEventListener("loadedmetadata", () => {
$("info").textContent = `${video.videoWidth}×${video.videoHeight}, ${KF.fmtTime(video.duration)}`;
$("go").disabled = false; $("grab").disabled = false;
status("Ready. Choose how to find frames, then press Find keyframes.", "ok");
});
video.addEventListener("error", () => status("Your browser can't play this file. Convert it to MP4 (H.264) and try again.", "err"));
// Seek, then wait until the new frame is actually ready to draw: "seeked" can fire before it is,
// so where the browser supports it we also wait for requestVideoFrameCallback (with a short fallback).
function seek(t) {
return new Promise((res) => {
let settled = false;
const finish = () => { if (!settled) { settled = true; res(); } };
const onSeeked = () => {
video.removeEventListener("seeked", onSeeked);
if (video.requestVideoFrameCallback) { video.requestVideoFrameCallback(() => finish()); setTimeout(finish, 250); }
else setTimeout(finish, 30);
};
video.addEventListener("seeked", onSeeked);
setTimeout(() => { video.removeEventListener("seeked", onSeeked); finish(); }, 3000); // never hang on a bad seek
video.currentTime = Math.min(t, Math.max(0, video.duration - 0.001));
});
}
function measure() {
sctx.drawImage(video, 0, 0, SMALL_W, SMALL_H);
hctx.drawImage(video, 0, 0, SHARP_W, SHARP_H);
const g = KF.gray(sctx.getImageData(0, 0, SMALL_W, SMALL_H).data);
const h = KF.gray(hctx.getImageData(0, 0, SHARP_W, SHARP_H).data);
return { g, sharp: KF.sharpness(h, SHARP_W, SHARP_H), bright: KF.brightness(g) };
}
// Full-resolution frame at the current position, kept as a compressed PNG Blob (a 1080p canvas would hold ~8 MB).
const MAX_FRAMES = 200;
async function capture(t, how) {
const c = document.createElement("canvas");
c.width = video.videoWidth; c.height = video.videoHeight;
c.getContext("2d").drawImage(video, 0, 0);
const th = document.createElement("canvas"), tw = 320;
th.width = tw; th.height = Math.round(tw * c.height / c.width);
th.getContext("2d").drawImage(c, 0, 0, th.width, th.height);
const blob = await new Promise((r) => c.toBlob(r, "image/png"));
c.width = c.height = 0; // let the full-size canvas go
return { t, how, blob, thumb: th.toDataURL("image/jpeg", 0.85) };
}
async function run() {
if (busy) return; busy = true; stopFlag = false;
$("go").disabled = true; $("stop").hidden = false; $("prog").hidden = false; video.pause();
try {
const mode = document.querySelector("input[name=mode]:checked").value;
const found = []; let capped = false, stoppedEarly = false;
if (mode === "every") {
const step = Math.max(0.5, +$("every").value || 5), times = KF.sampleTimes(video.duration, step, 2000);
for (let i = 0; i < times.length && !stopFlag; i++) {
if (frames.length + found.length >= MAX_FRAMES) { capped = true; break; }
await seek(times[i]); const m = measure(); found.push(Object.assign(await capture(times[i], `every ${step} s`), { g: m.g }));
$("prog").value = (i + 1) / times.length; status(`Capturing ${i + 1} of ${times.length}…`);
}
} else {
const times = KF.sampleTimes(video.duration, 0.25, 1500), samples = [];
let prev = null;
for (let i = 0; i < times.length && !stopFlag; i++) {
await seek(times[i]);
const m = measure();
samples.push({ t: times[i], diff: prev ? KF.frameDiff(prev, m.g) : 1, sharp: m.sharp, bright: m.bright });
prev = m.g;
if (i % 4 === 0) { $("prog").value = (i + 1) / times.length * 0.9; status(`Scanning ${KF.fmtTime(times[i])} of ${KF.fmtTime(video.duration)}…`); }
}
window.__kfSamples = samples; // for debugging and tests
stoppedEarly = stopFlag; stopFlag = false; // Stop ends the scan; the scenes found so far are still captured
if (stale(samples)) staleHelp();
const step = times.length > 1 ? times[1] - times[0] : 0.25;
const picks = KF.pickScenes(samples, { threshold: KF.thresholdFor(+$("sens").value), minGap: Math.max(1, step * 2), window: 3 });
for (let k = 0; k < picks.length && !stopFlag; k++) {
if (frames.length + found.length >= MAX_FRAMES) { capped = true; break; }
const t = samples[picks[k]].t;
await seek(t); found.push(await capture(t, "scene change"));
$("prog").value = 0.9 + 0.1 * (k + 1) / picks.length;
}
}
const looksStale = mode === "every" ? found.length > 8 && found.slice(1).every((f, i) => KF.frameDiff(f.g, found[i].g) === 0)
: stale(window.__kfSamples || []);
frames = frames.concat(found).sort((a, b) => a.t - b.t);
render();
if (looksStale) staleHelp();
else status((stopFlag || stoppedEarly ? `Stopped early. ${found.length} frames kept.` : `Done: ${found.length} frames. The video was read in this browser and not uploaded.`) +
(capped ? ` The limit is ${MAX_FRAMES} frames at a time: download or clear some, then continue.` : ""), "ok");
} catch (e) { status("Something went wrong: " + e.message, "err"); }
finally { busy = false; $("go").disabled = false; $("stop").hidden = true; $("prog").hidden = true; }
}
// Every sample showed exactly the same picture. Either the video really is one still image, or the browser isn't
// handing this page new frames (this can happen when it is shown inside another page). Say so, and offer a fix.
function stale(samples) {
return samples.length > 8 && video.duration > 3 && samples.slice(1).every((x) => x.diff === 0);
}
function staleHelp() {
const own = location.href.split("?")[0];
$("info").innerHTML = "";
status("Every sample showed exactly the same picture. If the video does change, your browser may not be handing this page new frames (this can happen when the tool is shown inside another page): open it in its own tab and try again.", "err");
const a = document.createElement("a"); a.href = own; a.target = "_blank"; a.rel = "noopener"; a.textContent = "Open video-keyframes in its own tab";
$("info").appendChild(a);
}
const ENGINES = [["Google Lens", "https://lens.google.com/"], ["Bing", "https://www.bing.com/images"],
["Yandex", "https://yandex.com/images/"], ["TinEye", "https://tineye.com/"]];
function render() {
$("out").hidden = frames.length === 0;
$("count").textContent = `${frames.length} keyframe${frames.length === 1 ? "" : "s"}`;
$("frames").innerHTML = "";
frames.forEach((f, i) => {
const fig = document.createElement("figure");
fig.innerHTML = `