Files
dogfather-universe/workspace/assets/js/freistellen.js
T

229 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* =====================================================================
FREISTELLEN – Hintergrund weich, schwarz oder Mondnacht (05.11.2026,
Neuplan E7 / C5 / C9)
Für jeden, der seine Kamera sendet (Regie wie Gast): MediaPipes
Selfie-Segmentierung (Apache 2.0) trennt Mensch und Hintergrund, auf
dem eigenen Gerät – es geht kein Bild irgendwohin außer in die Sendung.
Rechenkern und Modell liegen auf unserem Server (assets/js/fremd) und
laden NUR, wenn jemand das Freistellen einschaltet (einmalig ~4 MB).
Gerechnet wird über die Grafikkarte (WebGL2), sonst auf dem Prozessor.
WAS ES NICHT TUT, und das wird gesagt statt verschwiegen:
· Beim Zocken bleibt es aus (das Spiel braucht die Grafikkarte).
· Meldet die Rechnerampel Last, geht die echte Kamera hinaus.
· Ist der Tab im Hintergrund, rechnet der Browser nicht – dann geht
ebenfalls die echte Kamera hinaus statt eines eingefrorenen Bilds.
Die Wahl bleibt gespeichert; sobald die Lage es erlaubt, greift sie
wieder von selbst.
===================================================================== */
(() => {
'use strict';
const $ = (id) => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const ABLAGE = 'saal-hintergrund';
const ARTEN = [['aus', 'Normal'], ['weich', 'Weich'], ['schwarz', 'Schwarz'], ['mond', 'Mondnacht']];
const HIER = document.currentScript?.src || location.href;
const STEMPEL = new URL(HIER).search;
const BIB = new URL(`fremd/mediapipe-tasks-vision-1.2.2.js${STEMPEL}`, HIER).href;
const WASM = new URL('fremd', HIER).href;
const MODELL = new URL('fremd/selfie_segmenter.tflite', HIER).href;
const KANN = !!(window.HTMLVideoElement?.prototype?.requestVideoFrameCallback && HTMLCanvasElement.prototype.captureStream);
let art = (() => { try { const a = localStorage.getItem(ABLAGE); return ARTEN.some(([k]) => k === a) ? a : 'aus'; } catch { return 'aus'; } })();
let lage = null;
let segm = null, segmLaedt = null, segmFehler = '';
let geraet = ''; /* 'GPU' | 'CPU' */
let quelle = null; /* die echte Kameraspur */
let ausgabe = null; /* die freigestellte Spur */
let video = null, klein = null, maske = null, bild = null, mond = null;
let bilder = 0, bilderSeit = performance.now(), rate = 0;
let grund = ''; /* warum gerade die echte Kamera hinausgeht */
let zuletztAktiv = null;
/* ZU LANGSAM? Schafft ein Gerät weniger als MINDESTRATE Bilder/s, fünf
Sekunden in Folge (nach dem Anlaufen), geht wieder die echte Kamera
hinaus – lieber ein normales Bild als eine Diashow. Gilt, bis jemand
die Wahl neu trifft. */
const MINDESTRATE = () => (typeof window.__freistellenMindestrate === 'number' ? window.__freistellenMindestrate : 12);
let langsamSeit = 0, zuLangsam = 0, laeuftSeit = 0;
/* ---- Bibliothek + Modell, einmal ---- */
function segmenter() {
if (segm) return Promise.resolve(segm);
if (!segmLaedt) {
segmLaedt = (async () => {
const v = await import(BIB);
const dateien = await v.FilesetResolver.forVisionTasks(WASM);
const bauen = (delegate) => v.ImageSegmenter.createFromOptions(dateien, {
baseOptions: { modelAssetPath: MODELL, delegate }, runningMode: 'VIDEO',
outputCategoryMask: false, outputConfidenceMasks: true,
});
try { segm = await bauen('GPU'); geraet = 'GPU'; } catch { segm = await bauen('CPU'); geraet = 'CPU'; }
return segm;
})().catch((f) => { segmFehler = String(f?.message || f).slice(0, 120); segmLaedt = null; throw f; });
}
return segmLaedt;
}
/* Die Mondnacht: ein ruhiges, dunkles Bild, einmal gemalt. */
function mondMalen(w, h) {
if (mond && mond.width === w && mond.height === h) return mond;
mond = document.createElement('canvas'); mond.width = w; mond.height = h;
const x = mond.getContext('2d');
const g = x.createRadialGradient(w * 0.72, h * 0.28, 0, w * 0.5, h * 0.5, Math.max(w, h) * 0.8);
g.addColorStop(0, '#26304f'); g.addColorStop(0.45, '#111a33'); g.addColorStop(1, '#06070f');
x.fillStyle = g; x.fillRect(0, 0, w, h);
x.fillStyle = 'rgba(230, 236, 255, .85)';
x.beginPath(); x.arc(w * 0.78, h * 0.22, Math.min(w, h) * 0.06, 0, Math.PI * 2); x.fill();
x.fillStyle = '#111a33';
x.beginPath(); x.arc(w * 0.795, h * 0.21, Math.min(w, h) * 0.055, 0, Math.PI * 2); x.fill();
return mond;
}
function aufbauen(spur) {
abbauen();
quelle = spur;
const s = spur.getSettings?.() || {};
const W = Math.min(1280, s.width || 640), H = Math.round(W * ((s.height || 480) / (s.width || 640)));
video = document.createElement('video');
video.muted = true; video.playsInline = true; video.srcObject = new MediaStream([spur]);
video.play().catch(() => {});
klein = document.createElement('canvas'); klein.width = 256; klein.height = Math.max(64, Math.round(256 * H / W));
maske = document.createElement('canvas'); maske.width = klein.width; maske.height = klein.height;
bild = document.createElement('canvas'); bild.width = W; bild.height = H;
ausgabe = bild.captureStream(30).getVideoTracks()[0] || null;
if (ausgabe) { try { ausgabe.contentHint = 'motion'; } catch { /* egal */ } }
const kx = klein.getContext('2d', { willReadFrequently: true });
const mx = maske.getContext('2d');
const bx = bild.getContext('2d');
const md = mx.createImageData(maske.width, maske.height);
const schritt = (jetzt) => {
if (!video || video.srcObject?.getVideoTracks()[0] !== quelle) return;
try {
if (segm && video.videoWidth) {
kx.drawImage(video, 0, 0, klein.width, klein.height);
const r = segm.segmentForVideo(klein, jetzt);
const m = r.confidenceMasks?.[0];
const werte = m ? m.getAsFloat32Array() : null;
if (werte && !window.__freistellenOhneMaske) {
const d = md.data;
for (let i = 0, j = 3; i < werte.length; i++, j += 4) {
/* weiche, aber klare Kante: unter 0,3 weg, über 0,7 ganz da */
const a = (werte[i] - 0.3) / 0.4;
d[j] = a <= 0 ? 0 : a >= 1 ? 255 : a * 255;
}
} else if (window.__freistellenOhneMaske) {
for (let j = 3; j < md.data.length; j += 4) md.data[j] = 255;
}
r.close?.();
mx.putImageData(md, 0, 0);
bx.globalCompositeOperation = 'copy';
bx.drawImage(video, 0, 0, W, H);
bx.globalCompositeOperation = 'destination-in';
bx.drawImage(maske, 0, 0, W, H);
bx.globalCompositeOperation = 'destination-over';
if (art === 'weich') { bx.filter = 'blur(14px)'; bx.drawImage(video, -20, -20, W + 40, H + 40); bx.filter = 'none'; }
else if (art === 'mond') bx.drawImage(mondMalen(W, H), 0, 0);
else { bx.fillStyle = '#07060d'; bx.fillRect(0, 0, W, H); }
bx.globalCompositeOperation = 'source-over';
bilder++;
}
} catch (f) { segmFehler = String(f?.message || f).slice(0, 120); }
const t = performance.now();
if (t - bilderSeit >= 1000) {
rate = Math.round(bilder * 1000 / (t - bilderSeit)); bilder = 0; bilderSeit = t;
if (!laeuftSeit && rate > 0) laeuftSeit = t;
const angelaufen = laeuftSeit && t - laeuftSeit > 3000;
if (angelaufen && rate < MINDESTRATE()) { if (!langsamSeit) langsamSeit = t; if (t - langsamSeit >= 5000) zuLangsam = rate || 1; }
else langsamSeit = 0;
}
video?.requestVideoFrameCallback(schritt);
};
video.requestVideoFrameCallback(schritt);
}
function abbauen() {
try { ausgabe?.stop(); } catch { /* egal */ }
if (video) { video.srcObject = null; video = null; }
ausgabe = null; quelle = null; rate = 0; laeuftSeit = 0; langsamSeit = 0;
}
/* ---- Darf jetzt freigestellt hinausgehen? ---- */
function hindernis() {
if (art === 'aus') return 'aus';
if (!KANN) return 'Dieser Browser kann das nicht – es geht deine normale Kamera hinaus.';
if (lage?.art === 'spiel') return 'Beim Zocken bleibt das Freistellen aus – das Spiel braucht die Grafikkarte.';
if (document.hidden) return 'Der Tab ist im Hintergrund – solange geht deine normale Kamera hinaus.';
const ampel = $('cockpit-ampel')?.getAttribute('aria-label') || '';
if (/Rechner (unter Last|am Limit|ernst|kritisch)/i.test(ampel)) return 'Dein Rechner ist unter Last – solange geht deine normale Kamera hinaus.';
if (segmFehler && !segm) return `Das Freistellen ließ sich nicht laden (${segmFehler}).`;
if (zuLangsam) return `Dein Gerät schafft das Freistellen nicht flüssig (${zuLangsam} Bilder/s) – es geht deine normale Kamera hinaus. Wähl den Hintergrund neu, um es noch einmal zu versuchen.`;
return '';
}
/* Die Spur, die statt der Kamera hinausgehen soll – oder null. */
function spur(kamera) {
if (!kamera || hindernis()) return null;
if (quelle !== kamera) return null;
return segm && ausgabe && rate > 0 ? ausgabe : null;
}
function takt() {
const kamera = window.SaalKamera?.strom?.()?.getVideoTracks?.()[0] || null;
grund = hindernis();
const soll = !grund && !!kamera && kamera.readyState === 'live';
if (soll) {
if (!segm) segmenter().then(() => window.SaalKamera?.bildNeu?.()).catch(() => zeichnen());
if (quelle !== kamera) aufbauen(kamera);
} else if (quelle) abbauen();
const aktiv = !!spur(kamera);
if (aktiv !== zuletztAktiv) { zuletztAktiv = aktiv; window.SaalKamera?.bildNeu?.(); }
zeichnen();
}
/* ---- Bedienung: im Gerätefenster und im Ton-Bereich der Regie ---- */
function block(wurzel, id) {
if (!wurzel || $(id)) return;
const b = el('div', 'fs'); b.id = id;
b.append(el('h3', 'pult__ueber fs-titel', 'Hintergrund'));
const reihe = el('div', 'fs-reihe'); reihe.setAttribute('role', 'group'); reihe.setAttribute('aria-label', 'Hintergrund der Kamera');
for (const [k, wort] of ARTEN) {
const knopf = el('button', 'btn btn-klein btn-sekundaer fs-knopf', wort); knopf.type = 'button'; knopf.dataset.art = k;
knopf.addEventListener('click', () => { art = k; zuLangsam = 0; try { localStorage.setItem(ABLAGE, k); } catch { /* nur für jetzt */ } takt(); });
reihe.append(knopf);
}
const lageZeile = el('p', 'pult__klein fs-lage'); lageZeile.setAttribute('aria-live', 'polite');
const vorschau = el('video', 'fs-vorschau'); vorschau.muted = true; vorschau.playsInline = true; vorschau.autoplay = true; vorschau.setAttribute('aria-label', 'So sehen dich die anderen');
b.append(reihe, lageZeile, vorschau);
wurzel.append(b);
}
function zeichnen() {
block($('geraetefenster-inhalt')?.parentElement, 'fs-fenster');
block($('tafel-ton'), 'fs-ton');
const kamera = window.SaalKamera?.strom?.()?.getVideoTracks?.()[0] || null;
const aktiv = spur(kamera);
const text = art === 'aus' ? 'Dein Hintergrund bleibt, wie er ist.'
: grund && grund !== 'aus' ? grund
: !kamera ? 'Sobald deine Kamera an ist, wird freigestellt.'
: !segm ? 'Wird geladen (einmalig etwa 4 MB) …'
: aktiv ? `Läuft auf ${geraet === 'GPU' ? 'der Grafikkarte' : 'dem Prozessor'} · ${rate} Bilder/s · nur auf deinem Gerät.`
: 'Startet …';
for (const id of ['fs-fenster', 'fs-ton']) {
const b = $(id);
if (!b) continue;
for (const k of b.querySelectorAll('.fs-knopf')) k.setAttribute('aria-pressed', String(k.dataset.art === art));
const z = b.querySelector('.fs-lage');
if (z.textContent !== text) z.textContent = text;
const v = b.querySelector('.fs-vorschau');
const soll = aktiv ? ausgabe : null;
v.hidden = !soll;
if (soll && v.srcObject?.getVideoTracks()[0] !== soll) { v.srcObject = new MediaStream([soll]); v.play().catch(() => {}); }
if (!soll && v.srcObject) v.srcObject = null;
}
}
window.addEventListener('saal:lage', (ev) => { lage = ev.detail; takt(); });
document.addEventListener('visibilitychange', takt);
setInterval(takt, 1000);
window.Freistellen = { spur, art: () => art, rate: () => rate, geraet: () => geraet, ausgabe: () => ausgabe, grund: () => grund };
})();