/*!
* JFVR main — boot, DOM scan, in-page settings panel, XR session lifecycle,
* input dispatch, wiring.
*
* Loaded last. Owns everything the modules do not.
* See INTERFACES.md.
*/
(function () {
'use strict';
var NS = window.__JFVR;
if (!NS) { console.error('[JFVR] core missing'); return; }
if (NS.__main) return;
NS.__main = true;
var S = NS.state;
var log = NS.log;
/* ================================================================== *
* rAF broker
* ------------------------------------------------------------------
* While an immersive XR session runs, window.requestAnimationFrame is
* COMPLETELY stopped (measured: 0 callbacks in 6s). Jellyfin renders libass
* subtitles from an rAF loop, so that froze the subtitle canvas.
*
* The FIRST fix was to queue callbacks in XR and pump the queue from
* video.requestVideoFrameCallback. That is not enough on Jellyfin 12.x: a
* callback that is ALREADY PENDING in the NATIVE scheduler when the session
* starts is destroyed with the native scheduler and never runs again, and
* SubtitlesOctopus starts ONE long-lived rAF loop when the video loads whose
* id is never reset. Verified on device: instance.rafId stuck on a native id
* (1150), oneshotState.eventStart frozen ~7 min behind the playhead, zero
* oneshot-render requests for the whole session -> the whole prerender chain
* stalls and the HUD shows the last line drawn before VR started.
*
* So the queue is used ALWAYS, even outside XR, and drained by a native rAF
* pump. Nothing is ever left pending natively, so nothing can be lost when the
* session starts; startRafPump just swaps the driver. In XR the native pump
* stops and video.requestVideoFrameCallback drives the queue (it still fires,
* in step with the video); a slow timer also drives it when the video is not
* presenting frames (paused / stalled / ended), so a paused seek or a track
* switch still redraws instead of leaving a stale line on screen.
* ================================================================== */
var RAFQ = {
inXR: false,
native: (window.requestAnimationFrame || function () {}).bind(window),
nativeCancel: (window.cancelAnimationFrame || function () {}).bind(window),
queue: new Map(),
nextId: 1000000000,
pumped: 0,
nativeId: null,
lastPump: 0,
err: null
};
function drainRaf(t) {
if (!RAFQ.queue.size) return;
var cbs = [];
RAFQ.queue.forEach(function (cb) { cbs.push(cb); });
RAFQ.queue.clear();
RAFQ.pumped++;
for (var i = 0; i < cbs.length; i++) {
try { cbs[i](t); } catch (e) { if (!RAFQ.err) RAFQ.err = NS.recordError('raf cb', e); }
}
}
// Native driver (outside XR). Exactly ONE native callback is kept in flight so
// that a rAF which re-schedules itself cannot multiply the driver (an earlier
// version nulled nativeId before draining, re-armed on every self-rescheduling
// callback AND again at the end -> exponential native callbacks -> frozen page).
function nativeRafStep(t) {
if (RAFQ.inXR) { RAFQ.nativeId = null; return; } // the XR driver owns the queue
RAFQ.nativeId = RAFQ.native(nativeRafStep); // re-arm BEFORE draining
drainRaf(t);
if (!RAFQ.queue.size && !RAFQ.inXR) { // nothing left -> stop
try { RAFQ.nativeCancel(RAFQ.nativeId); } catch (e) {}
RAFQ.nativeId = null;
}
}
function ensureNativeRaf() {
if (RAFQ.inXR || RAFQ.nativeId != null) return;
RAFQ.nativeId = RAFQ.native(nativeRafStep);
}
try {
window.requestAnimationFrame = function (cb) {
if (typeof cb !== 'function') return 0;
var id = RAFQ.nextId++;
RAFQ.queue.set(id, cb);
if (!RAFQ.inXR) ensureNativeRaf();
return id;
};
window.cancelAnimationFrame = function (id) {
if (RAFQ.queue.has(id)) { RAFQ.queue.delete(id); return; }
return RAFQ.nativeCancel(id);
};
} catch (e) { log('rAF broker install failed', e); }
function startRafPump(video) {
// NOTE: do NOT clear the queue. The callback that a naive broker loses at
// session start is sitting in it, and it is the one that keeps Jellyfin's
// subtitle loop alive. The pending NATIVE driver id is dropped: that callback
// is lost with the native scheduler anyway, and clearing the id lets the
// driver restart cleanly after the session ends.
RAFQ.nativeId = null;
RAFQ.inXR = true;
RAFQ.pumped = 0;
RAFQ.lastPump = 0;
RAFQ.err = null;
var stopped = false;
S.stats.rafPump = video && video.requestVideoFrameCallback ? 'videoFrameCallback' : 'interval';
if (video && video.requestVideoFrameCallback) {
var step = function (now) {
if (stopped) return;
RAFQ.lastPump = performance.now();
drainRaf(now);
video.requestVideoFrameCallback(step);
};
video.requestVideoFrameCallback(step);
}
// Idle fallback: rVFC stops while the video is paused / stalled / ended.
var id = setInterval(function () {
if (stopped || !RAFQ.inXR) return;
if (performance.now() - RAFQ.lastPump > 60) drainRaf(performance.now());
}, 50);
RAFQ.stop = function () { stopped = true; clearInterval(id); };
}
function stopRafPump() {
try { if (RAFQ.stop) RAFQ.stop(); } catch (e) {}
RAFQ.stop = null;
RAFQ.inXR = false;
RAFQ.lastPump = 0;
// hand the queue back to the native driver so nothing is stranded
ensureNativeRaf();
}
/* ================================================================== *
* settings persistence (localStorage, per browser)
* ================================================================== */
var STORE_KEY = 'jfvr.settings.v1';
var saveTimer = null;
function num(v, lo, hi, dflt) {
if (typeof v !== 'number' || !isFinite(v)) return dflt;
return NS.clamp(v, lo, hi);
}
function loadSettings() {
var raw;
try { raw = localStorage.getItem(STORE_KEY); } catch (e) { return; }
if (!raw) return;
var o;
try { o = JSON.parse(raw); } catch (e) { return; } // corrupt -> defaults
if (!o || typeof o !== 'object') return;
try {
if (o.subPlacement && typeof o.subPlacement === 'object') {
S.subPlacement = {
y: num(o.subPlacement.y, -0.95, -0.05, S.subPlacement.y),
z: num(o.subPlacement.z, -2.6, -0.35, S.subPlacement.z),
width: num(o.subPlacement.width, 0.2, 4.5, S.subPlacement.width)
};
}
// ADDENDUM 6: depth/size decoupling. When locked, the stored width is
// re-derived from subAngleDeg + z by 10-subtitles.js, so this pair is what
// actually restores the user's look.
if (typeof o.subLockAngle === 'boolean') S.subLockAngle = o.subLockAngle;
if (typeof o.subAngleDeg === 'number') S.subAngleDeg = num(o.subAngleDeg, 20, 120, S.subAngleDeg);
S.subOpacity = num(o.subOpacity, 0.1, 1.0, S.subOpacity);
S.ctlAutoHideMs = num(o.ctlAutoHideMs, 1000, 10000, S.ctlAutoHideMs);
if (o.subMode === 'hud' || o.subMode === 'sphere') S.subMode = o.subMode;
// subLayout is deliberately NOT restored: a persisted manual override
// silently ruined the default dual-eye content once already (forced 'mono'
// made the HUD show both eyes side by side). Layout always starts on 'auto'.
// ADDENDUM 8: how the picture aim is applied. 'space' is the live path; the
// 'rebuild' escape hatch exists because mutating a media layer's transform is
// ignored by this runtime, so if an offset reference space turns out not to be
// honoured either, this is how we get movement back without a redeploy.
if (o.videoRotMode === 'auto' || o.videoRotMode === 'space' || o.videoRotMode === 'rebuild') {
S.videoRotMode = o.videoRotMode;
}
// 'off' is deliberately NOT restored. Persisting it had the same effect as
// persisting subtitles:false - the subtitle layer was never created on the
// next session, which looked like a loading failure. Same for subAlpha,
// which is harmless but pointless to restore when subtitles start ON.
if (o.subAlpha === 'premultiplied' || o.subAlpha === 'straight') S.subAlpha = o.subAlpha;
if (o.projection === '180' || o.projection === '360') S.projection = o.projection;
if (o.stereo === 'mono' || o.stereo === 'sbs' || o.stereo === 'ou') S.stereo = o.stereo;
if (o.handPref === 'right' || o.handPref === 'left') S.handPref = o.handPref;
if (typeof o.controls === 'boolean') S.controls = o.controls;
// NOTE: `subtitles` is deliberately NOT restored. Persisting it meant a
// session where the user toggled subtitles off came back with them off,
// the subtitle layer never being created - which looked like a loading
// failure. Subtitles always start ON; the toggle is per-session only.
log('settings restored', JSON.stringify(S.subPlacement), 'opacity', S.subOpacity);
} catch (e) { /* keep defaults */ }
}
function saveSettings() {
if (saveTimer != null) clearTimeout(saveTimer);
saveTimer = setTimeout(function () {
saveTimer = null;
try {
localStorage.setItem(STORE_KEY, JSON.stringify({
subPlacement: S.subPlacement,
subLockAngle: S.subLockAngle,
subAngleDeg: S.subAngleDeg,
subOpacity: S.subOpacity,
subMode: S.subMode,
subAlpha: S.subAlpha,
projection: S.projection,
stereo: S.stereo,
handPref: S.handPref,
videoRotMode: S.videoRotMode,
controls: S.controls,
ctlAutoHideMs: S.ctlAutoHideMs
}));
S.stats.saved = 'ok';
} catch (e) { S.stats.saved = 'err:' + ((e && e.message) || e); }
}, 400);
}
/* ================================================================== *
* video discovery
* ================================================================== */
function findVideo() {
var list = Array.prototype.slice.call(document.querySelectorAll('video'));
var playing = null, any = null;
for (var i = 0; i < list.length; i++) {
var v = list[i];
if (!v.videoWidth) continue;
if (!any) any = v;
if (!v.paused && v.readyState >= 2 && !playing) playing = v;
}
return playing || any || null;
}
/* ================================================================== *
* format detection
* ================================================================== */
function detectFromName(name) {
if (!name) return null;
var n = name.toLowerCase();
var is360 = /(^|[^0-9])360([^0-9]|$)/.test(n) || /\bvr360\b/.test(n);
var is180 = /(^|[^0-9])180([^0-9]|$)/.test(n) || /\bvr180\b/.test(n);
var sbs = /(^|[^a-z])(sbs|lr|3dh)([^a-z]|$)/.test(n);
var ou = /(^|[^a-z])(ou|tb|3dv)([^a-z]|$)/.test(n);
if (!is180 && !is360 && !sbs && !ou) return null;
return { projection: is360 ? '360' : '180', stereo: ou ? 'ou' : (sbs || is180 || is360) ? 'sbs' : 'mono' };
}
function detectFromShape(w, h) {
if (!w || !h) return null;
var r = w / h;
if (r >= 3.6) return { projection: '360', stereo: 'sbs' };
if (r >= 1.8 && r <= 2.2) return { projection: '180', stereo: 'sbs' };
if (r >= 1.15 && r <= 1.45) return { projection: '180', stereo: 'mono' };
if (r <= 0.6) return { projection: '180', stereo: 'ou' };
return { projection: '180', stereo: 'sbs' };
}
function currentItemId() {
var m = /[?&]id=([a-f0-9]{32})/i.exec(location.hash || '');
return m ? m[1] : null;
}
function tryFetchFileName() {
var id = currentItemId();
if (!id || typeof ApiClient === 'undefined' || !ApiClient.getItem) return Promise.resolve('');
var uid;
try { uid = ApiClient.getCurrentUserId(); } catch (e) { uid = null; }
if (!uid) return Promise.resolve('');
return ApiClient.getItem(uid, id)
.then(function (item) { return (item && (item.Path || item.Name)) || ''; })
.catch(function () { return ''; });
}
function applyAutoDetect() {
return tryFetchFileName().then(function (name) {
if (name) {
S.fileName = name.split(/[\\/]/).pop();
var d = detectFromName(S.fileName);
if (d) { S.projection = d.projection; S.stereo = d.stereo; S.detected = 'filename: ' + S.fileName; return; }
}
var v = S.video;
var d2 = v && v.videoWidth ? detectFromShape(v.videoWidth, v.videoHeight) : null;
if (d2) {
S.projection = d2.projection; S.stereo = d2.stereo;
S.detected = 'resolution: ' + v.videoWidth + 'x' + v.videoHeight;
}
}).catch(function () {});
}
/* ================================================================== *
* in-page UI
* ================================================================== */
var CSS = [
// Sits ABOVE Jellyfin's own OSD bar: at the viewport's bottom-right it
// covered the player's fullscreen button (owner report). 120 px clears the
// OSD bottom bar; the settings panel stacks above it.
// left/top are set from JS (see placeButton) so the button can be dragged
// anywhere. touch-action:none is what makes a drag work on a touch screen
// instead of scrolling the page underneath.
'.jfvr-btn{position:fixed;z-index:2147483000;display:flex;align-items:center;gap:8px;',
'padding:10px 16px;border:0;border-radius:24px;background:linear-gradient(135deg,#4ea1ff,#7b5cff);color:#fff;',
'font-size:15px;font-weight:600;cursor:grab;box-shadow:0 6px 22px rgba(0,0,0,.45);font-family:inherit;',
'touch-action:none;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}',
'.jfvr-btn:active{transform:scale(.96)}',
'.jfvr-btn.jfvr-drag{cursor:grabbing;transform:none;box-shadow:0 10px 32px rgba(0,0,0,.65)}',
// the panel must always fit the viewport AND keep the CTA reachable, so the
// body scrolls and the button lives in a sticky footer
// Positioned from JS (positionPanel) so it follows the button once the
// button has been dragged; it no longer lives in the viewport corner.
'.jfvr-panel{position:fixed;z-index:2147483001;width:290px;background:rgba(20,20,24,.96);',
'color:#eaeaea;border:1px solid rgba(255,255,255,.14);border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.6);',
'font-family:inherit;font-size:14px;backdrop-filter:blur(10px);display:flex;flex-direction:column;',
'max-height:calc(100vh - 32px);overflow:hidden}',
'.jfvr-head{display:flex;justify-content:space-between;align-items:center;padding:10px 12px;background:rgba(255,255,255,.06);font-weight:600;flex:0 0 auto}',
'.jfvr-x{background:none;border:0;color:#aaa;font-size:20px;line-height:1;cursor:pointer;padding:0 4px}',
'.jfvr-body{padding:12px;overflow-y:auto;flex:1 1 auto;min-height:0}',
'.jfvr-foot{flex:0 0 auto;padding:10px 12px 12px;background:rgba(16,16,20,.98);border-top:1px solid rgba(255,255,255,.1)}',
'.jfvr-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px;gap:8px}',
'.jfvr-lbl{color:#9aa0aa;font-size:13px;white-space:nowrap}',
'.jfvr-seg{display:flex;border:1px solid rgba(255,255,255,.16);border-radius:8px;overflow:hidden;flex-shrink:0}',
'.jfvr-seg button{background:none;border:0;color:#bbb;padding:6px 9px;font-size:12px;cursor:pointer;font-family:inherit}',
'.jfvr-seg button+button{border-left:1px solid rgba(255,255,255,.16)}',
'.jfvr-seg button.on{background:#4ea1ff;color:#fff;font-weight:600}',
'.jfvr-seg button:disabled{color:#555;cursor:default}',
'.jfvr-hint{font-size:12px;color:#8b93a1;margin:2px 0 10px;line-height:1.5;word-break:break-all}',
'.jfvr-go{width:100%;padding:10px;border:0;border-radius:9px;background:#4ea1ff;color:#fff;font-size:15px;',
'font-weight:600;cursor:pointer;font-family:inherit}',
'.jfvr-go:disabled{background:#3a3f47;color:#888;cursor:default}',
'.jfvr-diag{margin-top:10px;font-size:11px;color:#8b93a1}',
'.jfvr-diag summary{cursor:pointer;user-select:none}',
'.jfvr-diag pre{white-space:pre-wrap;word-break:break-all;margin:8px 0 0;font-size:10px;line-height:1.45;',
'max-height:230px;overflow:auto;color:#9fb0c4;background:rgba(0,0,0,.35);padding:8px;border-radius:7px}',
'.jfvr-msg{margin-top:8px;font-size:12px;color:#ffb3b3;line-height:1.55;white-space:pre-line;word-break:break-all}',
'.jfvr-sec{margin:12px 0 6px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#6d7684;',
'border-top:1px solid rgba(255,255,255,.09);padding-top:9px}',
'.jfvr-sl{margin-bottom:7px}',
'.jfvr-sl .jfvr-lbl{display:flex;justify-content:space-between;font-size:12px;margin-bottom:2px}',
'.jfvr-sl input[type=range]{width:100%;accent-color:#4ea1ff;height:18px;cursor:pointer}'
].join('');
function injectCss() {
if (document.getElementById('jfvr-css')) return;
var s = NS.makeEl('style');
s.id = 'jfvr-css';
s.textContent = CSS;
document.head.appendChild(s);
}
var btn = null, panel = null, diagTimer = null;
// Every sliderRow registers a re-read here, so a value changed from anywhere
// (VR control bar, grab & drag, the lock toggle) is reflected in the open panel.
var panelSync = null;
var panelSyncs = [];
function ensureButton() {
if (btn && document.body.contains(btn)) return;
injectCss();
var b = NS.makeEl('button', 'jfvr-btn');
b.type = 'button';
b.innerHTML = '🎥VR 播放';
b.title = '点击打开设置;按住拖动可以换位置;双击回到默认位置';
b.addEventListener('click', function (ev) {
ev.stopPropagation();
// A drag still produces a click on most browsers. Swallow that one so
// dragging the button never opens the panel by accident.
if (dragMoved) { dragMoved = false; return; }
togglePanel();
});
// Escape hatch: a button dragged half off a small window is annoying to
// recover by hand.
b.addEventListener('dblclick', function (ev) {
ev.stopPropagation();
resetButtonPos();
});
installDrag(b);
document.body.appendChild(b);
btn = b;
btnPos = readBtnPos();
placeButton(b, btnPos);
}
/* ------------------------------------------------------------------ *
* button placement / dragging
* ------------------------------------------------------------------
* The button used to be pinned to the bottom-right corner. On a short window
* that put it right on top of the bitrate choices the playback watchdog
* shows (that panel is centred), and there was no way to move it. It is
* draggable now and the spot is remembered per browser.
*
* The settings panel follows the button rather than the viewport corner, so
* the two cannot drift apart.
* ------------------------------------------------------------------ */
var BTN_POS_KEY = 'jfvr-btn-pos';
var BTN_MARGIN = 8;
var DRAG_SLOP = 4; // px of travel before it counts as a drag, not a tap
var btnPos = null; // {left, top} once placed; persisted on drop
var dragging = false;
var dragMoved = false;
var dragStart = null;
function readBtnPos() {
try {
var o = JSON.parse(localStorage.getItem(BTN_POS_KEY) || 'null');
if (o && typeof o.left === 'number' && typeof o.top === 'number') return o;
} catch (e) {}
return null;
}
function writeBtnPos(pos) {
try { localStorage.setItem(BTN_POS_KEY, JSON.stringify(pos)); } catch (e) {}
}
function clampPos(left, top, w, h) {
var maxLeft = Math.max(BTN_MARGIN, window.innerWidth - w - BTN_MARGIN);
var maxTop = Math.max(BTN_MARGIN, window.innerHeight - h - BTN_MARGIN);
return {
left: Math.round(Math.min(Math.max(left, BTN_MARGIN), maxLeft)),
top: Math.round(Math.min(Math.max(top, BTN_MARGIN), maxTop))
};
}
/** The default spot: the old fixed corner, expressed in left/top. */
function defaultPos(b) {
return { left: window.innerWidth - b.offsetWidth - 16,
top: window.innerHeight - b.offsetHeight - 120 };
}
function placeButton(b, pos) {
var p = pos || defaultPos(b);
var c = clampPos(p.left, p.top, b.offsetWidth, b.offsetHeight);
b.style.left = c.left + 'px';
b.style.top = c.top + 'px';
b.style.right = 'auto';
b.style.bottom = 'auto';
return c;
}
function resetButtonPos() {
if (!btn) return;
try { localStorage.removeItem(BTN_POS_KEY); } catch (e) {}
btnPos = placeButton(btn, null);
positionPanel();
}
function installDrag(b) {
b.addEventListener('pointerdown', function (ev) {
if (ev.button != null && ev.button !== 0) return; // primary button / touch only
var r = b.getBoundingClientRect();
dragging = true;
dragMoved = false;
dragStart = { x: ev.clientX, y: ev.clientY, left: r.left, top: r.top };
b.classList.add('jfvr-drag');
try { b.setPointerCapture(ev.pointerId); } catch (e) {}
});
b.addEventListener('pointermove', function (ev) {
if (!dragging || !dragStart) return;
var dx = ev.clientX - dragStart.x;
var dy = ev.clientY - dragStart.y;
if (!dragMoved) {
if (Math.abs(dx) < DRAG_SLOP && Math.abs(dy) < DRAG_SLOP) return;
dragMoved = true;
if (panel) hidePanel(); // do not drag the panel around with it
}
btnPos = clampPos(dragStart.left + dx, dragStart.top + dy, b.offsetWidth, b.offsetHeight);
b.style.left = btnPos.left + 'px';
b.style.top = btnPos.top + 'px';
});
function endDrag(ev) {
if (!dragging) return;
dragging = false;
dragStart = null;
b.classList.remove('jfvr-drag');
try { b.releasePointerCapture(ev.pointerId); } catch (e) {}
if (dragMoved) writeBtnPos(btnPos);
}
b.addEventListener('pointerup', endDrag);
b.addEventListener('pointercancel', endDrag);
}
/** Put the panel next to the button: above it, or below when there is no room. */
function positionPanel() {
if (!panel || !btn) return;
var b = btn.getBoundingClientRect();
var w = panel.offsetWidth;
var h = panel.offsetHeight;
var gap = 8;
var left = b.right - w; // right edges aligned
var top = b.top - h - gap;
if (top < BTN_MARGIN) top = b.bottom + gap; // no room above -> below
var maxLeft = Math.max(BTN_MARGIN, window.innerWidth - w - BTN_MARGIN);
var maxTop = Math.max(BTN_MARGIN, window.innerHeight - h - BTN_MARGIN);
panel.style.left = Math.round(Math.min(Math.max(left, BTN_MARGIN), maxLeft)) + 'px';
panel.style.top = Math.round(Math.min(Math.max(top, BTN_MARGIN), maxTop)) + 'px';
panel.style.right = 'auto';
panel.style.bottom = 'auto';
}
function onViewportResize() {
if (btn && document.body.contains(btn)) btnPos = placeButton(btn, btnPos);
positionPanel();
}
function removeButton() {
if (btn) { btn.remove(); btn = null; }
hidePanel();
}
function segRow(label, getValue, setValue, options, disabledFn) {
var row = NS.makeEl('div', 'jfvr-row');
row.appendChild(NS.makeEl('span', 'jfvr-lbl', label));
var seg = NS.makeEl('div', 'jfvr-seg');
options.forEach(function (o) {
var b = NS.makeEl('button', null, o.label);
b.type = 'button';
if (getValue() === o.value) b.classList.add('on');
if (disabledFn && disabledFn(o.value)) { b.disabled = true; }
b.addEventListener('click', function (ev) {
ev.stopPropagation();
setValue(o.value);
Array.prototype.forEach.call(seg.children, function (c) { c.classList.remove('on'); });
b.classList.add('on');
refreshHint();
});
seg.appendChild(b);
});
row.appendChild(seg);
return row;
}
function sliderRow(label, min, max, step, fmt, getValue, setValue) {
var wrap = NS.makeEl('div', 'jfvr-sl');
var lab = NS.makeEl('div', 'jfvr-lbl');
var name = NS.makeEl('span', null, label);
var val = NS.makeEl('span', null, fmt(getValue()));
lab.appendChild(name); lab.appendChild(val);
wrap.appendChild(lab);
var inp = NS.makeEl('input');
inp.type = 'range';
inp.min = min; inp.max = max; inp.step = step;
inp.value = getValue();
inp.addEventListener('input', function (ev) {
ev.stopPropagation();
var v = parseFloat(inp.value);
setValue(v);
val.textContent = fmt(v);
});
wrap.appendChild(inp);
panelSyncs.push(function () {
var v = getValue();
if (document.activeElement !== inp) inp.value = v;
val.textContent = fmt(v);
});
return wrap;
}
function togglePanel() {
if (panel) { hidePanel(); return; }
injectCss();
panelSyncs = [];
// Subtitles must be prepared BEFORE entering VR: libass does not recompute
// its backing store while an immersive session is running.
if (S.subtitles && NS.Subtitles) {
try { NS.Subtitles.prepare(); } catch (e) { NS.recordError('prepare', e); }
}
panel = NS.makeEl('div', 'jfvr-panel');
panel.addEventListener('click', function (ev) { ev.stopPropagation(); });
var head = NS.makeEl('div', 'jfvr-head');
head.appendChild(NS.makeEl('span', null, 'VR 播放'));
var x = NS.makeEl('button', 'jfvr-x', '\u00d7');
x.type = 'button';
x.addEventListener('click', function (ev) { ev.stopPropagation(); hidePanel(); });
head.appendChild(x);
panel.appendChild(head);
var body = NS.makeEl('div', 'jfvr-body');
if (!window.isSecureContext) {
body.appendChild(NS.makeEl('div', 'jfvr-msg',
'\u26a0 当前不是安全上下文(' + location.origin + '),点了也进不去 VR。\n' +
'先在 Quest 浏览器 chrome://flags 里启用 unsafely-treat-insecure-origin-as-secure,' +
'填入 http://192.168.123.199:8096,Relaunch 后重开本页。'));
}
body.appendChild(NS.makeEl('div', 'jfvr-sec', '画面'));
body.appendChild(segRow('投影', function () { return S.projection; },
function (v) { S.projection = v; S.detected = 'manual'; saveSettings(); },
[{ label: '180\u00b0', value: '180' }, { label: '360\u00b0', value: '360' }]));
body.appendChild(segRow('立体', function () { return S.stereo; },
function (v) { S.stereo = v; S.detected = 'manual'; saveSettings(); },
[{ label: '单目', value: 'mono' }, { label: '左右', value: 'sbs' }, { label: '上下', value: 'ou' }]));
// ADDENDUM 7: the ONLY subtitle setting left before entering VR. Everything
// else (mode / alpha / opacity / position / depth / size / lock) is set IN
// VR, where the user can actually judge it - slider values chosen on a flat
// screen do not transfer to the headset. 视角宽度 keeps its default; the
// in-VR "小/大" buttons and the subtitle-row caption are the controls.
body.appendChild(NS.makeEl('div', 'jfvr-sec', '字幕'));
body.appendChild(segRow('显示', function () { return S.subtitles ? 'on' : 'off'; },
function (v) { S.subtitles = v === 'on'; saveSettings(); },
[{ label: '开', value: 'on' }, { label: '关', value: 'off' }]));
// ADDENDUM 9: dual-eye ASS vs a normal (mono) subtitle. 'auto' detects from
// the libass canvas; force it only if the detection gets it wrong.
body.appendChild(segRow('字幕布局', function () { return S.subLayout || 'auto'; },
function (v) {
S.subLayout = v;
if (NS.Subtitles && NS.Subtitles.setLayout) { try { NS.Subtitles.setLayout(v); } catch (e) {} }
saveSettings();
},
[{ label: '自动', value: 'auto' }, { label: '双目', value: 'dual' }, { label: '普通', value: 'mono' }]));
body.appendChild(NS.makeEl('div', 'jfvr-hint',
'字幕的位置 / 距离 / 大小 / 不透明度都在 VR 里用控制条调(控制条最下面一行),' +
'调好会自动记住。VR 空间右侧有个锁图标:锁上后面板不会再被唤出。'));
body.appendChild(NS.makeEl('div', 'jfvr-sec', '操作'));
body.appendChild(segRow('主用手', function () { return S.handPref || 'right'; },
function (v) { S.handPref = v; saveSettings(); },
[{ label: '右手', value: 'right' }, { label: '左手', value: 'left' }]));
body.appendChild(NS.makeEl('div', 'jfvr-hint',
'引导线/光标默认在主用手上;另一只手按下会立刻接管那一次操作。'));
// ADDENDUM 8: the picture-pan mechanism. Only touch this if panning does not
// move the picture live (see stats.videoRotMode).
body.appendChild(segRow('画面旋转', function () { return S.videoRotMode || 'auto'; },
function (v) {
S.videoRotMode = v;
if (S.session) {
try { videoSpaceCache = null; S.videoTransformLive = undefined; applyVideoAngle(true); } catch (e) {}
}
saveSettings();
},
[{ label: '自动', value: 'auto' }, { label: '兼容', value: 'rebuild' }]));
body.appendChild(NS.makeEl('div', 'jfvr-sec', '控制'));
body.appendChild(segRow('VR 内控制条', function () { return S.controls ? 'on' : 'off'; },
function (v) { S.controls = v === 'on'; saveSettings(); },
[{ label: '开', value: 'on' }, { label: '关', value: 'off' }]));
body.appendChild(sliderRow('自动收起', 1000, 10000, 500,
function (v) { return (v / 1000).toFixed(1) + ' s'; },
function () { return S.ctlAutoHideMs; },
function (v) { S.ctlAutoHideMs = v; saveSettings(); }));
var hint = NS.makeEl('div', 'jfvr-hint');
hint.id = 'jfvr-hint';
body.appendChild(hint);
var det = document.createElement('details');
det.className = 'jfvr-diag';
var sum = document.createElement('summary');
sum.textContent = '诊断信息(可复制发我)';
det.appendChild(sum);
var pre = document.createElement('pre');
pre.id = 'jfvr-diag';
det.appendChild(pre);
body.appendChild(det);
panel.appendChild(body);
// The status line and the CTA live in a sticky footer so neither can scroll
// off-screen - the CTA did before, once the settings grew past a short viewport.
var foot = NS.makeEl('div', 'jfvr-foot');
var msg = NS.makeEl('div', 'jfvr-msg');
msg.id = 'jfvr-msg';
foot.appendChild(msg);
var go = NS.makeEl('button', 'jfvr-go', '进入 VR');
go.type = 'button';
go.id = 'jfvr-go';
go.addEventListener('click', function (ev) {
ev.stopPropagation();
if (S.subtitles && NS.Subtitles) { try { NS.Subtitles.prepare(); } catch (e) {} }
go.disabled = true;
go.textContent = '进入中\u2026';
enterVR().catch(function (e) { log('enterVR threw', e); }).then(function () {
go.disabled = false;
go.textContent = '进入 VR';
});
});
foot.appendChild(go);
panel.appendChild(foot);
document.body.appendChild(panel);
positionPanel();
panelSync = function () {
for (var i = 0; i < panelSyncs.length; i++) {
try { panelSyncs[i](); } catch (e) {}
}
};
refreshHint();
updateDiag();
if (!diagTimer) {
diagTimer = setInterval(function () {
if (panel) updateDiag(); else { clearInterval(diagTimer); diagTimer = null; }
}, 1000);
}
}
function hidePanel() {
if (panel) { panel.remove(); panel = null; }
panelSync = null;
panelSyncs = [];
// Only shrink the subtitle canvas back when we are not in / about to be in VR.
if (!S.session && NS.Subtitles) { try { NS.Subtitles.restore(); } catch (e) {} }
}
function refreshHint() {
var h = document.getElementById('jfvr-hint');
if (!h) return;
var v = S.video;
var shape = v && v.videoWidth ? (v.videoWidth + '\u00d7' + v.videoHeight) : '未知';
var txt = '画面 ' + shape + ' · ' + (S.detected || '自动');
var proj = S.projection === '360' ? 'VR360' : 'VR180';
var st = S.stereo === 'sbs' ? '左右' : S.stereo === 'ou' ? '上下' : '单目';
txt += ' → ' + proj + ' ' + st;
var cs = NS.Subtitles && NS.Subtitles.canvasSize ? NS.Subtitles.canvasSize() : null;
if (cs) txt += ' · 字幕画布 ' + cs.w + '\u00d7' + cs.h;
h.textContent = txt;
}
function updateDiag() {
var pre = document.getElementById('jfvr-diag');
if (!pre) return;
var v = S.video;
var video = v ? [
'size : ' + v.videoWidth + ' x ' + v.videoHeight,
'readyState : ' + v.readyState + ' paused: ' + v.paused,
't / dur : ' + v.currentTime.toFixed(1) + ' / ' + (isFinite(v.duration) ? v.duration.toFixed(1) : 'n/a'),
'src : ' + (v.currentSrc || '').slice(0, 100)
].join('\n') : 'no