Refactor video player and camera angle switching

- Removed inline JSON data for video clips; replaced with API endpoint to fetch video data.
- Simplified camera angle switching UI with a 3-column button grid around a Model Y graphic.
- Updated camera view mapping to use 'back' instead of 'rear'.
- Enhanced noise canvas handling during video loading.
- Streamlined clip playback logic and added auto-play for next clips in the same camera.
- Improved search and sorting functionality by removing unnecessary elements.
- Updated HTML structure for better accessibility and user experience.
This commit is contained in:
zwitschi committed 2026-07-25 00:43:43 +02:00
1 parent 06dc4f5f51
commit d12d5e5414
5 files changed
+508 -805

No files matched your search

+150 -385
View File
@@ -1,67 +1,32 @@
(function () {
"use strict";
const RAW = JSON.parse(
document.getElementById("videoData").textContent || "{}",
);
const cameras = {};
const clips = [];
Object.keys(RAW).forEach(function (key) {
const cam = RAW[key];
cameras[key] = cam.display;
(cam.videos || []).forEach(function (v) {
clips.push({
cam: key,
camDisplay: cam.display,
filename: v.filename,
timestamp: v.timestamp,
rel_path: v.rel_path,
url: v.url,
});
});
});
// Index clips by timestamp for angle synchronization
const byTimestamp = {};
clips.forEach(function (c) {
if (!byTimestamp[c.timestamp]) byTimestamp[c.timestamp] = {};
byTimestamp[c.timestamp][c.cam] = c;
});
// ---- DOM refs ----
const player = document.getElementById("player");
const noiseCanvas = document.getElementById("noiseCanvas");
const placeholder = document.getElementById("videoPlaceholder");
const badge = document.getElementById("videoBadge");
const badgeText = document.getElementById("badgeText");
const clipListEl = document.getElementById("clipList");
const searchBox = document.getElementById("searchBox");
const clearSearch = document.getElementById("clearSearch");
const camTabsEl = document.getElementById("camTabs");
const sortSelect = document.getElementById("sortSelect");
const resultCount = document.getElementById("resultCount");
const camSwitchBtns = document.getElementById("camSwitchButtons");
const nowPlaying = document.getElementById("nowPlaying");
const npName = document.getElementById("npName");
const npTime = document.getElementById("npTime");
document.getElementById("countAll").textContent = clips.length;
const csBtns = document.querySelectorAll(".cs-btn[data-cam]");
let activeCam = "all";
let query = "";
let sortMode = "oldest";
let current = null;
// ---- State ----
let allVideos = {}; // { camKey: { display, videos: [...] } }
let byTimestamp = {}; // { timestamp: { camKey: clip } }
let currentClip = null; // currently playing clip object
let currentCam = "front"; // active camera key
// ---- Static noise canvas for loading indicator ----
var noiseCtx = noiseCanvas.getContext("2d");
var noiseAnimId = null;
var noiseRunning = false;
// ---- Static noise canvas ----
const noiseCtx = noiseCanvas.getContext("2d");
let noiseAnimId = null;
let noiseRunning = false;
function noiseStart() {
if (noiseRunning) return;
noiseRunning = true;
noiseCanvas.classList.remove("hidden");
noiseAnimId = null;
noiseTick();
}
@@ -76,14 +41,12 @@
function noiseTick() {
if (!noiseRunning) return;
var w = noiseCanvas.width;
var h = noiseCanvas.height;
var rect = noiseCanvas.getBoundingClientRect();
// Render at reduced resolution (160px wide) for performance,
// CSS image-rendering: pixelated handles the upscale.
var targetW = Math.max(1, Math.min(160, (rect.width * 0.25) | 0));
var ratio = rect.height / Math.max(1, rect.width);
var targetH = Math.max(1, (targetW * ratio) | 0);
let w = noiseCanvas.width;
let h = noiseCanvas.height;
const rect = noiseCanvas.getBoundingClientRect();
const targetW = Math.max(1, Math.min(160, (rect.width * 0.25) | 0));
const ratio = rect.height / Math.max(1, rect.width);
const targetH = Math.max(1, (targetW * ratio) | 0);
if (w !== targetW || h !== targetH) {
noiseCanvas.width = targetW;
noiseCanvas.height = targetH;
@@ -94,10 +57,10 @@
noiseAnimId = requestAnimationFrame(noiseTick);
return;
}
var imageData = noiseCtx.createImageData(w, h);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var v = (Math.random() * 255) | 0;
const imageData = noiseCtx.createImageData(w, h);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const v = (Math.random() * 255) | 0;
data[i] = v;
data[i + 1] = v;
data[i + 2] = v;
@@ -107,73 +70,7 @@
noiseAnimId = requestAnimationFrame(noiseTick);
}
// Start noise immediately on page load (no video selected yet)
noiseStart();
// ---- Prefetch helpers ----
// Track already-prefetched URLs so we don't re-fetch
var prefetchedUrls = {};
/**
* Prefetch a video URL using a <link rel="prefetch"> element.
* The browser downloads the resource in the background at low priority
* and caches it for instant playback later.
*/
function prefetchVideo(url) {
if (!url || prefetchedUrls[url]) return;
prefetchedUrls[url] = true;
var link = document.createElement("link");
link.rel = "prefetch";
link.as = "video";
link.href = url;
document.head.appendChild(link);
}
/**
* After the current video starts playing, prefetch:
* 1. All sibling camera angles for the same timestamp
* 2. The next clip in the same camera's timeline
*/
function schedulePrefetch(clip) {
// Use requestIdleCallback to run after the browser has handled the
// current frame (i.e. the video has started loading). Fall back to a
// short setTimeout if requestIdleCallback isn't available.
var doPrefetch = function () {
// 1. Sibling camera angles (same timestamp, different cameras)
var group = byTimestamp[clip.timestamp] || {};
Object.keys(group).forEach(function (key) {
if (key !== clip.cam) {
prefetchVideo(group[key].url);
}
});
// 2. Next clip in the same camera's timeline
var sameCam = clips
.filter(function (c) {
return c.cam === clip.cam;
})
.sort(function (a, b) {
if (sortMode === "name") return a.filename.localeCompare(b.filename);
var da = tsToDate(a.timestamp),
db = tsToDate(b.timestamp);
return (da ? da.getTime() : 0) - (db ? db.getTime() : 0);
});
var idx = sameCam.findIndex(function (c) {
return c.timestamp === clip.timestamp && c.filename === clip.filename;
});
if (idx > -1 && sameCam[idx + 1]) {
prefetchVideo(sameCam[idx + 1].url);
}
};
if (typeof requestIdleCallback === "function") {
requestIdleCallback(doPrefetch, { timeout: 2000 });
} else {
setTimeout(doPrefetch, 100);
}
}
// ---- Helpers ----
function tsToDate(ts) {
const m = /^(\d{4})-(\d{2})-(\d{2})[_ ](\d{2})-(\d{2})-(\d{2})/.exec(
ts || "",
@@ -195,136 +92,50 @@
});
}
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
}[c];
});
// ---- Prefetch ----
const prefetchedUrls = {};
function prefetchVideo(url) {
if (!url || prefetchedUrls[url]) return;
prefetchedUrls[url] = true;
const link = document.createElement("link");
link.rel = "prefetch";
link.as = "video";
link.href = url;
document.head.appendChild(link);
}
function getFiltered() {
let out = clips.filter(function (c) {
if (activeCam !== "all" && c.cam !== activeCam) return false;
if (query) {
const hay = (
c.filename +
" " +
c.timestamp +
" " +
c.camDisplay +
" " +
prettyTs(c.timestamp)
).toLowerCase();
if (hay.indexOf(query) === -1) return false;
}
return true;
});
out.sort(function (a, b) {
if (sortMode === "name") return a.filename.localeCompare(b.filename);
const da = tsToDate(a.timestamp),
db = tsToDate(b.timestamp);
const ta = da ? da.getTime() : 0,
tb = db ? db.getTime() : 0;
return sortMode === "oldest" ? ta - tb : tb - ta;
});
return out;
}
function render() {
const list = getFiltered();
resultCount.textContent =
list.length + (list.length === 1 ? " clip" : " clips");
if (!list.length) {
clipListEl.innerHTML =
'<div class="empty"><div>No clips match your filters.</div></div>';
return;
}
let html = "";
if (activeCam === "all") {
const groups = {};
list.forEach(function (c) {
(groups[c.cam] = groups[c.cam] || []).push(c);
function schedulePrefetch(clip) {
const doPrefetch = function () {
// Sibling angles at same timestamp
const group = byTimestamp[clip.timestamp] || {};
Object.keys(group).forEach(function (key) {
if (key !== clip.cam) prefetchVideo(group[key].url);
});
Object.keys(groups).forEach(function (key) {
html += groupHeader(key, groups[key].length);
groups[key].forEach(function (c) {
html += clipRow(c);
});
// Next clip in same camera (oldest-first)
const sameCam = (allVideos[clip.cam] && allVideos[clip.cam].videos) || [];
const idx = sameCam.findIndex(function (c) {
return c.timestamp === clip.timestamp && c.filename === clip.filename;
});
if (idx > -1 && sameCam[idx + 1]) prefetchVideo(sameCam[idx + 1].url);
};
if (typeof requestIdleCallback === "function") {
requestIdleCallback(doPrefetch, { timeout: 2000 });
} else {
html += groupHeader(activeCam, list.length);
list.forEach(function (c) {
html += clipRow(c);
});
setTimeout(doPrefetch, 100);
}
clipListEl.innerHTML = html;
highlightCurrent();
}
function groupHeader(key, n) {
return (
'<div class="cam-group-header"><span>' +
esc(cameras[key] || key) +
" &middot; " +
n +
"</span>" +
"</div>"
);
}
function clipRow(c) {
const id = c.cam + "|" + c.timestamp + "|" + c.filename;
return (
'<div class="clip" data-id="' +
esc(id) +
'" ' +
'data-url="' +
esc(c.url) +
'" data-cam="' +
esc(c.cam) +
'" ' +
'data-ts="' +
esc(c.timestamp) +
'" data-fn="' +
esc(c.filename) +
'">' +
'<div class="thumb">' +
'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="2" y="6" width="14" height="12" rx="2"/><path d="M16 10l6-3v10l-6-3"/></svg>' +
"</div>" +
'<div class="meta">' +
'<div class="fn">' +
esc(c.filename) +
"</div>" +
'<div class="sub"><span class="cam-pill">' +
esc(c.camDisplay) +
"</span>" +
"<span>" +
esc(prettyTs(c.timestamp)) +
"</span></div>" +
"</div>" +
'<div class="play-ico">' +
'<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>' +
"</div>" +
"</div>"
);
}
// ---- Playback ----
function playClip(clip) {
if (!clip) return;
current = clip;
currentClip = clip;
currentCam = clip.cam;
player.src = clip.url;
player.load();
// Show noise while loading, stop when video starts playing
noiseStart();
var prefetchDone = false;
let prefetchDone = false;
function onPlaying() {
noiseStop();
if (prefetchDone) return;
@@ -334,7 +145,6 @@
}
player.addEventListener("playing", onPlaying);
player.play().catch(function () {
// Even if autoplay is blocked, still prefetch for when the user clicks play
noiseStop();
if (!prefetchDone) {
prefetchDone = true;
@@ -351,57 +161,26 @@
npName.textContent = clip.filename;
npTime.textContent = prettyTs(clip.timestamp);
buildCamSwitch(clip);
highlightCurrent();
updateCamButtons(clip.cam);
}
function buildCamSwitch(clip) {
const group = byTimestamp[clip.timestamp] || {};
const availKeys = Object.keys(group);
let html = "";
Object.keys(cameras).forEach(function (key) {
const has = group[key];
const isActive = key === clip.cam;
html +=
'<button data-switch="' +
esc(key) +
'" ' +
(has ? "" : "disabled ") +
'class="' +
(isActive ? "active" : "") +
'" ' +
'title="' +
(has ? "Switch to " + esc(cameras[key]) : "No footage available") +
'">' +
esc(cameras[key]) +
"</button>";
});
if (availKeys.length <= 1) {
html +=
'<span style="color:var(--text-muted);font-size:11.5px;width:100%;padding-top:4px;">' +
"Only one camera view recorded for this timestamp.</span>";
}
camSwitchBtns.innerHTML = html;
}
function switchCam(key) {
if (!current) return;
const group = byTimestamp[current.timestamp] || {};
const target = group[key];
function switchCam(camKey) {
if (!currentClip) return;
const group = byTimestamp[currentClip.timestamp] || {};
const target = group[camKey];
if (!target) return;
const savedTime = player.currentTime || 0;
const wasPlaying = !player.paused;
current = target;
currentClip = target;
currentCam = camKey;
player.src = target.url;
player.load();
badgeText.textContent = target.camDisplay;
npName.textContent = target.filename;
// Preserve video playback timestamp position across camera angles
player.addEventListener("loadedmetadata", function onMeta() {
player.removeEventListener("loadedmetadata", onMeta);
try {
@@ -412,124 +191,110 @@
if (wasPlaying) player.play().catch(function () {});
});
camSwitchBtns.querySelectorAll("button").forEach(function (b) {
b.classList.toggle("active", b.getAttribute("data-switch") === key);
});
highlightCurrent();
updateCamButtons(camKey);
}
function highlightCurrent() {
const rows = clipListEl.querySelectorAll(".clip");
rows.forEach(function (r) {
const isCur =
current &&
r.getAttribute("data-cam") === current.cam &&
r.getAttribute("data-ts") === current.timestamp &&
r.getAttribute("data-fn") === current.filename;
r.classList.toggle("playing", !!isCur);
function updateCamButtons(activeKey) {
csBtns.forEach(function (btn) {
const key = btn.getAttribute("data-cam");
btn.classList.toggle("active", key === activeKey);
});
}
clipListEl.addEventListener("click", function (e) {
const row = e.target.closest(".clip");
if (!row) return;
playClip({
cam: row.getAttribute("data-cam"),
camDisplay: cameras[row.getAttribute("data-cam")],
filename: row.getAttribute("data-fn"),
timestamp: row.getAttribute("data-ts"),
url: row.getAttribute("data-url"),
// ---- Auto-play next clip in same camera ----
player.addEventListener("ended", function () {
if (!currentClip) return;
const sameCam =
(allVideos[currentClip.cam] && allVideos[currentClip.cam].videos) || [];
const idx = sameCam.findIndex(function (c) {
return (
c.timestamp === currentClip.timestamp &&
c.filename === currentClip.filename
);
});
if (idx > -1 && sameCam[idx + 1]) playClip(sameCam[idx + 1]);
});
camSwitchBtns.addEventListener("click", function (e) {
const btn = e.target.closest("button[data-switch]");
// ---- Camera button clicks ----
document.querySelector(".cs-grid").addEventListener("click", function (e) {
const btn = e.target.closest(".cs-btn[data-cam]");
if (!btn || btn.disabled) return;
switchCam(btn.getAttribute("data-switch"));
});
const camKey = btn.getAttribute("data-cam");
if (camKey === currentCam) return; // already active
camTabsEl.addEventListener("click", function (e) {
const tab = e.target.closest(".tab");
if (!tab) return;
camTabsEl.querySelectorAll(".tab").forEach(function (t) {
t.classList.remove("active");
});
tab.classList.add("active");
activeCam = tab.getAttribute("data-cam");
render();
});
let searchTimer;
searchBox.addEventListener("input", function () {
clearSearch.classList.toggle("visible", !!searchBox.value);
clearTimeout(searchTimer);
searchTimer = setTimeout(function () {
query = searchBox.value.trim().toLowerCase();
render();
}, 120);
});
clearSearch.addEventListener("click", function () {
searchBox.value = "";
query = "";
clearSearch.classList.remove("visible");
render();
searchBox.focus();
});
sortSelect.addEventListener("change", function () {
sortMode = sortSelect.value;
render();
});
// Keyboard Shortcuts: 1-9 (Camera Switch), J/K (Next/Prev Clip)
document.addEventListener("keydown", function (e) {
if (/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName)) return;
if (e.key >= "1" && e.key <= "9") {
const keys = Object.keys(cameras);
const idx = +e.key - 1;
if (current && keys[idx]) switchCam(keys[idx]);
} else if (e.key === "j" || e.key === "k") {
const list = getFiltered();
if (!list.length) return;
let i = list.findIndex(function (c) {
return (
current &&
c.cam === current.cam &&
c.timestamp === current.timestamp &&
c.filename === current.filename
);
});
i = e.key === "j" ? Math.min(list.length - 1, i + 1) : Math.max(0, i - 1);
if (list[i]) playClip(list[i]);
// Try same timestamp first, else fall back to oldest in that camera
const group = currentClip ? byTimestamp[currentClip.timestamp] || {} : {};
const sameTs = group[camKey];
if (sameTs) {
switchCam(camKey);
} else {
// No same-timestamp match: play oldest clip for this camera
const videos = (allVideos[camKey] && allVideos[camKey].videos) || [];
if (videos.length > 0) playClip(videos[0]);
}
});
// Auto-play next clip of the same camera when video finishes
player.addEventListener("ended", function () {
if (!current) return;
// Build a list of clips for the SAME camera, sorted like the sidebar
const sameCam = clips
.filter(function (c) {
return c.cam === current.cam;
})
.sort(function (a, b) {
if (sortMode === "name") return a.filename.localeCompare(b.filename);
const da = tsToDate(a.timestamp),
db = tsToDate(b.timestamp);
const ta = da ? da.getTime() : 0,
tb = db ? db.getTime() : 0;
return sortMode === "oldest" ? ta - tb : tb - ta;
});
const i = sameCam.findIndex(function (c) {
return (
c.cam === current.cam &&
c.timestamp === current.timestamp &&
c.filename === current.filename
);
});
if (i > -1 && sameCam[i + 1]) playClip(sameCam[i + 1]);
// ---- Keyboard shortcuts: 1-6 for camera angles ----
const camOrder = [
"front",
"left_repeater",
"right_repeater",
"back",
"left_pillar",
"right_pillar",
];
document.addEventListener("keydown", function (e) {
if (/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName)) return;
if (e.key >= "1" && e.key <= "6") {
const idx = +e.key - 1;
const camKey = camOrder[idx];
if (!camKey) return;
const group = currentClip ? byTimestamp[currentClip.timestamp] || {} : {};
const sameTs = group[camKey];
if (sameTs) {
switchCam(camKey);
} else {
const videos = (allVideos[camKey] && allVideos[camKey].videos) || [];
if (videos.length > 0) playClip(videos[0]);
}
}
});
render();
// ---- Init: fetch full video data, then auto-play front ----
function init() {
fetch("/api/videos")
.then(function (r) {
return r.json();
})
.then(function (data) {
allVideos = data;
// Build byTimestamp index
Object.keys(data).forEach(function (camKey) {
const videos = data[camKey].videos || [];
videos.forEach(function (v) {
v.cam = camKey;
v.camDisplay = data[camKey].display;
if (!byTimestamp[v.timestamp]) byTimestamp[v.timestamp] = {};
byTimestamp[v.timestamp][camKey] = v;
});
});
// Auto-play front if video element has a src
if (player.src && player.src !== window.location.href) {
const frontVideos =
(allVideos["front"] && allVideos["front"].videos) || [];
if (frontVideos.length > 0) {
playClip(frontVideos[0]);
}
}
})
.catch(function (err) {
console.error("Failed to load video data:", err);
});
}
// Start noise immediately
noiseStart();
init();
})();