HotSight / html /sync-video-player.html
hotsight's picture
Super-squash branch 'main' using huggingface_hub
4e6a175
Raw History Blame Contribute Delete
46.3 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Synchronized Dual Video Player (WebCodecs)</title>
<!-- mp4box.js vendored locally (0.5.x "all" bundle): exposes the UMD global
`MP4Box` (createFile only) and a separate global `DataStream`. -->
<script src="mp4box.all.min.js"></script>
<style>
:root {
--bg: #0e0f13; --panel: #191b22; --panel-2: #21242d; --border: #2c303b;
--text: #e6e8ee; --muted: #9aa0ac; --accent: #4f8cff; --accent-2: #3a6fd8; --danger: #ff5a5a;
color-scheme: dark;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text);
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; height: 100%; }
body { display: flex; flex-direction: column; height: 100vh; }
header { padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--border);
display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
header h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: .2px; }
.filepaths { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }
.filepath { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--muted); min-width: 0; }
.fp-tag { color: var(--accent); font-weight: 600; flex: none; width: 30px; }
.fp-path { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; direction: rtl; text-align: left; }
.loaders { display: flex; gap: 10px; flex-wrap: wrap; }
.loader label { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); }
.file-btn { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
padding: 6px 10px; border-radius: 7px; cursor: pointer; font-size: 12px; }
.file-btn:hover { border-color: var(--accent); }
input[type=file] { display: none; }
/* Codec / WebCodecs error banner */
.error { display: none; margin: 8px 16px 0; padding: 10px 14px; background: #2a1416;
border: 1px solid #6b2b30; border-radius: 8px; color: #ffd7da; font-size: 12px; white-space: pre-wrap; }
.error.show { display: block; }
main { flex: 1; display: flex; padding: 8px; min-height: 0; }
.stage { position: relative; flex: 1; width: 100%; background: #000; border: 1px solid var(--border);
border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; min-height: 0; }
/* #scene wraps the RGB canvas + IR panel; scroll-zoom / right-drag-pan apply a
single transform here so the IR overlay stays locked to the RGB underneath. */
#scene { position: absolute; inset: 0; transform-origin: 0 0; will-change: transform; }
#scene > canvas { width: 100%; height: 100%; object-fit: contain; background: #000; display: block; }
.stage .badge { position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,.6); color: #fff;
padding: 3px 8px; border-radius: 6px; font-size: 11px; pointer-events: none; z-index: 2; }
.ftime { font-variant-numeric: tabular-nums; color: var(--accent); margin-left: 4px; }
/* IR size/position readout (top-right of the panel; unaffected by IR opacity) */
.ir-panel .geom { left: auto; right: 8px; font-size: 10px; font-variant-numeric: tabular-nums; }
/* IR geometry input fields */
.geo { display: inline-flex; align-items: center; gap: 3px; }
.geolab { font-size: 11px; color: var(--muted); }
input[type=number].geoinput { width: 54px; }
/* Indexing (demux) overlay: spinner + live % over the stage */
.loading { position: absolute; inset: 0; z-index: 10; display: none; pointer-events: none;
flex-direction: column; align-items: center; justify-content: center; gap: 12px;
background: rgba(14,15,19,.72); color: var(--text); font-size: 13px; }
.loading.show { display: flex; }
.loading .spinner { width: 34px; height: 34px; border-radius: 50%;
border: 3px solid var(--panel-2); border-top-color: var(--accent); animation: spin .8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.loading .pct { color: var(--accent); font-variant-numeric: tabular-nums; }
.stage .empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
color: var(--muted); font-size: 13px; text-align: center; padding: 20px; pointer-events: none; }
.stage .drop-hint { opacity: .8; }
.stage.dragover { outline: 2px dashed var(--accent); outline-offset: -6px; }
/* IR overlay panel (sits on top of the full-size RGB) */
.ir-panel { position: absolute; left: 0; top: 0; width: 320px; height: 240px;
border: 2px solid var(--accent); border-radius: 6px; overflow: hidden; background: transparent;
box-shadow: 0 6px 24px rgba(0,0,0,.55); cursor: move; touch-action: none; z-index: 5; }
.ir-panel.ir-hidden { opacity: 0; pointer-events: none; transform: translateX(calc(-100vw - 100% - 32px)); }
.ir-panel > canvas { width: 100%; height: 100%; object-fit: contain; display: block; background: #000;
opacity: var(--ir-opacity, 1); }
.ir-panel.dragover { outline: 2px dashed var(--accent); outline-offset: -4px; }
.ir-resize { position: absolute; right: 0; bottom: 0; width: 18px; height: 18px; background: var(--accent);
border-top-left-radius: 6px; cursor: nwse-resize; touch-action: none; z-index: 6; }
.ir-resize::before { content: ""; position: absolute; right: 3px; bottom: 3px; width: 6px; height: 6px;
border-right: 2px solid #fff; border-bottom: 2px solid #fff; }
/* Counter-scale the IR panel's chrome so it stays a constant on-screen size
while the scene is zoomed (--zoom is set on #scene by applyView()), keeping
the border thin and the badges/handle from ballooning. */
.ir-panel { border-width: calc(2px / var(--zoom, 1)); }
.ir-panel .badge { transform: scale(calc(1 / var(--zoom, 1))); transform-origin: top left; }
.ir-panel .geom { transform-origin: top right; }
.ir-resize { transform: scale(calc(1 / var(--zoom, 1))); transform-origin: bottom right; }
footer { background: var(--panel); border-top: 1px solid var(--border); padding: 10px 16px 14px;
display: flex; flex-direction: column; gap: 10px; }
.scrubber-row { display: flex; align-items: center; gap: 12px; }
.time { font-variant-numeric: tabular-nums; font-size: 12px; color: var(--muted); min-width: 100px; }
.time.right { text-align: right; }
input[type=range].seek { flex: 1; height: 6px; -webkit-appearance: none; appearance: none;
background: var(--panel-2); border-radius: 4px; outline: none; cursor: pointer; }
input[type=range].seek::-webkit-slider-thumb { -webkit-appearance: none; appearance: none;
width: 15px; height: 15px; border-radius: 50%; background: var(--accent); cursor: pointer; border: 2px solid #fff; }
input[type=range].seek::-moz-range-thumb { width: 15px; height: 15px; border-radius: 50%;
background: var(--accent); cursor: pointer; border: 2px solid #fff; }
.controls { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
button.ctrl { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
padding: 8px 12px; border-radius: 8px; cursor: pointer; font-size: 13px; min-width: 40px;
display: inline-flex; align-items: center; justify-content: center; gap: 6px; }
button.ctrl:hover:not(:disabled) { border-color: var(--accent); background: #262a34; }
button.ctrl:disabled { opacity: .4; cursor: not-allowed; }
button.ctrl.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
button.ctrl.primary:hover:not(:disabled) { background: var(--accent-2); }
.group { display: flex; align-items: center; gap: 8px; padding-left: 12px; margin-left: 4px; border-left: 1px solid var(--border); }
.group:first-child { border-left: none; padding-left: 0; margin-left: 0; }
.group label { font-size: 12px; color: var(--muted); }
input[type=number] { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
border-radius: 7px; padding: 6px 8px; font-size: 12px; width: 76px; }
input[type=range].ir-opacity { width: 110px; height: 6px; -webkit-appearance: none; appearance: none;
background: var(--panel-2); border-radius: 4px; outline: none; cursor: pointer; }
input[type=range].ir-opacity::-webkit-slider-thumb { -webkit-appearance: none; appearance: none;
width: 14px; height: 14px; border-radius: 50%; background: var(--accent); cursor: pointer; border: 2px solid #fff; }
input[type=range].ir-opacity::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%;
background: var(--accent); cursor: pointer; border: 2px solid #fff; }
input[type=range].ir-opacity:disabled { opacity: .45; cursor: not-allowed; }
.speed-badge { font-size: 12px; color: var(--accent); font-variant-numeric: tabular-nums; min-width: 42px; text-align: center; }
.opacity-badge { font-size: 12px; color: var(--accent); font-variant-numeric: tabular-nums; min-width: 38px; text-align: right; }
.spacer { flex: 1; }
kbd { background: var(--panel-2); border: 1px solid var(--border); border-bottom-width: 2px; border-radius: 4px;
padding: 1px 5px; font-size: 11px; font-family: inherit; color: var(--text); }
</style>
</head>
<body>
<header>
<h1>⏯ Synchronized Dual Video Player</h1>
<div class="loaders">
<div class="loader"><label><span class="file-btn">📁 Load RGB</span><input type="file" id="fileA" accept="video/mp4,video/quicktime,.mp4,.mov,.m4v"></label></div>
<div class="loader"><label><span class="file-btn">📁 Load IR</span><input type="file" id="fileB" accept="video/mp4,video/quicktime,.mp4,.mov,.m4v"></label></div>
</div>
<div class="filepaths">
<div class="filepath"><span class="fp-tag">RGB</span><span class="fp-path" id="pathA" title="No file loaded">—</span></div>
<div class="filepath"><span class="fp-tag">IR</span><span class="fp-path" id="pathB" title="No file loaded">—</span></div>
</div>
</header>
<div id="error" class="error"></div>
<main id="main">
<div class="stage" id="stageRGB">
<span class="badge">RGB<span class="ftime" id="tA">—</span></span>
<!-- Everything inside #scene zooms/pans together (RGB + IR overlay). -->
<div id="scene">
<canvas id="canvasA"></canvas>
<div class="ir-panel" id="irPanel">
<span class="badge">IR<span class="ftime" id="tB">—</span></span>
<span class="badge geom" id="irGeom">—</span>
<canvas id="canvasB"></canvas>
<div class="empty drop-hint" id="emptyB">Drop IR video here</div>
<div class="ir-resize" id="irResize" title="Drag to resize (keeps aspect ratio)"></div>
</div>
</div>
<div class="empty drop-hint" id="emptyA">Click “Load RGB” or drop an RGB video here</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<div><span id="loadingLabel">Indexing…</span> <span class="pct" id="loadingPct"></span></div>
</div>
</div>
</main>
<footer>
<div class="scrubber-row">
<span class="time" id="curTime">0:00.0</span>
<input type="range" class="seek" id="seek" min="0" max="1" value="0" step="0.01" disabled>
<span class="time right" id="durTime">0:00.0</span>
</div>
<div class="controls">
<div class="group">
<button class="ctrl" id="btnStart" title="Restart (Home)" disabled>⏮</button>
<button class="ctrl" id="btnBack" title="Back 1s (←)" disabled>⏪ 1s</button>
<button class="ctrl primary" id="btnPlay" title="Play / Pause (Space)" disabled>▶ Play</button>
<button class="ctrl" id="btnFwd" title="Forward 1s (→)" disabled>1s ⏩</button>
<button class="ctrl" id="btnStop" title="Stop (reset to start)" disabled>⏹ Stop</button>
</div>
<div class="group">
<label>Speed</label>
<button class="ctrl" id="btnSlower" title="Slower" disabled>−</button>
<span class="speed-badge" id="speedBadge">1.0×</span>
<button class="ctrl" id="btnFaster" title="Faster" disabled>+</button>
</div>
<div class="group">
<label title="IR time = RGB time + offset">IR offset (s)</label>
<input type="number" id="offset" value="0" step="0.01" disabled>
</div>
<div class="spacer"></div>
<div class="group">
<label for="irOpacity">IR opacity</label>
<input type="range" class="ir-opacity" id="irOpacity" min="0" max="100" value="80" step="1" disabled>
<span class="opacity-badge" id="irOpacityValue">80%</span>
<button class="ctrl" id="btnToggleIR" title="Hide / Show IR overlay (I)" disabled>Hide IR</button>
<button class="ctrl" id="btnCenterIR" title="Center IR over RGB">⊹ Center IR</button>
<button class="ctrl" id="btnResetIR" title="Reset IR to 3/4 size, centered">↺ Reset IR</button>
</div>
<div class="group">
<label title="IR panel size &amp; position in stage pixels">IR box</label>
<span class="geo"><span class="geolab">W</span><input type="number" class="geoinput" id="irW" title="width (px)"></span>
<span class="geo"><span class="geolab">H</span><input type="number" class="geoinput" id="irH" title="height (px)"></span>
<span class="geo"><span class="geolab">X</span><input type="number" class="geoinput" id="irX" title="left (px)"></span>
<span class="geo"><span class="geolab">Y</span><input type="number" class="geoinput" id="irY" title="top (px)"></span>
</div>
</div>
<div class="hint" style="font-size:11px;color:var(--muted)">
Shortcuts: <kbd>Space</kbd> play/pause · <kbd>←</kbd>/<kbd>→</kbd> skip 1s ·
<kbd>↑</kbd>/<kbd>↓</kbd> speed · <kbd>Home</kbd> restart · <kbd>S</kbd> stop · <kbd>I</kbd> hide/show IR · <kbd>Enter</kbd> edit offset ·
<kbd>scroll</kbd> zoom · <kbd>right-drag</kbd> pan · <kbd>double-click</kbd>/<kbd>0</kbd> reset view ·
drag the <span style="color:var(--accent)">IR</span> panel to move it, drag its corner to resize
</div>
</footer>
<script>
"use strict";
// ============================================================================
// ENGINE — WebCodecs + canvas, one shared master clock (see -engine.html for
// the annotated standalone build). This file grafts that engine onto the real
// draggable IR-overlay UI. Units: VideoFrame/chunk timestamps are µs (…Us);
// the clock is seconds.
// ============================================================================
const DECODE_AHEAD_SEC = 0.75, QUEUE_CAP = 8, MAX_BUFFERED = 32;
const SPEEDS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4];
const SKIP_SEC = 1; // skip-button / arrow-key jump amount (seconds)
const $ = (id) => document.getElementById(id);
const clamp = (x, lo, hi) => x < lo ? lo : (x > hi ? hi : x);
const errorEl = $("error");
const showError = (m) => { errorEl.textContent = m; errorEl.classList.add("show"); };
const clearError = () => { errorEl.textContent = ""; errorEl.classList.remove("show"); };
// ---- master clock (derived from performance.now(); window = overlap) --------
class MasterClock {
constructor() { this.playing = false; this.rate = 1; this.anchorWall = performance.now();
this.anchorMedia = 0; this.pausedMedia = 0; this.tStart = 0; this.tEnd = 0; }
get mediaTime() {
const t = this.playing ? (performance.now() - this.anchorWall) / 1000 * this.rate + this.anchorMedia : this.pausedMedia;
return clamp(t, this.tStart, this.tEnd);
}
_reanchor(atMedia) { this.anchorMedia = atMedia; this.anchorWall = performance.now(); }
play() { if (this.playing) return; this._reanchor(this.mediaTime); this.playing = true; }
pause() { if (!this.playing) return; this.pausedMedia = this.mediaTime; this.playing = false; }
seek(t) { t = clamp(t, this.tStart, this.tEnd); this.pausedMedia = t; if (this.playing) this._reanchor(t); }
setRate(r) { if (this.playing) { const t = this.mediaTime; this.rate = r; this._reanchor(t); } else this.rate = r; }
}
// ---- one decoded stream -----------------------------------------------------
class Stream {
constructor(canvasEl, badgeEl) {
this.canvas = canvasEl; this.ctx = canvasEl.getContext("2d", { alpha: false }); this.badge = badgeEl;
this.samples = []; this.frames = []; this.config = null; this.decoder = null;
this.durationSec = 0; this.feedIndex = 0; this.displayW = 0; this.displayH = 0;
this._lastTarget = 0; this._flushing = false; this._flushed = false; this._sizedCanvas = false;
}
async init(track, samples, durationSec, description) {
this.samples = samples; this.durationSec = durationSec;
this.displayW = track.video.width; this.displayH = track.video.height; // refined on first frame
const fourcc = track.codec.split(".")[0];
const needsDesc = (fourcc === "avc1" || fourcc === "hvc1");
this.config = { codec: track.codec, codedWidth: track.video.width, codedHeight: track.video.height, optimizeForLatency: true };
if (needsDesc && description) this.config.description = description;
let support; try { support = await VideoDecoder.isConfigSupported(this.config); } catch (e) { support = { supported: false }; }
if (!support.supported) {
throw new Error("Codec not supported by your browser's VideoDecoder.\n codec: " + track.codec +
"\n size: " + track.video.width + "×" + track.video.height + "\n\n" +
((fourcc === "hvc1" || fourcc === "hev1")
? "This is HEVC/H.265 — Chrome only decodes it with hardware support (no software fallback).\nUse HEVC-capable hardware or transcode to H.264."
: "Try Chrome/Edge desktop over http://localhost, or transcode to H.264."));
}
this.decoder = new VideoDecoder({ output: (f) => this._onFrame(f), error: (e) => this._onError(e) });
this.decoder.addEventListener("dequeue", () => this.pump(this._lastTarget));
this.decoder.configure(this.config);
}
_onFrame(frame) {
if (!this._sizedCanvas) {
const w = frame.displayWidth || frame.codedWidth, h = frame.displayHeight || frame.codedHeight;
const changed = (w !== this.displayW || h !== this.displayH); // true frame dims ≠ container track dims
this.displayW = w; this.displayH = h;
this.canvas.width = w; this.canvas.height = h; this._sizedCanvas = true;
if (changed && typeof onStreamRefined === "function") onStreamRefined(this); // re-fit overlay to real aspect
}
const a = this.frames;
if (a.length === 0 || frame.timestamp >= a[a.length - 1].timestamp) a.push(frame);
else { let i = a.length; while (i > 0 && a[i - 1].timestamp > frame.timestamp) i--; a.splice(i, 0, frame); }
}
get lastBufferedSec() { const a = this.frames; return a.length ? a[a.length - 1].timestamp / 1e6 : -Infinity; }
pump(target) {
this._lastTarget = target;
if (!this.decoder || this.decoder.state !== "configured") return;
while (this.feedIndex < this.samples.length) {
if (this.frames.length && (this.lastBufferedSec - target) >= DECODE_AHEAD_SEC) break;
if (this.decoder.decodeQueueSize >= QUEUE_CAP) break;
if (this.frames.length >= MAX_BUFFERED) break;
const s = this.samples[this.feedIndex++];
this.decoder.decode(new EncodedVideoChunk({ type: s.isKey ? "key" : "delta", timestamp: s.ctsUs, duration: s.durUs, data: s.data }));
}
if (this.feedIndex >= this.samples.length && !this._flushing && !this._flushed) {
this._flushing = true;
this.decoder.flush().then(() => { this._flushed = true; })
.catch((e) => { if (e && e.name !== "AbortError") console.warn(e); }).finally(() => { this._flushing = false; });
}
}
present(target) {
const a = this.frames; if (a.length === 0) return;
const targetUs = target * 1e6;
let lo = 0, hi = a.length - 1, idx = -1;
while (lo <= hi) { const mid = (lo + hi) >> 1; if (a[mid].timestamp <= targetUs) { idx = mid; lo = mid + 1; } else hi = mid - 1; }
if (idx === -1) return;
if (idx > 0) { for (let i = 0; i < idx; i++) a[i].close(); a.splice(0, idx); }
const atEnd = this.feedIndex >= this.samples.length && this._flushed;
if (a.length === 1 && a[0].timestamp < targetUs && !atEnd) return;
this.ctx.drawImage(a[0], 0, 0, this.canvas.width, this.canvas.height);
this.badge.textContent = (a[0].timestamp / 1e6).toFixed(3) + "s";
}
_startAt(targetSec) {
this._flushing = false; this._flushed = false;
for (const f of this.frames) { try { f.close(); } catch {} } this.frames.length = 0;
const targetUs = targetSec * 1e6; let start = 0;
for (let i = 0; i < this.samples.length; i++) {
if (this.samples[i].isKey && this.samples[i].ctsUs <= targetUs) start = i;
else if (this.samples[i].ctsUs > targetUs) break;
}
this.feedIndex = start; this.pump(targetSec);
}
seekTo(targetSec) { if (!this.decoder || this.decoder.state === "closed") return; this.decoder.reset(); this.decoder.configure(this.config); this._startAt(targetSec); }
rebuild(targetSec) {
try { if (this.decoder && this.decoder.state !== "closed") this.decoder.close(); } catch {}
this.decoder = new VideoDecoder({ output: (f) => this._onFrame(f), error: (e) => this._onError(e) });
this.decoder.addEventListener("dequeue", () => this.pump(this._lastTarget));
this.decoder.configure(this.config); this._startAt(targetSec);
}
_onError(e) { console.warn("VideoDecoder error (will auto-recover):", e && e.message); }
isDead() { return !this.decoder || this.decoder.state === "closed"; }
destroy() {
for (const f of this.frames) { try { f.close(); } catch {} } this.frames.length = 0;
try { if (this.decoder && this.decoder.state !== "closed") this.decoder.close(); } catch {}
this.decoder = null;
}
}
// ---- demux glue (mp4box.js) -------------------------------------------------
function getDescription(mp4file, trackId) {
const trak = mp4file.getTrackById(trackId);
for (const entry of trak.mdia.minf.stbl.stsd.entries) {
const box = entry.avcC || entry.hvcC || entry.vpcC || entry.av1C;
if (box) { const ds = new DataStream(undefined, 0, DataStream.BIG_ENDIAN); box.write(ds); return new Uint8Array(ds.buffer, 8); }
}
return null;
}
function demuxFile(file, onProgress) {
return new Promise((resolve, reject) => {
const mp4file = MP4Box.createFile(); const collected = [];
let track = null, expected = 0, description = null, durationSec = 0;
mp4file.onError = (e) => reject(new Error("mp4box parse error: " + e));
mp4file.onReady = (info) => {
if (!info.videoTracks || !info.videoTracks.length) { reject(new Error("No video track in this file.")); return; }
track = info.videoTracks[0]; expected = track.nb_samples;
description = getDescription(mp4file, track.id); durationSec = info.duration / info.timescale;
mp4file.onSamples = (id, user, samples) => {
for (const s of samples) collected.push({
ctsUs: Math.round((1e6 * s.cts) / s.timescale), durUs: Math.round((1e6 * s.duration) / s.timescale),
isKey: !!s.is_sync, data: s.data.slice() });
if (collected.length >= expected) resolve({ track, samples: collected, durationSec, description });
};
mp4file.setExtractionOptions(track.id, null, { nbSamples: expected }); mp4file.start();
};
const CHUNK = 16 * 1024 * 1024;
(async () => {
try { let pos = 0; while (pos < file.size) { const end = Math.min(pos + CHUNK, file.size);
const buf = await file.slice(pos, end).arrayBuffer(); buf.fileStart = pos; mp4file.appendBuffer(buf); pos = end;
if (onProgress) onProgress(pos / file.size); }
mp4file.flush(); } catch (e) { reject(e); }
})();
});
}
// ============================================================================
// PLAYER STATE + WIRING
// ============================================================================
const clock = new MasterClock();
let streamA = null, streamB = null; // RGB, IR
let genA = 0, genB = 0; // per-side load generation (rapid re-pick guard)
let offset = 0; // IR time = RGB time + offset
let speedIndex = SPEEDS.indexOf(1);
let raf = 0, scrubbing = false;
const canvasA = $("canvasA"), canvasB = $("canvasB"), tA = $("tA"), tB = $("tB");
const seek = $("seek"), curTime = $("curTime"), durTime = $("durTime");
const btnPlay = $("btnPlay"), speedBadge = $("speedBadge"), offsetInput = $("offset");
const irOpacityInput = $("irOpacity"), irOpacityValue = $("irOpacityValue"), btnToggleIR = $("btnToggleIR");
const pathA = $("pathA"), pathB = $("pathB");
const loadingEl = $("loading"), loadingLabel = $("loadingLabel"), loadingPct = $("loadingPct");
function showLoading(which) { loadingLabel.textContent = "Indexing " + (which === "A" ? "RGB" : "IR") + "…"; loadingPct.textContent = ""; loadingEl.classList.add("show"); }
function setLoadingPct(frac) { loadingPct.textContent = Math.round(clamp(frac, 0, 1) * 100) + "%"; }
function hideLoading() { loadingEl.classList.remove("show"); }
function fmt(t) { if (!isFinite(t) || t < 0) t = 0; const m = Math.floor(t / 60), s = Math.floor(t % 60), d = Math.floor((t * 10) % 10);
return `${m}:${String(s).padStart(2, "0")}.${d}`; }
const anyLoaded = () => !!(streamA || streamB);
// Playable window in master (RGB) time = the OVERLAP where both clips have real
// content: [ max(0,-offset) , min(A.dur, B.dur-offset) ]. Scrubber/readout are
// 0-based on it, so the shown duration IS the overlap length.
function computeWindow() {
let tStart = 0, tEnd = 0;
if (streamA && streamB) { tStart = Math.max(0, -offset); tEnd = Math.min(streamA.durationSec, streamB.durationSec - offset); }
else if (streamA) { tEnd = streamA.durationSec; }
else if (streamB) { tStart = Math.max(0, -offset); tEnd = streamB.durationSec - offset; }
if (tEnd < tStart) tEnd = tStart;
clock.tStart = tStart; clock.tEnd = tEnd;
seek.min = "0"; seek.max = String((tEnd - tStart) || 1);
}
function setControlsEnabled(on) {
document.querySelectorAll("button.ctrl").forEach(b => b.disabled = !on);
seek.disabled = !on; offsetInput.disabled = !on; irOpacityInput.disabled = !on;
}
function updatePlayBtn() { btnPlay.textContent = clock.playing ? "⏸ Pause" : "▶ Play"; }
function updateReadout() {
const t = clock.mediaTime, p = t - clock.tStart, len = clock.tEnd - clock.tStart;
curTime.textContent = fmt(p); durTime.textContent = fmt(len);
if (!scrubbing && len > 0) seek.value = String(p);
updatePlayBtn();
}
// ---- decoder-reclaim recovery (AFK / hidden tab / idle) ---------------------
// Rebuild any decoder Chrome reclaimed while we were away. Per-stream cooldown so
// each recovers promptly (a shared throttle could defer the 2nd one) while a truly
// dead codec still can't spin.
function recoverDecoders() {
const now = performance.now(), t = clock.mediaTime;
const tryRebuild = (s, target) => {
if (s && s.isDead() && (now - (s._lastRebuild || 0) > 800)) { s._lastRebuild = now; s.rebuild(target); }
};
try {
if (streamA) tryRebuild(streamA, clamp(t, 0, streamA.durationSec));
if (streamB) tryRebuild(streamB, clamp(t + offset, 0, streamB.durationSec));
} catch (e) { showError("The video decoder was reclaimed and could not be restarted.\nReload the page.\n" + (e && e.message || e)); }
}
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") { if (clock.playing) { clock.pause(); updatePlayBtn(); } }
else recoverDecoders();
});
// ---- the one render loop ----------------------------------------------------
function loop() {
raf = requestAnimationFrame(loop);
if ((streamA && streamA.isDead()) || (streamB && streamB.isDead())) recoverDecoders();
let t = clock.mediaTime;
if (clock.playing && clock.tEnd > clock.tStart && t >= clock.tEnd) { clock.seek(clock.tEnd); clock.pause(); updatePlayBtn(); t = clock.mediaTime; }
if (streamA) { const ta = clamp(t, 0, streamA.durationSec); streamA.pump(ta); streamA.present(ta); }
if (streamB) { const tb = clamp(t + offset, 0, streamB.durationSec); streamB.pump(tb); streamB.present(tb); }
updateReadout();
}
// ---- transport --------------------------------------------------------------
function doSeek(t) {
clock.seek(t); const t2 = clock.mediaTime;
if (streamA) streamA.seekTo(clamp(t2, 0, streamA.durationSec));
if (streamB) streamB.seekTo(clamp(t2 + offset, 0, streamB.durationSec));
updateReadout();
}
function play() { if (!anyLoaded() || clock.tEnd <= clock.tStart) return; if (clock.mediaTime >= clock.tEnd) doSeek(clock.tStart); clock.play(); updatePlayBtn(); }
function pause() { clock.pause(); updatePlayBtn(); }
function togglePlay() { if (clock.playing) pause(); else play(); }
function stop() { pause(); doSeek(clock.tStart); }
function skip(d) { doSeek(clock.mediaTime + d); }
function applySpeed() { clock.setRate(SPEEDS[speedIndex]); speedBadge.textContent = SPEEDS[speedIndex].toFixed(2).replace(/0$/, "") + "×"; }
function changeSpeed(dir) { speedIndex = clamp(speedIndex + dir, 0, SPEEDS.length - 1); applySpeed(); }
// ---- file loading -----------------------------------------------------------
async function loadInto(which, file) {
clearError();
const fpEl = which === "A" ? pathA : pathB;
const prevPath = fpEl.textContent, prevTitle = fpEl.title;
const shown = (file.path || file.webkitRelativePath || file.name);
const myGen = (which === "A") ? ++genA : ++genB;
const superseded = () => (which === "A" ? genA : genB) !== myGen;
// Only touch the label while we're the current pick, so a failed/superseded load
// never overwrites the file that actually ended up loaded.
const setLabel = (txt) => { if (!superseded()) { fpEl.textContent = txt; fpEl.title = shown; } };
const restoreLabel = () => { if (!superseded()) { fpEl.textContent = prevPath; fpEl.title = prevTitle; } };
const finishLoading = () => { if (!superseded()) hideLoading(); };
setLabel("indexing… " + shown);
showLoading(which);
if (!("VideoDecoder" in window)) { showError("This browser has no WebCodecs VideoDecoder. Use Chrome/Edge desktop over http://localhost."); restoreLabel(); finishLoading(); return; }
// Free the previous clip on THIS side BEFORE demuxing the new one, so peak RAM
// stays ~one video instead of holding (old video's samples + decoded frames) AND
// (mp4box's copy + our copy) of the new one all at once. Trade-off: if the new
// load fails or is superseded, this side ends up empty rather than showing the
// old clip. Freeing here is safe: destroy()+null are synchronous, so the rAF
// loop (which null-guards streamA/streamB) never sees a torn-down stream.
if (which === "A") { if (streamA) { streamA.destroy(); streamA = null; } $("emptyA").style.display = ""; }
else { if (streamB) { streamB.destroy(); streamB = null; } $("emptyB").style.display = ""; }
let demuxed;
try { demuxed = await demuxFile(file, (frac) => { if (!superseded()) setLoadingPct(frac); }); }
catch (e) { showError("Could not demux the " + which + " file.\n" + e.message); restoreLabel(); finishLoading(); return; }
if (superseded()) { finishLoading(); return; }
const s = new Stream(which === "A" ? canvasA : canvasB, which === "A" ? tA : tB);
try { await s.init(demuxed.track, demuxed.samples, demuxed.durationSec, demuxed.description); }
catch (e) { showError("[" + which + "] " + e.message); s.destroy(); restoreLabel(); finishLoading(); return; }
if (superseded()) { s.destroy(); finishLoading(); return; }
setLabel(shown); // committed — label the file that actually loaded (old one already freed above)
if (which === "A") { streamA = s; $("emptyA").style.display = "none"; }
else { streamB = s; $("emptyB").style.display = "none"; }
// A new upload resets playback settings — current time, IR offset, speed and
// play state — while intentionally KEEPING the IR overlay's size/position/opacity.
clock.pause();
offset = 0; offsetInput.value = "0";
speedIndex = SPEEDS.indexOf(1);
computeWindow();
doSeek(clock.tStart); // jump both streams to the start (tStart = 0)
setControlsEnabled(true); applySpeed(); updatePlayBtn(); updateReadout();
if (!irUserMoved) initIR(); // size IR overlay to the clips' real aspect
if (which === "A") resetView(); // a new RGB scene starts back at fit (1×, no pan)
finishLoading();
if (!raf) raf = requestAnimationFrame(loop);
}
$("fileA").addEventListener("change", (e) => { const f = e.target.files && e.target.files[0]; e.target.blur(); if (f) loadInto("A", f); });
$("fileB").addEventListener("change", (e) => { const f = e.target.files && e.target.files[0]; e.target.blur(); if (f) loadInto("B", f); });
// Drag & drop: RGB onto the stage, IR onto the panel.
function wireDrop(el, which) {
el.addEventListener("dragover", e => { e.preventDefault(); e.stopPropagation(); el.classList.add("dragover"); });
el.addEventListener("dragleave", e => { e.stopPropagation(); el.classList.remove("dragover"); });
el.addEventListener("drop", e => { e.preventDefault(); e.stopPropagation(); el.classList.remove("dragover");
const f = e.dataTransfer.files[0]; if (!f || !f.type.startsWith("video")) return; loadInto(which, f); });
}
wireDrop($("stageRGB"), "A");
wireDrop($("irPanel"), "B");
// ---- control wiring ---------------------------------------------------------
btnPlay.addEventListener("click", togglePlay);
$("btnStop").addEventListener("click", stop);
$("btnStart").addEventListener("click", () => doSeek(clock.tStart));
$("btnBack").addEventListener("click", () => skip(-SKIP_SEC));
$("btnFwd").addEventListener("click", () => skip(SKIP_SEC));
$("btnSlower").addEventListener("click", () => changeSpeed(-1));
$("btnFaster").addEventListener("click", () => changeSpeed(1));
seek.addEventListener("pointerdown", () => { scrubbing = true; });
seek.addEventListener("input", () => { if (anyLoaded()) doSeek(clock.tStart + (parseFloat(seek.value) || 0)); });
// Clear scrubbing on ANY pointer release (even off the slider) so the readout
// never freezes if you drag out and let go.
window.addEventListener("pointerup", () => { scrubbing = false; });
function applyOffset() {
offset = parseFloat(offsetInput.value) || 0;
const before = clock.mediaTime;
computeWindow();
const after = clock.mediaTime; // may be re-clamped by the new overlap window
clock.seek(after);
if (streamA && after !== before) streamA.seekTo(clamp(after, 0, streamA.durationSec)); // RGB only moves if clamped
if (streamB) streamB.seekTo(clamp(after + offset, 0, streamB.durationSec)); // IR always shifts with offset
updateReadout();
}
offsetInput.addEventListener("input", applyOffset);
offsetInput.addEventListener("change", applyOffset);
// Shift = coarse step (0.1), normal = fine (0.01) — for the spinner arrows and ↑/↓.
function setOffsetStep(large) { offsetInput.step = large ? "0.1" : "0.01"; }
offsetInput.addEventListener("pointerdown", e => setOffsetStep(e.shiftKey));
offsetInput.addEventListener("keydown", e => {
setOffsetStep(e.shiftKey && (e.key === "ArrowUp" || e.key === "ArrowDown"));
if (e.key === "Enter") offsetInput.blur(); // return focus to the page so shortcuts work again
});
offsetInput.addEventListener("keyup", () => setOffsetStep(false));
offsetInput.addEventListener("blur", () => setOffsetStep(false));
// ============================================================================
// IR OVERLAY: move / resize (locked aspect) / opacity / hide — operates on the
// #irPanel DIV + a CSS variable, so it is engine-agnostic (unchanged from the
// <video> build except aspect/ box come from the decoded stream dimensions).
// ============================================================================
const stageRGB = $("stageRGB"), irPanel = $("irPanel"), irResize = $("irResize");
const irGeom = $("irGeom"), irW = $("irW"), irH = $("irH"), irX = $("irX"), irY = $("irY");
const IR_MIN = 60;
// Default IR overlay geometry in RGB pixels. initIR() projects it into the
// rendered RGB box so the alignment is independent of the stage/screen size.
const RGB_DEFAULT = { w: 2688, h: 1512 };
const IR_DEFAULT = { x: 312, y: 202, w: 2040, h: 1148 };
let ir = { x: 0, y: 0, w: 0, h: 0 };
let irUserMoved = false, irVisible = true;
// ---- VIEW: scroll = zoom (about cursor), right-drag = pan --------------------
// Zoom/pan the whole #scene (RGB canvas + IR panel together) so the overlay
// stays aligned. `view` is in STAGE pixels: screen = pan + zoom * sceneCoord.
const scene = $("scene");
const view = { zoom: 1, panX: 0, panY: 0 };
const ZOOM_MIN = 1, ZOOM_MAX = 20;
function clampView() {
const sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
view.zoom = clamp(view.zoom, ZOOM_MIN, ZOOM_MAX);
// Keep the scaled scene covering the stage (no black gaps from over-panning).
view.panX = clamp(view.panX, sw * (1 - view.zoom), 0);
view.panY = clamp(view.panY, sh * (1 - view.zoom), 0);
}
function applyView() {
clampView();
scene.style.transform = `translate(${view.panX}px, ${view.panY}px) scale(${view.zoom})`;
scene.style.setProperty("--zoom", view.zoom);
}
function resetView() { view.zoom = 1; view.panX = 0; view.panY = 0; applyView(); }
// Zoom about the cursor: the scene point under the pointer stays put.
function zoomAt(clientX, clientY, factor) {
const r = stageRGB.getBoundingClientRect();
const cx = clientX - r.left, cy = clientY - r.top;
const sx = (cx - view.panX) / view.zoom, sy = (cy - view.panY) / view.zoom;
view.zoom = clamp(view.zoom * factor, ZOOM_MIN, ZOOM_MAX);
view.panX = cx - sx * view.zoom; view.panY = cy - sy * view.zoom;
applyView();
}
stageRGB.addEventListener("wheel", e => {
if (!anyLoaded()) return;
e.preventDefault();
zoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.15 : 1 / 1.15);
}, { passive: false });
// Right-button drag = pan (captured on the stage so it keeps tracking off-panel).
let panDrag = null;
stageRGB.addEventListener("pointerdown", e => {
if (e.button !== 2 || !anyLoaded()) return;
e.preventDefault();
panDrag = { sx: e.clientX, sy: e.clientY, px: view.panX, py: view.panY };
try { stageRGB.setPointerCapture(e.pointerId); } catch {}
});
stageRGB.addEventListener("pointermove", e => {
if (!panDrag) return;
view.panX = panDrag.px + (e.clientX - panDrag.sx);
view.panY = panDrag.py + (e.clientY - panDrag.sy);
applyView();
});
function endPan(e) { if (panDrag) { try { stageRGB.releasePointerCapture(e.pointerId); } catch {} panDrag = null; } }
stageRGB.addEventListener("pointerup", endPan);
stageRGB.addEventListener("pointercancel", endPan);
stageRGB.addEventListener("contextmenu", e => e.preventDefault()); // right-drag would else pop the menu
stageRGB.addEventListener("dblclick", e => { if (anyLoaded()) { e.preventDefault(); resetView(); } });
function irAspect() { if (streamB && streamB.displayW && streamB.displayH) return streamB.displayW / streamB.displayH; return ir.w / ir.h || 4 / 3; }
function rgbBox() {
const sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
const vw = streamA ? streamA.displayW : 0, vh = streamA ? streamA.displayH : 0;
if (streamA && vw && vh) { const scale = Math.min(sw / vw, sh / vh), w = vw * scale, h = vh * scale;
return { left: (sw - w) / 2, top: (sh - h) / 2, width: w, height: h }; }
return { left: 0, top: 0, width: sw, height: sh };
}
function applyIR() {
irPanel.style.left = ir.x + "px"; irPanel.style.top = ir.y + "px"; irPanel.style.width = ir.w + "px"; irPanel.style.height = ir.h + "px";
irGeom.textContent = Math.round(ir.w) + "×" + Math.round(ir.h) + " @ (" + Math.round(ir.x) + ", " + Math.round(ir.y) + ")";
syncGeoInputs();
}
// Keep the W/H/X/Y fields showing the live geometry — but never clobber the one
// being typed in.
function syncGeoInputs() {
const set = (el, v) => { if (el !== document.activeElement) el.value = Math.round(v); };
set(irW, ir.w); set(irH, ir.h); set(irX, ir.x); set(irY, ir.y);
}
// Apply typed/spun field values back onto the panel. W and H are ASPECT-LOCKED
// (each drives the other via irAspect, like the drag-corner); X and Y are free.
function setIRW(w) { irUserMoved = true; if (isFinite(w)) { ir.w = Math.max(IR_MIN, w); ir.h = ir.w / irAspect(); } clampIR(); applyIR(); }
function setIRH(h) { irUserMoved = true; if (isFinite(h)) { ir.h = Math.max(IR_MIN, h); ir.w = ir.h * irAspect(); } clampIR(); applyIR(); }
function setIRX(x) { irUserMoved = true; if (isFinite(x)) ir.x = x; clampIR(); applyIR(); }
function setIRY(y) { irUserMoved = true; if (isFinite(y)) ir.y = y; clampIR(); applyIR(); }
[[irW, setIRW], [irH, setIRH], [irX, setIRX], [irY, setIRY]].forEach(([el, fn]) => {
const run = () => fn(parseFloat(el.value));
el.addEventListener("input", run);
el.addEventListener("change", run);
el.addEventListener("keydown", e => { if (e.key === "Enter") el.blur(); });
});
function applyIROpacity() { const o = clamp(parseFloat(irOpacityInput.value) / 100 || 0, 0, 1);
irPanel.style.setProperty("--ir-opacity", o); irOpacityValue.textContent = Math.round(o * 100) + "%"; }
function setIRVisible(on) { irVisible = on; irPanel.classList.toggle("ir-hidden", !irVisible);
irPanel.setAttribute("aria-hidden", String(!irVisible)); btnToggleIR.textContent = irVisible ? "Hide IR" : "Show IR";
btnToggleIR.title = irVisible ? "Hide IR overlay (I)" : "Show IR overlay (I)"; if (irVisible) { clampIR(); applyIR(); } }
function toggleIR() { setIRVisible(!irVisible); }
function clampIR() { const sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
if (sw && sh) { ir.w = Math.min(ir.w, sw); ir.h = Math.min(ir.h, sh); ir.x = Math.max(0, Math.min(ir.x, sw - ir.w)); ir.y = Math.max(0, Math.min(ir.y, sh - ir.h)); } }
function initIR() {
const box = rgbBox(), rw = streamA ? streamA.displayW : RGB_DEFAULT.w, rh = streamA ? streamA.displayH : RGB_DEFAULT.h;
const scale = Math.min(box.width / rw, box.height / rh);
const left = box.left + (box.width - rw * scale) / 2, top = box.top + (box.height - rh * scale) / 2;
ir.x = left + IR_DEFAULT.x * scale; ir.y = top + IR_DEFAULT.y * scale;
ir.w = IR_DEFAULT.w * scale; ir.h = IR_DEFAULT.h * scale;
clampIR(); applyIR();
}
function centerIR() { const box = rgbBox(); ir.x = box.left + (box.width - ir.w) / 2; ir.y = box.top + (box.height - ir.h) / 2; clampIR(); applyIR(); }
// Pointer -> SCENE coordinates (undo the zoom/pan transform), so IR drag/resize
// keep working at any zoom. ir.x/y/w/h all live in this (untransformed) space.
function stagePoint(e) { const r = stageRGB.getBoundingClientRect();
return { x: (e.clientX - r.left - view.panX) / view.zoom, y: (e.clientY - r.top - view.panY) / view.zoom }; }
// Called by a stream once its first decoded frame reveals the true (SAR/rotation-
// corrected) dimensions, so the overlay re-fits if the user hasn't moved it.
function onStreamRefined(s) { if ((s === streamA || s === streamB) && !irUserMoved) initIR(); }
irPanel.addEventListener("pointerdown", e => {
if (e.target === irResize || e.button !== 0) return; // right button falls through to pan
e.preventDefault(); irUserMoved = true; irPanel.setPointerCapture(e.pointerId);
const p = stagePoint(e), grabX = p.x - ir.x, grabY = p.y - ir.y;
function move(ev) { const q = stagePoint(ev); ir.x = q.x - grabX; ir.y = q.y - grabY; clampIR(); applyIR(); }
function up() { irPanel.releasePointerCapture(e.pointerId); irPanel.removeEventListener("pointermove", move); irPanel.removeEventListener("pointerup", up); }
irPanel.addEventListener("pointermove", move); irPanel.addEventListener("pointerup", up);
});
irResize.addEventListener("pointerdown", e => {
if (e.button !== 0) return; // right button falls through to pan
e.preventDefault(); e.stopPropagation(); irUserMoved = true; irResize.setPointerCapture(e.pointerId);
const start = stagePoint(e), startW = ir.w, a = irAspect(), sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
function move(ev) { const q = stagePoint(ev); let w = Math.max(IR_MIN, startW + (q.x - start.x)), h = w / a;
if (ir.x + w > sw) { w = sw - ir.x; h = w / a; } if (ir.y + h > sh) { h = sh - ir.y; w = h * a; } ir.w = w; ir.h = h; applyIR(); }
function up() { irResize.releasePointerCapture(e.pointerId); irResize.removeEventListener("pointermove", move); irResize.removeEventListener("pointerup", up); }
irResize.addEventListener("pointermove", move); irResize.addEventListener("pointerup", up);
});
$("btnCenterIR").addEventListener("click", () => { irUserMoved = true; centerIR(); });
$("btnResetIR").addEventListener("click", () => { irUserMoved = false; initIR(); });
btnToggleIR.addEventListener("click", toggleIR);
irOpacityInput.addEventListener("input", applyIROpacity);
new ResizeObserver(() => { if (!irUserMoved) initIR(); else { clampIR(); applyIR(); } applyView(); }).observe(stageRGB);
initIR(); applyIROpacity(); resetView();
// ---- keyboard ---------------------------------------------------------------
document.addEventListener("keydown", e => {
const el = e.target;
if (el.tagName === "INPUT" && el.type !== "range") return;
if (el.tagName === "INPUT" && el.type === "range" && e.key.indexOf("Arrow") === 0) return; // let a focused slider keep its arrows
if (!anyLoaded()) return;
switch (e.key) {
case " ": e.preventDefault(); togglePlay(); break;
case "ArrowLeft": e.preventDefault(); skip(-SKIP_SEC); break;
case "ArrowRight": e.preventDefault(); skip(SKIP_SEC); break;
case "ArrowUp": e.preventDefault(); changeSpeed(1); break;
case "ArrowDown": e.preventDefault(); changeSpeed(-1); break;
case "Home": e.preventDefault(); doSeek(clock.tStart); break;
case "s": case "S": stop(); break;
case "i": case "I": e.preventDefault(); toggleIR(); break;
case "0": e.preventDefault(); resetView(); break; // reset zoom/pan to fit
case "Enter": e.preventDefault(); offsetInput.focus(); offsetInput.select(); break; // jump to offset (Enter again blurs back)
}
});
</script>
</body>
</html>