4 Commits
Author SHA1 Message Date
cat-shark 131e0349b8 plugin: publish 0.2.0.0 (bundle edca47) 2026-10-18 00:28:26 +08:00
cat-shark d0fe04bf25 watchdog: tell the user when a video never starts, and offer transcode
Some files never produce a picture on some machines. The Quest decodes the
8K HEVC Main 10 files fine; a Windows desktop browser claims HEVC Main 10 up to
level 6.1 via canPlayType() (Jellyfin Web builds its device profile from that,
browserDeviceProfile.js) so the server picks Direct Play, and the desktop GPU
cannot actually decode it. Result: black screen and a spinner.

The user-visible symptom is worse than it sounds: Jellyfin Web creates the whole
player UI only after 'playbackstart', which never fires, so the OSD -- including
the quality menu -- is never built. There is literally nothing to click to lower
the bitrate. Load order, from the source:

  HtmlVideoPlayer.play()            htmlVideoPlayer/plugin.js:502
    createMediaElement()            :1802  spinner + <div.videoPlayerContainer>
                                           + <video>, inserted with no src yet
    setCurrentSrc()                 :593   elem.src = url
      -> loadedmetadata -> canplay -> play -> 'playbackstart'
        -> OSD controller (apps/legacy/controllers/playback/video/index.js:591)

So 40-watchdog.js watches for exactly the pre-OSD state: a .videoPlayerContainer
whose <video> still has videoWidth === 0. It fires immediately on a media error,
or after 15s (45s when the src is already an HLS transcode, where the server has
to produce segments first). It stands down the moment there is a picture, and
never runs during a VR session.

The panel names the format (fetched from the Jellyfin API), explains the cause,
and offers 20/8/3 Mbps plus "keep waiting". A choice writes the same localStorage
keys Jellyfin's own menu writes and reloads: window.playbackManager is not
reachable from injected script (verified: undefined; window.Emby only has Page),
so the settings path is the only option. Note the upstream key really is
'enableautobitratebitrate-...' with "bitrate" twice; reproduced deliberately.
A 120s cooldown in sessionStorage stops it nagging a slow-but-working playback.

Verified against a local harness (3 cases, all passing): healthy playback ->
never arms; media error -> immediate; hung stream -> ~16.4s; dismiss -> hides and
persists the cooldown, and stayed hidden 20s past the threshold; bitrate choice
-> writes maxbitrate-Video-true/false=20000000 and
enableautobitratebitrate-Video-true/false=false, then reloads.
2026-10-18 00:27:53 +08:00
cat-shark 51ab1a4b48 plugin: publish 0.1.0.1 (bundle 917fde) 2026-10-17 23:33:17 +08:00
cat-shark 5279f3929a plugin: fix zip reproducibility and legacy-tag log spam
Two issues found while verifying the live install:

1. pack.py produced a different zip MD5 for identical content, because zip
   records file mtimes. Re-running pack.py would have rewritten the manifest
   checksum while the already-published asset stayed the same, and Jellyfin
   would then refuse the install with "The checksum of the received data
   doesn't match." The zip entry now carries a fixed 1980-01-01 timestamp, and
   --publish downloads the published asset back and compares its MD5 with the
   manifest checksum before reporting success.

2. The legacy deploy.py tag lives in the on-disk index.html, so it was stripped
   from every single response and logged at INFO each time (6 lines and counting
   per boot on the live server). The message is now emitted once, and says what
   it actually means: the tag is still on disk, run deploy.py rollback to clean
   it up.

Verified: 21/21 rewrite checks pass, including a regression case built from the
tag actually present on the server.
2026-10-17 23:33:06 +08:00
8 changed files with 794 additions and 7 deletions
+1 -1
View File
@@ -21,7 +21,7 @@ SRC = os.path.join(HERE, "src")
DIST = os.path.join(HERE, "dist") DIST = os.path.join(HERE, "dist")
OUT = os.path.join(DIST, "jfvr.js") OUT = os.path.join(DIST, "jfvr.js")
ORDER = ["00-core.js", "10-subtitles.js", "20-controls.js", "30-hands.js", "90-main.js"] ORDER = ["00-core.js", "10-subtitles.js", "20-controls.js", "30-hands.js", "40-watchdog.js", "90-main.js"]
def sources(): def sources():
+366 -1
View File
@@ -1,7 +1,7 @@
/*! /*!
* JFVR (Jellyfin Web VR) — built bundle. DO NOT EDIT. * JFVR (Jellyfin Web VR) — built bundle. DO NOT EDIT.
* Edit src/*.js and run: python3 build.py * Edit src/*.js and run: python3 build.py
* Modules: 00-core.js, 10-subtitles.js, 20-controls.js, 30-hands.js, 90-main.js * Modules: 00-core.js, 10-subtitles.js, 20-controls.js, 30-hands.js, 40-watchdog.js, 90-main.js
*/ */
/* ===== 00-core.js ===== */ /* ===== 00-core.js ===== */
@@ -4396,6 +4396,368 @@
/* ===== 40-watchdog.js ===== */
/*!
* JFVR watchdog — "this video never started" detection.
*
* WHY THIS EXISTS
* ---------------
* Jellyfin Web builds the whole player UI (including the quality menu) only
* after the 'playbackstart' event, which the media element fires once it has
* actually started. The load order is:
*
* HtmlVideoPlayer.play() htmlVideoPlayer/plugin.js:502
* createMediaElement() :1802 -> loading.show() spinner
* -> <div.videoPlayerContainer><video>
* -> inserted into document.body
* (no src yet!)
* setCurrentSrc() :593 -> elem.src = url, only now
* -> loadedmetadata -> canplay -> play
* -> 'playbackstart'
* -> OSD controller (apps/legacy/controllers/playback/video/index.js:591)
*
* So when the browser cannot use the stream, the OSD never appears at all: the
* page is a spinner over an empty container with a <video> whose videoWidth is
* still 0. There is no quality menu to click, because it was never created.
*
* That is the case this module covers. It watches for exactly that state and
* offers the only thing that can help: tell Jellyfin to transcode.
*
* WHY localStorage AND NOT THE PLAYBACK MANAGER
* --------------------------------------------
* The bitrate is normally set through playbackManager.setMaxStreamingBitrate(),
* which does a live changeStream(). That manager is an ES module export and is
* NOT on window (verified: window.playbackManager is undefined; window.Emby only
* has Page). So the watchdog writes the same keys appSettings would have written
* (src/scripts/settings/appSettings.js) and reloads, which makes Jellyfin request
* PlaybackInfo again with the new cap and pick Transcode.
*
* NOTE the key name really does say "bitrate" twice — that is upstream's typo,
* reproduced here deliberately.
*/
(function () {
'use strict';
var NS = window.__JFVR;
if (!NS) { console.error('[JFVR] core missing'); return; }
if (NS.__watchdog) return;
NS.__watchdog = true;
var S = NS.state;
var log = NS.log;
/* ------------------------------------------------------------------ *
* tunables
* ------------------------------------------------------------------ */
var POLL_MS = 500;
// Direct play on a LAN should have metadata almost immediately; the file is
// 11 GB but its moov atom is at the front, so there is nothing to wait for.
// A transcode is different: the server has to decode the first GOP and produce
// segments before the browser sees any metadata, and this NAS is doing 8K.
var DEAD_MS = 15000;
var DEAD_TRANSCODE_MS = 45000;
// After the user answers (either way) stay quiet, so a slow-but-working
// playback does not get nagged at.
var QUIET_MS = 120000;
var QUIET_KEY = 'jfvr-watchdog-quiet-until';
// Values from Jellyfin's own menu (src/components/qualityOptions.js).
var CHOICES = [
{ label: '20 Mbps', bitrate: 20000000, note: '≈4K,最接近原始画质' },
{ label: '8 Mbps', bitrate: 8000000, note: '1080p 档,稳' },
{ label: '3 Mbps', bitrate: 3000000, note: '720p 档,最省算力' }
];
var W = {
seenAt: 0, // when the current stalled <video> first showed up
shown: false,
quietUntil: 0,
lastReason: '',
applied: null,
codec: null, // filled in best-effort from the Jellyfin API
panel: null
};
NS.Watchdog = W;
/* ------------------------------------------------------------------ *
* helpers
* ------------------------------------------------------------------ */
function now() { return Date.now(); }
/**
* The element Jellyfin creates in createMediaElement(). It exists from the
* very start of playback — including the failure case, which is the whole
* point: findVideo() in 90-main.js requires videoWidth and would return null.
*/
function playerVideo() {
var c = document.querySelector('.videoPlayerContainer');
if (!c) return null;
return c.querySelector('video') || null;
}
function isTranscode(v) {
var src = v.currentSrc || v.src || '';
return src.indexOf('/hls') >= 0 || src.indexOf('.m3u8') >= 0;
}
/** Metadata parsed AND a frame available. False means "no picture". */
function hasPicture(v) {
return v.videoWidth > 0 && v.readyState >= 2;
}
function readQuiet() {
try {
var raw = window.sessionStorage && sessionStorage.getItem(QUIET_KEY);
return raw ? parseInt(raw, 10) || 0 : 0;
} catch (e) { return 0; }
}
function setQuiet(ms) {
W.quietUntil = now() + ms;
try { sessionStorage.setItem(QUIET_KEY, String(W.quietUntil)); } catch (e) {}
}
/**
* Write the same keys Jellyfin's own quality menu writes, for BOTH in-network
* and out-of-network, because the client is the only side that knows which one
* applies and we cannot ask it (appSettings is not on window).
*/
function applyBitrate(bitrate) {
var media = 'Video';
['true', 'false'].forEach(function (inNet) {
try {
localStorage.setItem('enableautobitratebitrate-' + media + '-' + inNet, 'false');
localStorage.setItem('maxbitrate-' + media + '-' + inNet, String(bitrate));
} catch (e) {
log('watchdog: could not persist bitrate', e && e.message);
}
});
W.applied = bitrate;
log('watchdog: capped bitrate at', bitrate, 'and reloading');
setQuiet(QUIET_MS);
window.location.reload();
}
/* ------------------------------------------------------------------ *
* best-effort: name the actual format so the message is actionable
* ------------------------------------------------------------------ */
function itemIdFrom(v) {
var s = (v && (v.currentSrc || v.src)) || '';
var m = s.match(/\/Videos\/([0-9a-f]{32})\//i);
if (m) return m[1];
m = (window.location.hash || '').match(/[?&]id=([0-9a-f]{32})/i);
return m ? m[1] : null;
}
function describeCodec(v) {
if (W.codec) return;
var id = itemIdFrom(v);
if (!id || !window.ApiClient) return;
var url;
try { url = window.ApiClient.getUrl('Items/' + id); } catch (e) { return; }
window.ApiClient.ajax({ type: 'GET', url: url, dataType: 'json' }).then(function (item) {
var ms = (item && item.MediaSources && item.MediaSources[0] && item.MediaSources[0].MediaStreams) || [];
for (var i = 0; i < ms.length; i++) {
var st = ms[i];
if (st.Type !== 'Video') continue;
W.codec = [
st.Width + '×' + st.Height,
(st.Codec || '').toUpperCase(),
st.Profile || '',
st.BitDepth ? st.BitDepth + '-bit' : ''
].filter(Boolean).join(' ');
break;
}
if (W.shown) render(); // update the message in place
}).catch(function () { /* the prompt works fine without this */ });
}
/* ------------------------------------------------------------------ *
* the prompt
* ------------------------------------------------------------------ */
var WD_CSS = [
'.jfvr-wd{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);z-index:2147483002;width:420px;max-width:calc(100vw - 32px);',
'background:rgba(18,18,22,.97);color:#eaeaea;border:1px solid rgba(255,255,255,.16);border-radius:14px;',
'box-shadow:0 18px 60px rgba(0,0,0,.7);font-family:inherit;font-size:14px;padding:18px 18px 14px;backdrop-filter:blur(10px)}',
'.jfvr-wd h3{margin:0 0 6px;font-size:16px;font-weight:600}',
'.jfvr-wd p{margin:0 0 10px;font-size:13px;line-height:1.6;color:#c3c9d4}',
'.jfvr-wd .jfvr-wd-fmt{color:#ffd479;font-weight:600}',
'.jfvr-wd .jfvr-wd-sub{font-size:12px;color:#8b93a1;line-height:1.55;margin-bottom:12px}',
'.jfvr-wd-btns{display:flex;flex-direction:column;gap:8px;margin-bottom:10px}',
'.jfvr-wd-btns button{display:flex;justify-content:space-between;align-items:baseline;gap:10px;width:100%;padding:10px 12px;',
'border:1px solid rgba(255,255,255,.16);border-radius:9px;background:rgba(255,255,255,.05);color:#eaeaea;',
'font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;text-align:left}',
'.jfvr-wd-btns button:hover{background:rgba(78,161,255,.18);border-color:#4ea1ff}',
'.jfvr-wd-btns button span.note{font-size:11px;font-weight:400;color:#8b93a1}',
'.jfvr-wd-quiet{width:100%;padding:9px;border:0;border-radius:9px;background:transparent;color:#8b93a1;',
'font-size:13px;cursor:pointer;font-family:inherit}',
'.jfvr-wd-quiet:hover{color:#eaeaea}',
'.jfvr-wd-diag{margin-top:10px;font-size:11px;color:#8b93a1}',
'.jfvr-wd-diag summary{cursor:pointer;user-select:none}',
'.jfvr-wd-diag pre{white-space:pre-wrap;word-break:break-all;margin:8px 0 0;font-size:10px;line-height:1.5;',
'max-height:150px;overflow:auto;color:#9fb0c4;background:rgba(0,0,0,.35);padding:8px;border-radius:7px}'
].join('');
function injectWdCss() {
if (document.getElementById('jfvr-wd-css')) return;
var s = NS.makeEl('style');
s.id = 'jfvr-wd-css';
s.textContent = WD_CSS;
document.head.appendChild(s);
}
function diagText(v) {
var e = v.error;
return [
'readyState : ' + v.readyState + ' (0=HAVE_NOTHING, 1=HAVE_METADATA, 2=HAVE_CURRENT_DATA)',
'networkState: ' + v.networkState,
'videoWidth : ' + v.videoWidth + '×' + v.videoHeight,
'paused : ' + v.paused,
'currentTime : ' + v.currentTime,
'error : ' + (e ? e.code + ' ' + (e.message || '') : 'none'),
'src : ' + String(v.currentSrc || v.src || '').slice(0, 160),
'格式 : ' + (W.codec || '(未知)')
].join('\n');
}
function render() {
if (!W.panel) return;
var body = W.panel.querySelector('.jfvr-wd-body');
var v = playerVideo();
if (body && v) {
var fmt = body.querySelector('.jfvr-wd-fmt');
if (fmt) fmt.textContent = W.codec || '这个格式';
var pre = body.querySelector('pre');
if (pre) pre.textContent = diagText(v);
}
}
function show(v, reason) {
if (W.shown) { render(); return; }
W.shown = true;
W.lastReason = reason;
injectWdCss();
var p = NS.makeEl('div', 'jfvr-wd');
p.id = 'jfvr-wd';
p.appendChild(NS.makeEl('h3', null, '视频没能开始播放'));
var body = NS.makeEl('div', 'jfvr-wd-body');
var msg = NS.makeEl('p');
var waited = Math.round(timeoutMs(v) / 1000);
msg.innerHTML =
(reason === 'error'
? '播放器报错了,一个画面都没解出来。'
: '等了 ' + waited + ' 秒都没拿到任何画面(<code>videoWidth = 0</code>),' +
'所以播放器界面也没有被创建出来。') +
'最常见的原因是<strong>这台设备解不动这个格式</strong>:' +
'<span class="jfvr-wd-fmt">' + (W.codec || '该格式') + '</span>。<br>' +
'让服务器转码成 H.264 再播就能看到画面,代价是画质下降(这台 NAS 的转码上限约 4K)。';
body.appendChild(msg);
body.appendChild(NS.makeEl('div', 'jfvr-wd-sub',
'选一档码率后会写入播放设置并重新加载页面。'));
var btns = NS.makeEl('div', 'jfvr-wd-btns');
CHOICES.forEach(function (c) {
var b = NS.makeEl('button');
b.type = 'button';
b.appendChild(NS.makeEl('span', null, c.label));
b.appendChild(NS.makeEl('span', 'note', c.note));
b.addEventListener('click', function (ev) {
ev.stopPropagation();
applyBitrate(c.bitrate);
});
btns.appendChild(b);
});
body.appendChild(btns);
var quiet = NS.makeEl('button', 'jfvr-wd-quiet', '继续等待,先别管我');
quiet.type = 'button';
quiet.addEventListener('click', function (ev) {
ev.stopPropagation();
setQuiet(QUIET_MS);
hide();
});
body.appendChild(quiet);
var diag = NS.makeEl('details', 'jfvr-wd-diag');
diag.appendChild(NS.makeEl('summary', null, '诊断信息'));
diag.appendChild(NS.makeEl('pre', null, diagText(v)));
body.appendChild(diag);
p.appendChild(body);
document.body.appendChild(p);
W.panel = p;
NS.recordError('watchdog', new Error('playback never started: ' + reason));
log('watchdog: playback never started, reason =', reason, 'codec =', W.codec);
}
function hide() {
W.shown = false;
if (W.panel) { W.panel.remove(); W.panel = null; }
}
function reset() {
W.seenAt = 0;
W.codec = null;
if (W.shown) hide();
}
function timeoutMs(v) {
return isTranscode(v) ? DEAD_TRANSCODE_MS : DEAD_MS;
}
/* ------------------------------------------------------------------ *
* poll
* ------------------------------------------------------------------ */
function poll() {
// Never interfere with an active VR session: the session owns the flow and
// a modal in the middle of it would be a disaster.
if (S.session) { if (W.shown) hide(); return; }
var v = playerVideo();
if (!v) { reset(); return; }
// Playback is fine (or at least has a picture): stand down.
if (hasPicture(v)) { reset(); return; }
// A media error is unambiguous — no need to wait out the timer.
if (v.error) {
describeCodec(v);
if (W.quietUntil && now() < W.quietUntil) return;
show(v, 'error');
return;
}
if (!W.seenAt) W.seenAt = now();
if (now() - W.seenAt < timeoutMs(v)) return;
if (W.quietUntil && now() < W.quietUntil) return;
describeCodec(v);
show(v, 'timeout');
}
NS.Watchdog.init = function () {
W.quietUntil = readQuiet();
setInterval(poll, POLL_MS);
log('watchdog armed (dead=' + DEAD_MS + 'ms, transcode=' + DEAD_TRANSCODE_MS + 'ms)');
};
})();
/* ===== 90-main.js ===== */ /* ===== 90-main.js ===== */
/*! /*!
@@ -6343,6 +6705,9 @@
try { if (NS.Subtitles && NS.Subtitles.init) NS.Subtitles.init(); } catch (e) { NS.recordError('Subtitles.init', e); } try { if (NS.Subtitles && NS.Subtitles.init) NS.Subtitles.init(); } catch (e) { NS.recordError('Subtitles.init', e); }
try { if (NS.Controls && NS.Controls.init) NS.Controls.init(); } catch (e) { NS.recordError('Controls.init', e); } try { if (NS.Controls && NS.Controls.init) NS.Controls.init(); } catch (e) { NS.recordError('Controls.init', e); }
try { if (NS.Hands && NS.Hands.init) NS.Hands.init(); } catch (e) { NS.recordError('Hands.init', e); } try { if (NS.Hands && NS.Hands.init) NS.Hands.init(); } catch (e) { NS.recordError('Hands.init', e); }
// Watches for "the player never produced a picture" and offers the only fix
// that helps (let the server transcode). See 40-watchdog.js.
try { if (NS.Watchdog && NS.Watchdog.init) NS.Watchdog.init(); } catch (e) { NS.recordError('Watchdog.init', e); }
scan(); scan();
new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true }); new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true });
+16
View File
@@ -7,6 +7,22 @@
"owner": "cat-shark", "owner": "cat-shark",
"category": "General", "category": "General",
"versions": [ "versions": [
{
"version": "0.2.0.0",
"targetAbi": "12.0.0.0",
"changelog": "Bundle version: `edca47`\n\nFirst plugin build. The web bundle is embedded in the DLL and served from /JFVR/jfvr.js; index.html is rewritten at request time, so nothing is written to the jellyfin-web folder on disk.",
"sourceUrl": "https://git.cat-shark.xyz/cat-shark/jellyfin_vr_web_plugin/releases/download/v0.2.0.0/Jellyfin.Plugin.JFVR_12.0.0.0.zip",
"checksum": "355DD18DC228A6586334431518C4B60D",
"timestamp": "2026-10-17T16:28:23"
},
{
"version": "0.1.0.1",
"targetAbi": "12.0.0.0",
"changelog": "Bundle version: `917fde`\n\nFirst plugin build. The web bundle is embedded in the DLL and served from /JFVR/jfvr.js; index.html is rewritten at request time, so nothing is written to the jellyfin-web folder on disk.",
"sourceUrl": "https://git.cat-shark.xyz/cat-shark/jellyfin_vr_web_plugin/releases/download/v0.1.0.1/Jellyfin.Plugin.JFVR_12.0.0.0.zip",
"checksum": "5BB9DA51A50C5449E7C1D0D6602E8813",
"timestamp": "2026-10-17T15:33:14"
},
{ {
"version": "0.1.0.0", "version": "0.1.0.0",
"targetAbi": "12.0.0.0", "targetAbi": "12.0.0.0",
+41 -2
View File
@@ -240,6 +240,24 @@ def head_ok(url):
return e.code, None return e.code, None
def fetch_md5(url):
"""Download the published asset and hash it -- exactly what Jellyfin does.
This is the check that catches a manifest whose checksum no longer matches the
uploaded zip (a real failure mode: the install then dies with
"The checksum of the received data doesn't match.").
"""
h = hashlib.md5()
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=300) as resp:
while True:
chunk = resp.read(1 << 20)
if not chunk:
break
h.update(chunk)
return h.hexdigest().upper()
# ---------------------------------------------------------------- steps # ---------------------------------------------------------------- steps
@@ -275,11 +293,25 @@ def verify_embedded(dll):
def make_zip(dll, target_abi): def make_zip(dll, target_abi):
"""Package the DLL the way Jellyfin expects: one file, named after the assembly.
The entry gets a fixed timestamp on purpose. zip stores mtimes, so packaging
the same DLL twice would otherwise produce different bytes, a different MD5,
and a manifest checksum that no longer matches the already-uploaded asset.
"""
os.makedirs(OUT_DIR, exist_ok=True) os.makedirs(OUT_DIR, exist_ok=True)
asset = "%s_%s.zip" % (ASSEMBLY, target_abi) asset = "%s_%s.zip" % (ASSEMBLY, target_abi)
path = os.path.join(OUT_DIR, asset) path = os.path.join(OUT_DIR, asset)
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
zf.write(dll, ASSEMBLY + ".dll") info = zipfile.ZipInfo(ASSEMBLY + ".dll", date_time=(1980, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o644 << 16
with open(dll, "rb") as fh:
payload = fh.read()
with zipfile.ZipFile(path, "w") as zf:
zf.writestr(info, payload)
print("packaged %s (%d bytes)" % (path, os.path.getsize(path))) print("packaged %s (%d bytes)" % (path, os.path.getsize(path)))
return path, asset return path, asset
@@ -383,6 +415,13 @@ def main():
if status != 200: if status != 200:
sys.exit("the asset is not downloadable -- is the release a draft?") sys.exit("the asset is not downloadable -- is the release a draft?")
# What Jellyfin will do at install time: download it and compare MD5.
live = fetch_md5(entry["sourceUrl"])
if live != checksum:
sys.exit("published asset md5 %s != manifest checksum %s -- install would fail"
% (live, checksum))
print("asset md5 matches the manifest checksum (%s)" % live)
if not args.no_push: if not args.no_push:
run(["git", "add", "manifest.json", "plugin/build.yaml"], cwd=HERE) run(["git", "add", "manifest.json", "plugin/build.yaml"], cwd=HERE)
dirty = subprocess.run( dirty = subprocess.run(
@@ -38,6 +38,7 @@ public sealed class ScriptInjectionStartupFilter : IStartupFilter
private readonly BundleProvider _bundle; private readonly BundleProvider _bundle;
private readonly ILogger<ScriptInjectionStartupFilter> _logger; private readonly ILogger<ScriptInjectionStartupFilter> _logger;
private int _loggedOnce; private int _loggedOnce;
private int _legacyLoggedOnce;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ScriptInjectionStartupFilter"/> class. /// Initializes a new instance of the <see cref="ScriptInjectionStartupFilter"/> class.
@@ -158,9 +159,15 @@ public sealed class ScriptInjectionStartupFilter : IStartupFilter
var rewritten = IndexHtmlRewriter.Rewrite(html, scriptUrl, out var removedLegacy); var rewritten = IndexHtmlRewriter.Rewrite(html, scriptUrl, out var removedLegacy);
if (removedLegacy) if (removedLegacy && Interlocked.Exchange(ref _legacyLoggedOnce, 1) == 0)
{ {
_logger.LogInformation("JFVR: removed the legacy deploy.py <script> tag from index.html."); // Logged once, not per request: the legacy tag lives in the on-disk
// index.html, so it is stripped from every single response until the
// file itself is cleaned up (deploy.py rollback) or deploy.py is run
// again. Per-request logging would just fill the log with the same line.
_logger.LogInformation(
"JFVR: stripping the legacy deploy.py <script> tag from index.html. "
+ "It is still present on disk; run 'python3 deploy.py rollback' to clean it up.");
} }
if (IndexHtmlRewriter.IsInjected(html) || rewritten == html) if (IndexHtmlRewriter.IsInjected(html) || rewritten == html)
+1 -1
View File
@@ -7,7 +7,7 @@
# (InstallationManager.GetAvailablePackages), so one package covers all of 12.x. # (InstallationManager.GetAvailablePackages), so one package covers all of 12.x.
name: "Jellyfin Web VR" name: "Jellyfin Web VR"
guid: "7d33ef59-f9b0-412b-93bd-5cd5353018de" guid: "7d33ef59-f9b0-412b-93bd-5cd5353018de"
version: "0.1.0.0" version: "0.2.0.0"
targetAbi: "12.0.0.0" targetAbi: "12.0.0.0"
framework: "net10.0" framework: "net10.0"
overview: "VR180/VR360 playback inside Jellyfin Web for Meta Quest 3." overview: "VR180/VR360 playback inside Jellyfin Web for Meta Quest 3."
+357
View File
@@ -0,0 +1,357 @@
/*!
* JFVR watchdog — "this video never started" detection.
*
* WHY THIS EXISTS
* ---------------
* Jellyfin Web builds the whole player UI (including the quality menu) only
* after the 'playbackstart' event, which the media element fires once it has
* actually started. The load order is:
*
* HtmlVideoPlayer.play() htmlVideoPlayer/plugin.js:502
* createMediaElement() :1802 -> loading.show() spinner
* -> <div.videoPlayerContainer><video>
* -> inserted into document.body
* (no src yet!)
* setCurrentSrc() :593 -> elem.src = url, only now
* -> loadedmetadata -> canplay -> play
* -> 'playbackstart'
* -> OSD controller (apps/legacy/controllers/playback/video/index.js:591)
*
* So when the browser cannot use the stream, the OSD never appears at all: the
* page is a spinner over an empty container with a <video> whose videoWidth is
* still 0. There is no quality menu to click, because it was never created.
*
* That is the case this module covers. It watches for exactly that state and
* offers the only thing that can help: tell Jellyfin to transcode.
*
* WHY localStorage AND NOT THE PLAYBACK MANAGER
* --------------------------------------------
* The bitrate is normally set through playbackManager.setMaxStreamingBitrate(),
* which does a live changeStream(). That manager is an ES module export and is
* NOT on window (verified: window.playbackManager is undefined; window.Emby only
* has Page). So the watchdog writes the same keys appSettings would have written
* (src/scripts/settings/appSettings.js) and reloads, which makes Jellyfin request
* PlaybackInfo again with the new cap and pick Transcode.
*
* NOTE the key name really does say "bitrate" twice — that is upstream's typo,
* reproduced here deliberately.
*/
(function () {
'use strict';
var NS = window.__JFVR;
if (!NS) { console.error('[JFVR] core missing'); return; }
if (NS.__watchdog) return;
NS.__watchdog = true;
var S = NS.state;
var log = NS.log;
/* ------------------------------------------------------------------ *
* tunables
* ------------------------------------------------------------------ */
var POLL_MS = 500;
// Direct play on a LAN should have metadata almost immediately; the file is
// 11 GB but its moov atom is at the front, so there is nothing to wait for.
// A transcode is different: the server has to decode the first GOP and produce
// segments before the browser sees any metadata, and this NAS is doing 8K.
var DEAD_MS = 15000;
var DEAD_TRANSCODE_MS = 45000;
// After the user answers (either way) stay quiet, so a slow-but-working
// playback does not get nagged at.
var QUIET_MS = 120000;
var QUIET_KEY = 'jfvr-watchdog-quiet-until';
// Values from Jellyfin's own menu (src/components/qualityOptions.js).
var CHOICES = [
{ label: '20 Mbps', bitrate: 20000000, note: '≈4K,最接近原始画质' },
{ label: '8 Mbps', bitrate: 8000000, note: '1080p 档,稳' },
{ label: '3 Mbps', bitrate: 3000000, note: '720p 档,最省算力' }
];
var W = {
seenAt: 0, // when the current stalled <video> first showed up
shown: false,
quietUntil: 0,
lastReason: '',
applied: null,
codec: null, // filled in best-effort from the Jellyfin API
panel: null
};
NS.Watchdog = W;
/* ------------------------------------------------------------------ *
* helpers
* ------------------------------------------------------------------ */
function now() { return Date.now(); }
/**
* The element Jellyfin creates in createMediaElement(). It exists from the
* very start of playback — including the failure case, which is the whole
* point: findVideo() in 90-main.js requires videoWidth and would return null.
*/
function playerVideo() {
var c = document.querySelector('.videoPlayerContainer');
if (!c) return null;
return c.querySelector('video') || null;
}
function isTranscode(v) {
var src = v.currentSrc || v.src || '';
return src.indexOf('/hls') >= 0 || src.indexOf('.m3u8') >= 0;
}
/** Metadata parsed AND a frame available. False means "no picture". */
function hasPicture(v) {
return v.videoWidth > 0 && v.readyState >= 2;
}
function readQuiet() {
try {
var raw = window.sessionStorage && sessionStorage.getItem(QUIET_KEY);
return raw ? parseInt(raw, 10) || 0 : 0;
} catch (e) { return 0; }
}
function setQuiet(ms) {
W.quietUntil = now() + ms;
try { sessionStorage.setItem(QUIET_KEY, String(W.quietUntil)); } catch (e) {}
}
/**
* Write the same keys Jellyfin's own quality menu writes, for BOTH in-network
* and out-of-network, because the client is the only side that knows which one
* applies and we cannot ask it (appSettings is not on window).
*/
function applyBitrate(bitrate) {
var media = 'Video';
['true', 'false'].forEach(function (inNet) {
try {
localStorage.setItem('enableautobitratebitrate-' + media + '-' + inNet, 'false');
localStorage.setItem('maxbitrate-' + media + '-' + inNet, String(bitrate));
} catch (e) {
log('watchdog: could not persist bitrate', e && e.message);
}
});
W.applied = bitrate;
log('watchdog: capped bitrate at', bitrate, 'and reloading');
setQuiet(QUIET_MS);
window.location.reload();
}
/* ------------------------------------------------------------------ *
* best-effort: name the actual format so the message is actionable
* ------------------------------------------------------------------ */
function itemIdFrom(v) {
var s = (v && (v.currentSrc || v.src)) || '';
var m = s.match(/\/Videos\/([0-9a-f]{32})\//i);
if (m) return m[1];
m = (window.location.hash || '').match(/[?&]id=([0-9a-f]{32})/i);
return m ? m[1] : null;
}
function describeCodec(v) {
if (W.codec) return;
var id = itemIdFrom(v);
if (!id || !window.ApiClient) return;
var url;
try { url = window.ApiClient.getUrl('Items/' + id); } catch (e) { return; }
window.ApiClient.ajax({ type: 'GET', url: url, dataType: 'json' }).then(function (item) {
var ms = (item && item.MediaSources && item.MediaSources[0] && item.MediaSources[0].MediaStreams) || [];
for (var i = 0; i < ms.length; i++) {
var st = ms[i];
if (st.Type !== 'Video') continue;
W.codec = [
st.Width + '×' + st.Height,
(st.Codec || '').toUpperCase(),
st.Profile || '',
st.BitDepth ? st.BitDepth + '-bit' : ''
].filter(Boolean).join(' ');
break;
}
if (W.shown) render(); // update the message in place
}).catch(function () { /* the prompt works fine without this */ });
}
/* ------------------------------------------------------------------ *
* the prompt
* ------------------------------------------------------------------ */
var WD_CSS = [
'.jfvr-wd{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);z-index:2147483002;width:420px;max-width:calc(100vw - 32px);',
'background:rgba(18,18,22,.97);color:#eaeaea;border:1px solid rgba(255,255,255,.16);border-radius:14px;',
'box-shadow:0 18px 60px rgba(0,0,0,.7);font-family:inherit;font-size:14px;padding:18px 18px 14px;backdrop-filter:blur(10px)}',
'.jfvr-wd h3{margin:0 0 6px;font-size:16px;font-weight:600}',
'.jfvr-wd p{margin:0 0 10px;font-size:13px;line-height:1.6;color:#c3c9d4}',
'.jfvr-wd .jfvr-wd-fmt{color:#ffd479;font-weight:600}',
'.jfvr-wd .jfvr-wd-sub{font-size:12px;color:#8b93a1;line-height:1.55;margin-bottom:12px}',
'.jfvr-wd-btns{display:flex;flex-direction:column;gap:8px;margin-bottom:10px}',
'.jfvr-wd-btns button{display:flex;justify-content:space-between;align-items:baseline;gap:10px;width:100%;padding:10px 12px;',
'border:1px solid rgba(255,255,255,.16);border-radius:9px;background:rgba(255,255,255,.05);color:#eaeaea;',
'font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;text-align:left}',
'.jfvr-wd-btns button:hover{background:rgba(78,161,255,.18);border-color:#4ea1ff}',
'.jfvr-wd-btns button span.note{font-size:11px;font-weight:400;color:#8b93a1}',
'.jfvr-wd-quiet{width:100%;padding:9px;border:0;border-radius:9px;background:transparent;color:#8b93a1;',
'font-size:13px;cursor:pointer;font-family:inherit}',
'.jfvr-wd-quiet:hover{color:#eaeaea}',
'.jfvr-wd-diag{margin-top:10px;font-size:11px;color:#8b93a1}',
'.jfvr-wd-diag summary{cursor:pointer;user-select:none}',
'.jfvr-wd-diag pre{white-space:pre-wrap;word-break:break-all;margin:8px 0 0;font-size:10px;line-height:1.5;',
'max-height:150px;overflow:auto;color:#9fb0c4;background:rgba(0,0,0,.35);padding:8px;border-radius:7px}'
].join('');
function injectWdCss() {
if (document.getElementById('jfvr-wd-css')) return;
var s = NS.makeEl('style');
s.id = 'jfvr-wd-css';
s.textContent = WD_CSS;
document.head.appendChild(s);
}
function diagText(v) {
var e = v.error;
return [
'readyState : ' + v.readyState + ' (0=HAVE_NOTHING, 1=HAVE_METADATA, 2=HAVE_CURRENT_DATA)',
'networkState: ' + v.networkState,
'videoWidth : ' + v.videoWidth + '×' + v.videoHeight,
'paused : ' + v.paused,
'currentTime : ' + v.currentTime,
'error : ' + (e ? e.code + ' ' + (e.message || '') : 'none'),
'src : ' + String(v.currentSrc || v.src || '').slice(0, 160),
'格式 : ' + (W.codec || '(未知)')
].join('\n');
}
function render() {
if (!W.panel) return;
var body = W.panel.querySelector('.jfvr-wd-body');
var v = playerVideo();
if (body && v) {
var fmt = body.querySelector('.jfvr-wd-fmt');
if (fmt) fmt.textContent = W.codec || '这个格式';
var pre = body.querySelector('pre');
if (pre) pre.textContent = diagText(v);
}
}
function show(v, reason) {
if (W.shown) { render(); return; }
W.shown = true;
W.lastReason = reason;
injectWdCss();
var p = NS.makeEl('div', 'jfvr-wd');
p.id = 'jfvr-wd';
p.appendChild(NS.makeEl('h3', null, '视频没能开始播放'));
var body = NS.makeEl('div', 'jfvr-wd-body');
var msg = NS.makeEl('p');
var waited = Math.round(timeoutMs(v) / 1000);
msg.innerHTML =
(reason === 'error'
? '播放器报错了,一个画面都没解出来。'
: '等了 ' + waited + ' 秒都没拿到任何画面(<code>videoWidth = 0</code>),' +
'所以播放器界面也没有被创建出来。') +
'最常见的原因是<strong>这台设备解不动这个格式</strong>:' +
'<span class="jfvr-wd-fmt">' + (W.codec || '该格式') + '</span>。<br>' +
'让服务器转码成 H.264 再播就能看到画面,代价是画质下降(这台 NAS 的转码上限约 4K)。';
body.appendChild(msg);
body.appendChild(NS.makeEl('div', 'jfvr-wd-sub',
'选一档码率后会写入播放设置并重新加载页面。'));
var btns = NS.makeEl('div', 'jfvr-wd-btns');
CHOICES.forEach(function (c) {
var b = NS.makeEl('button');
b.type = 'button';
b.appendChild(NS.makeEl('span', null, c.label));
b.appendChild(NS.makeEl('span', 'note', c.note));
b.addEventListener('click', function (ev) {
ev.stopPropagation();
applyBitrate(c.bitrate);
});
btns.appendChild(b);
});
body.appendChild(btns);
var quiet = NS.makeEl('button', 'jfvr-wd-quiet', '继续等待,先别管我');
quiet.type = 'button';
quiet.addEventListener('click', function (ev) {
ev.stopPropagation();
setQuiet(QUIET_MS);
hide();
});
body.appendChild(quiet);
var diag = NS.makeEl('details', 'jfvr-wd-diag');
diag.appendChild(NS.makeEl('summary', null, '诊断信息'));
diag.appendChild(NS.makeEl('pre', null, diagText(v)));
body.appendChild(diag);
p.appendChild(body);
document.body.appendChild(p);
W.panel = p;
NS.recordError('watchdog', new Error('playback never started: ' + reason));
log('watchdog: playback never started, reason =', reason, 'codec =', W.codec);
}
function hide() {
W.shown = false;
if (W.panel) { W.panel.remove(); W.panel = null; }
}
function reset() {
W.seenAt = 0;
W.codec = null;
if (W.shown) hide();
}
function timeoutMs(v) {
return isTranscode(v) ? DEAD_TRANSCODE_MS : DEAD_MS;
}
/* ------------------------------------------------------------------ *
* poll
* ------------------------------------------------------------------ */
function poll() {
// Never interfere with an active VR session: the session owns the flow and
// a modal in the middle of it would be a disaster.
if (S.session) { if (W.shown) hide(); return; }
var v = playerVideo();
if (!v) { reset(); return; }
// Playback is fine (or at least has a picture): stand down.
if (hasPicture(v)) { reset(); return; }
// A media error is unambiguous — no need to wait out the timer.
if (v.error) {
describeCodec(v);
if (W.quietUntil && now() < W.quietUntil) return;
show(v, 'error');
return;
}
if (!W.seenAt) W.seenAt = now();
if (now() - W.seenAt < timeoutMs(v)) return;
if (W.quietUntil && now() < W.quietUntil) return;
describeCodec(v);
show(v, 'timeout');
}
NS.Watchdog.init = function () {
W.quietUntil = readQuiet();
setInterval(poll, POLL_MS);
log('watchdog armed (dead=' + DEAD_MS + 'ms, transcode=' + DEAD_TRANSCODE_MS + 'ms)');
};
})();
+3
View File
@@ -1943,6 +1943,9 @@
try { if (NS.Subtitles && NS.Subtitles.init) NS.Subtitles.init(); } catch (e) { NS.recordError('Subtitles.init', e); } try { if (NS.Subtitles && NS.Subtitles.init) NS.Subtitles.init(); } catch (e) { NS.recordError('Subtitles.init', e); }
try { if (NS.Controls && NS.Controls.init) NS.Controls.init(); } catch (e) { NS.recordError('Controls.init', e); } try { if (NS.Controls && NS.Controls.init) NS.Controls.init(); } catch (e) { NS.recordError('Controls.init', e); }
try { if (NS.Hands && NS.Hands.init) NS.Hands.init(); } catch (e) { NS.recordError('Hands.init', e); } try { if (NS.Hands && NS.Hands.init) NS.Hands.init(); } catch (e) { NS.recordError('Hands.init', e); }
// Watches for "the player never produced a picture" and offers the only fix
// that helps (let the server transcode). See 40-watchdog.js.
try { if (NS.Watchdog && NS.Watchdog.init) NS.Watchdog.init(); } catch (e) { NS.recordError('Watchdog.init', e); }
scan(); scan();
new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true }); new MutationObserver(scan).observe(document.documentElement, { childList: true, subtree: true });