File size: 12,689 Bytes
5dba712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e701140
5dba712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// 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 = `<button class="thumb" type="button" aria-label="View frame at ${KF.fmtTime(f.t)} full size"><img alt="Frame at ${KF.fmtTime(f.t)}" src="${f.thumb}"></button>
        <figcaption><span class="mono">${KF.fmtTime(f.t)}</span> <span class="how">${f.how}</span></figcaption>
        <div class="row small"><button type="button" data-a="png" aria-label="Download the frame at ${KF.fmtTime(f.t)} as PNG">PNG</button><button type="button" data-a="copy" aria-label="Copy the frame at ${KF.fmtTime(f.t)}">Copy</button>
        <button type="button" data-a="seek" title="Show this moment in the video" aria-label="Show ${KF.fmtTime(f.t)} in the video">Show</button><button type="button" data-a="del" aria-label="Remove the frame at ${KF.fmtTime(f.t)}">✕</button></div>
        <div class="engines">Search: ${ENGINES.map(([n, u]) => `<a href="${u}" target="_blank" rel="noopener">${n}</a>`).join(" · ")}</div>`;
      fig.querySelector(".thumb").onclick = () => {
        if (bigUrl) URL.revokeObjectURL(bigUrl); bigUrl = URL.createObjectURL(f.blob);
        $("big").src = bigUrl; $("big").alt = `Frame at ${KF.fmtTime(f.t)}`; $("viewer").showModal(); };
      fig.querySelector("[data-a=png]").onclick = () => save(f.blob, `${fileName}_${KF.fmtTime(f.t).replace(/:/g, "-")}.png`);
      fig.querySelector("[data-a=copy]").onclick = async () => {
        try { await navigator.clipboard.write([new ClipboardItem({ "image/png": f.blob })]); status(`Frame at ${KF.fmtTime(f.t)} copied. Paste it into the search engine.`, "ok"); }
        catch (_) { status("This browser didn't allow copying images. Use PNG to download the frame instead.", "err"); }
      };
      fig.querySelector("[data-a=seek]").onclick = () => { video.currentTime = f.t; video.scrollIntoView({ behavior: "smooth", block: "center" }); };
      fig.querySelector("[data-a=del]").onclick = () => { frames.splice(i, 1); render(); };
      $("frames").appendChild(fig);
    });
  }

  function save(blob, name) {
    const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name;
    document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 60000);
  }

  async function zipAll() {
    status("Preparing the ZIP…");
    const files = [], lines = ["file,time,found_by"], used = new Set();
    for (const f of frames) {
      let name = `${fileName}_${KF.fmtTime(f.t).replace(/:/g, "-")}.png`;
      for (let n = 2; used.has(name); n++) name = `${fileName}_${KF.fmtTime(f.t).replace(/:/g, "-")}_${n}.png`;
      used.add(name);
      files.push({ name, data: new Uint8Array(await f.blob.arrayBuffer()) }); lines.push(`${name},${KF.fmtTime(f.t)},${f.how}`);
    }
    files.push({ name: "frames.csv", data: new TextEncoder().encode(lines.join("\n") + "\n") });
    save(new Blob([KF.zip(files)], { type: "application/zip" }), `${fileName}_keyframes.zip`);
    status(`ZIP of ${frames.length} frames saved.`, "ok");
  }

  $("file").addEventListener("change", (e) => { const f = e.target.files[0]; if (f) load(URL.createObjectURL(f), f.name); });
  const drop = $("drop");
  ["dragenter", "dragover"].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.add("over"); }));
  ["dragleave", "drop"].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.remove("over"); }));
  drop.addEventListener("drop", (e) => { const f = e.dataTransfer.files[0]; if (f) load(URL.createObjectURL(f), f.name); });
  $("sample").onclick = () => load("examples/expo-sample.mp4", "expo-sample.mp4");
  $("sens").oninput = () => { $("sensOut").textContent = $("sens").value; };
  $("go").onclick = run;
  $("stop").onclick = () => { stopFlag = true; };
  $("grab").onclick = async () => {
    if (video.readyState < 2) return;
    if (frames.length >= MAX_FRAMES) { status(`The limit is ${MAX_FRAMES} frames at a time: download or clear some first.`, "err"); return; }
    video.pause(); frames.push(await capture(video.currentTime, "by hand")); frames.sort((a, b) => a.t - b.t); render(); };
  $("zip").onclick = zipAll;
  $("clear").onclick = () => { frames = []; render(); };

  // ?demo opens the sample and finds its keyframes straight away (a one-click demo link)
  if (new URLSearchParams(location.search).has("demo")) {
    video.addEventListener("loadedmetadata", () => setTimeout(run, 50), { once: true });
    load("examples/expo-sample.mp4", "expo-sample.mp4");
  }
})();