Handle stopped streams, live bandwidth, and rework the upscaling tiers

When the server owner stops a stream, Plex cuts the connection and repeats
the termination in every timeline reply to the client until it reports a
stop. The player now reads those replies (also when playback stalls or
fails), stops mpv, shows the owner's message and acknowledges it; a
termination on a session's first reply is left over from an earlier stream
and is cleared instead of cancelling the new one. Each title also starts
unpaused, as mpv keeps pause across files.

The dashboard's bandwidth graph refreshes every second. Plex's real-time
samples are bytes per second with idle seconds omitted, so they are laid on
a gap-free per-second axis (they were divided by six before).

Upscaling: Balanced is now the strongest shader chain, light nlmeans,
FSRCNNX 16, KrigBilateral and debanding. Measured against 1080p references
shrunk to 480p it beat FSRCNNX 8, two network passes, RAVU and
SSimSuperRes. The denoiser is AN3223's light profile with luma strength at
60%, which keeps texture the default profile smoothed away. Quality is now
NVIDIA RTX Video Super Resolution through mpv's d3d11vpp filter, sized to
the window and re-applied when it changes; it is offered only on Windows
with an NVIDIA RTX GPU (app_info now lists the adapters), runs Balanced for
HDR or at native size, and drops a tier if the driver refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-10-31 12:09:34 -07:00
parent ac5048f0b2
commit d9e22dde2e
17 changed files with 316 additions and 524 deletions

View file

@ -10,7 +10,7 @@ import { win, isNative } from '../platform/native';
import { WindowControls } from '../app/TopBar';
import { navigate } from '../app/router';
import { mpv } from './engine';
import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, toggleBypass, type Diagnostics } from './enhance';
import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance';
import { toast } from '../ui/overlays';
import type { Item } from '../plex/types';
@ -173,9 +173,9 @@ function Panel({ title, onClose, onBack, children, className = '' }: { title: st
);
}
function Option({ selected, label, detail, onClick }: { selected: boolean; label: string; detail?: string; onClick: () => void }) {
function Option({ selected, label, detail, disabled, onClick }: { selected: boolean; label: string; detail?: string; disabled?: boolean; onClick: () => void }) {
return (
<button className={`panel-option${selected ? ' selected' : ''}`} onClick={onClick}>
<button className={`panel-option${selected ? ' selected' : ''}`} disabled={disabled} onClick={onClick}>
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
<span className="panel-label">
{label}
@ -328,12 +328,19 @@ function SettingsPanel({ onClose }: { onClose: () => void }) {
return (
<Panel title="Upscaling" onClose={onClose} onBack={back} className="upscaling">
{UPSCALING_ORDER.map((m) => (
<Option key={m} selected={prefs.upscaling === m} label={UPSCALING[m].label} detail={hasFailed(m) ? 'Couldn’t start on this computer' : UPSCALING[m].detail} onClick={() => prefs.set('upscaling', m)} />
<Option
key={m}
selected={prefs.upscaling === m}
label={UPSCALING[m].label}
detail={!tierAvailable(m) ? 'Needs an NVIDIA RTX graphics card on Windows' : hasFailed(m) ? 'Couldn’t start on this computer' : UPSCALING[m].detail}
disabled={!tierAvailable(m)}
onClick={() => prefs.set('upscaling', m)}
/>
))}
<div className="panel-subhead">Stages</div>
<Option selected={prefs.enhanceDeband} label="Debanding" detail="Smooths banding in gradients" onClick={() => prefs.set('enhanceDeband', !prefs.enhanceDeband)} />
<Option selected={prefs.enhanceSharpen} label="Sharpening" detail="AMD CAS · SDR only" onClick={() => prefs.set('enhanceSharpen', !prefs.enhanceSharpen)} />
<Option selected={prefs.enhanceDenoise} label="Denoising" detail="Non-local means, at any size · Quality tier, SDR only" onClick={() => prefs.set('enhanceDenoise', !prefs.enhanceDenoise)} />
<Option selected={prefs.enhanceDenoise} label="Denoising" detail="Non-local means, at any size · Balanced tier, SDR only" onClick={() => prefs.set('enhanceDenoise', !prefs.enhanceDenoise)} />
<button className={`panel-compare${st.enhance.bypass ? ' on' : ''}`} onClick={() => toggleBypass()}>
{st.enhance.bypass ? 'Turn enhancement back on' : 'Compare with enhancement off'}
<kbd>B</kbd>
@ -728,7 +735,8 @@ export function PlayerOverlay() {
case 'u':
case 'U': {
const prefs = useSettings.getState();
const next = UPSCALING_ORDER[(UPSCALING_ORDER.indexOf(prefs.upscaling) + 1) % UPSCALING_ORDER.length];
const tiers = UPSCALING_ORDER.filter(tierAvailable);
const next = tiers[(tiers.indexOf(prefs.upscaling) + 1) % tiers.length];
prefs.set('upscaling', next);
// Confirm what is actually running once it's applied.
requestEnhancement().then(() => {
@ -841,12 +849,20 @@ export function PlayerOverlay() {
<h2>Playback stopped</h2>
<p>{st.error}</p>
<div className="actions">
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
Try converting
</Button>
<Button variant="ghost" onClick={() => st.close()}>
Close
</Button>
{st.terminated ? (
<Button variant="primary" onClick={() => st.close()}>
Close
</Button>
) : (
<>
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
Try converting
</Button>
<Button variant="ghost" onClick={() => st.close()}>
Close
</Button>
</>
)}
</div>
</div>
)}

View file

@ -1,19 +1,28 @@
/**
* Video enhancement: upscaling tiers built from mpv's scalers, debanding and
* the shaders bundled in src-tauri/shaders. Each shader's WHEN condition
* decides whether it runs for the current video and window size, so one list
* covers every case: FSRCNNX doubles luma when the video is enlarged (the
* small model above 1.3×, the large one at any enlargement, so 1080p in a
* maximized 1440p window is doubled and scaled down), KrigBilateral rebuilds
* subsampled colour, CAS sharpens at native size (CAS-prescale also before
* upscaling) and nlmeans denoises at any size.
* Video enhancement: upscaling tiers built from mpv's scalers, debanding, the
* shaders bundled in src-tauri/shaders and, on Windows with an NVIDIA RTX
* GPU, the driver's RTX Video Super Resolution.
*
* Shader tiers: each shader's WHEN condition decides whether it runs for the
* current video and window size, so one list covers every case. FSRCNNX 16
* doubles luma at any enlargement (1080p in a maximized 1440p window is
* doubled and scaled down), KrigBilateral rebuilds subsampled colour, CAS
* sharpens at native size (CAS-prescale also before upscaling) and nlmeans
* denoises lightly at any size. Against a 1080p reference shrunk to 480p,
* FSRCNNX 16 beat the smaller model, two network passes, RAVU and
* SSimSuperRes.
*
* Quality hands enlargement to the GPU's video processor (mpv's d3d11vpp
* filter with NVIDIA's scaling mode), sized to the window, which also
* removes compression artifacts. It needs D3D11 decoding and SDR video;
* otherwise (or at native size) it runs Balanced's chain.
*
* The tier the user chose (preferences) and the one actually running (player
* state) are kept apart: a tier whose shaders fail drops to the one below with
* a notice instead of silently showing plain scaling, and isn't retried.
* state) are kept apart: a tier that fails drops to the one below with a
* notice instead of silently showing plain scaling, and isn't retried.
*/
import { useSettings, UPSCALING, type Upscaling } from '../app/settings';
import { isNative, resourcePath } from '../platform/native';
import { appInfo, isNative, resourcePath } from '../platform/native';
import { toast } from '../ui/overlays';
import { mpv } from './engine';
import { usePlayer } from './store';
@ -25,47 +34,63 @@ const SCALER_PROPS = ['scale', 'cscale', 'dscale', 'sigmoid-upscaling', 'deband'
let scalerDefaults: Partial<Record<(typeof SCALER_PROPS)[number], unknown>> | null = null;
let shaderDir: Promise<string> | null = null;
/** The enlargement above which each tier's network runs (its shaders' WHEN condition). */
const NETWORK_MIN_SCALE: Partial<Record<Upscaling, number>> = { balanced: 1.3, quality: 1.0 };
const runsNetwork = async (mode: Upscaling) => mode in NETWORK_MIN_SCALE && (await scaleFactor()) > NETWORK_MIN_SCALE[mode]!;
const NETWORK = 'FSRCNNX_x2_16-0-4-1.glsl';
const NEURAL: Partial<Record<Upscaling, string>> = { balanced: 'FSRCNNX_x2_8-0-4-1.glsl', quality: 'FSRCNNX_x2_16-0-4-1.glsl' };
/** RTX Video needs Windows (D3D11) and an NVIDIA RTX GPU. */
let rtxVideo = false;
appInfo()
.then((info) => (rtxVideo = info.platform === 'windows' && info.gpus.some((n) => /NVIDIA/i.test(n) && /\bRTX\b/i.test(n))))
.catch(() => {});
/** Whether this computer can run a tier at all (Quality is greyed out otherwise). */
export const tierAvailable = (mode: Upscaling) => mode !== 'quality' || rtxVideo;
/** mpv label for the RTX Video filter, so other video filters are left alone. */
const VSR_LABEL = '@kaleido-vsr';
/** NVIDIA's video processor enlarges up to 4×; mpv scales any remainder. */
const VSR_MAX_SCALE = 4;
interface Plan {
props: Record<string, unknown>;
shaders: string[];
/** d3d11vpp settings for RTX Video, or '' for none. */
vsr: string;
}
/**
* What a tier runs. Sharpening (CAS) and denoising (nlmeans) are tuned for
* SDR levels, so HDR video skips them; the upscalers and debanding stay.
* Quality denoises first, so the network enlarges the picture rather than
* the compression noise. Both FSRCNNX models are trained on general imagery,
* which suits live action.
* Balanced denoises first, so the network enlarges the picture rather than
* the compression noise. FSRCNNX is trained on general imagery, which suits
* live action.
*/
function plan(mode: Upscaling, hdr: boolean): Plan {
function plan(mode: Upscaling, hdr: boolean, scale: number): Plan {
const { enhanceDeband, enhanceSharpen, enhanceDenoise } = useSettings.getState();
const sharpen = enhanceSharpen && !hdr;
let props: Record<string, unknown>;
let shaders: string[] = [];
let vsr = '';
// RTX Video is SDR-only and only enlarges; otherwise Quality runs Balanced.
if (mode === 'quality' && (hdr || scale <= 1.05)) mode = 'balanced';
switch (mode) {
case 'performance':
props = { scale: 'spline36', cscale: 'spline36', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 1, 'deband-grain': 24 };
if (sharpen) shaders = ['CAS-prescale.glsl'];
break;
case 'balanced':
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 2, 'deband-grain': 16 };
shaders = [NEURAL.balanced!, 'KrigBilateral.glsl', ...(sharpen ? ['CAS.glsl'] : [])];
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 2, 'deband-grain': 12 };
shaders = [...(enhanceDenoise && !hdr ? ['nlmeans_light.glsl'] : []), NETWORK, 'KrigBilateral.glsl', ...(sharpen ? ['CAS.glsl'] : [])];
break;
case 'quality':
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 2, 'deband-grain': 12 };
shaders = [...(enhanceDenoise && !hdr ? ['nlmeans.glsl'] : []), NEURAL.quality!, 'KrigBilateral.glsl', ...(sharpen ? ['CAS.glsl'] : [])];
// The video processor deblocks as it enlarges; mpv only scales any remainder.
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 1, 'deband-grain': 8 };
vsr = `d3d11vpp=scaling-mode=nvidia:scale=${Math.min(scale, VSR_MAX_SCALE).toFixed(2)}`;
break;
default:
return { props: { ...scalerDefaults }, shaders: [] };
return { props: { ...scalerDefaults }, shaders: [], vsr };
}
if (!enhanceDeband) props.deband = false;
return { props, shaders };
return { props, shaders, vsr };
}
/** HDR as decoded (a converted stream may already be SDR), else Plex's metadata. */
@ -79,8 +104,12 @@ function isHdr() {
const shaderErrors: { at: number; text: string }[] = [];
/** Fed every mpv log line; keeps the ones that mean a user shader failed. */
/** Fed every mpv log line; keeps the ones that mean a user shader or RTX Video failed. */
export function noteMpvLog(level: string, prefix: string, text: string) {
if (/RTX Super Resolution/i.test(text) && /fail|not supported/i.test(text)) {
shaderErrors.push({ at: Date.now(), text: text.trim() });
return;
}
if (level !== 'error' && level !== 'fatal') return;
// A missing file is reported by mpv's file/stream layers; a broken one by the renderer.
if (/\.glsl/i.test(text) || (/^vo/.test(prefix) && /shader|glsl|hook|compil|spirv|parse/i.test(text))) {
@ -119,22 +148,40 @@ export async function scaleFactor(): Promise<number> {
return Math.min((osd.w - osd.ml - osd.mr) / st.video.width, (osd.h - osd.mt - osd.mb) / st.video.height);
}
/** Whether RTX Video is enlarging the picture (mpv's output exceeds the decoded size). */
async function vsrRunning() {
const st = usePlayer.getState();
const out = await mpv.get<{ w: number }>('video-out-params').catch(() => null);
return !!st.video?.width && !!out?.w && out.w > st.video.width * 1.05;
}
/**
* After a tier is applied: wait for frames, then look for shader errors in
* mpv's log, and for the passes that should be running at this size (the
* denoiser always, the network when enlarging). Either failing drops to the
* tier below.
* After a tier is applied: wait for frames, then look for shader or RTX
* Video errors in mpv's log, for the passes that should be running at this
* size (the denoiser always, the network when enlarging) and for RTX Video's
* enlarged output. Any failing drops to the tier below.
*/
async function verify(id: number, mode: Upscaling, appliedAt: number, signature: string, shaders: string[]) {
async function verify(id: number, mode: Upscaling, appliedAt: number, signature: string, { shaders, vsr }: Plan) {
for (let i = 0; i < 80 && !usePlayer.getState().firstFrame; i++) await sleep(250);
await sleep(1500);
if (id !== seq || !usePlayer.getState().open) return;
const expected: RegExp[] = [];
if (shaders.includes('nlmeans.glsl')) expected.push(/Non-local means/);
if (NEURAL[mode] && (await runsNetwork(mode))) expected.push(/feature map/);
if (shaders.includes('nlmeans_light.glsl')) expected.push(/Non-local means/);
if (shaders.includes(NETWORK) && (await scaleFactor()) > 1) expected.push(/feature map/);
let error = shaderErrors.find((e) => e.at >= appliedAt);
let missing = false;
if (!error && expected.length) {
if (!error && vsr) {
missing = true;
for (let i = 0; i < 8 && id === seq && usePlayer.getState().open; i++) {
error = shaderErrors.find((e) => e.at >= appliedAt);
if (error || (await vsrRunning())) {
missing = !!error;
break;
}
await sleep(1000);
}
}
if (!error && !missing && expected.length) {
// A first compile can hold the renderer for over a minute; wait for the
// expected passes to appear (or an error) rather than judging too early.
// Already compiled, they appear within a few frames.
@ -160,7 +207,7 @@ async function verify(id: number, mode: Upscaling, appliedAt: number, signature:
clearPreparing();
failed.add(mode);
const fallback = usable(mode);
console.warn('[upscaling]', mode, 'failed:', error?.text ?? 'network passes not running');
console.warn('[upscaling]', mode, 'failed:', error?.text ?? (vsr ? 'RTX Video output not enlarged' : 'network passes not running'));
toast(`${UPSCALING[mode].label} upscaling couldn’t start. Using ${UPSCALING[fallback].label}.`, 'error');
requestEnhancement();
}
@ -199,14 +246,14 @@ function markWarm(signature: string) {
}
if (usePlayer.getState().enhance.preparing) usePlayer.setState({ enhance: { ...usePlayer.getState().enhance, preparing: false } });
}
/** Tiers whose shaders failed this session. */
/** Tiers that failed this session. */
const failed = new Set<Upscaling>();
let missingWarned = false;
/** The chosen tier, or the nearest one below it that hasn't failed. */
/** The chosen tier, or the nearest one below it that this computer can run and hasn't failed. */
function usable(mode: Upscaling): Upscaling {
let i = UPSCALING_ORDER.indexOf(mode);
while (i > 0 && failed.has(UPSCALING_ORDER[i])) i--;
while (i > 0 && (failed.has(UPSCALING_ORDER[i]) || !tierAvailable(UPSCALING_ORDER[i]))) i--;
return UPSCALING_ORDER[i];
}
@ -224,7 +271,8 @@ async function apply(id: number, requested: Upscaling) {
}
const bypass = usePlayer.getState().enhance.bypass;
let mode = usable(requested);
let { props, shaders } = plan(bypass ? 'off' : mode, isHdr());
const scale = await scaleFactor();
let { props, shaders, vsr } = plan(bypass ? 'off' : mode, isHdr(), scale);
const dir = await (shaderDir ??= resourcePath('shaders').catch(() => ''));
if (shaders.length && !dir) {
// No shaders at all: keep the scaler and debanding settings only.
@ -232,7 +280,7 @@ async function apply(id: number, requested: Upscaling) {
missingWarned = true;
shaders = [];
if (mode !== 'performance') mode = 'performance';
({ props } = plan(mode, isHdr()));
({ props, vsr } = plan(mode, isHdr(), scale));
}
// Decided before touching mpv: while a shader compiles, mpv holds option
// changes until it finishes, so a notice set afterwards would come too late.
@ -246,7 +294,7 @@ async function apply(id: number, requested: Upscaling) {
if (id === seq && usePlayer.getState().enhance.preparing) toast(`Preparing ${UPSCALING[mode].label} upscaling for the first time. The picture may pause for a moment.`);
}, PREPARING_NOTICE_MS);
const settings = JSON.stringify({ props, shaders });
const settings = JSON.stringify({ props, shaders, vsr });
if (settings !== lastApplied) {
lastApplied = settings;
lastAppliedAt = Date.now();
@ -257,10 +305,13 @@ async function apply(id: number, requested: Upscaling) {
const list = shaders.map((n) => `${dir}${windows ? '\\' : '/'}${n}`).join(windows ? ';' : ':');
await mpv.set('glsl-shaders', list).catch((e) => shaderErrors.push({ at: Date.now(), text: String(e) }));
} else await mpv.command('change-list', 'glsl-shaders', 'clr', '').catch(() => {});
// Replaced by label; removing one that isn't there is harmless.
await mpv.command('vf', 'remove', VSR_LABEL).catch(() => {});
if (vsr) await mpv.command('vf', 'add', `${VSR_LABEL}:${vsr}`).catch((e) => shaderErrors.push({ at: Date.now(), text: String(e) }));
}
// Errors count from when these shaders actually reached mpv, even if this
// re-apply changed nothing (mpv may have already reported a failure).
if (!bypass && shaders.length) verify(id, mode, lastAppliedAt, signature, shaders);
if (!bypass && (shaders.length || vsr)) verify(id, mode, lastAppliedAt, signature, { props, shaders, vsr });
}
/**
@ -309,6 +360,8 @@ const STAGES: [RegExp, string][] = [
export async function readDiagnostics(): Promise<Diagnostics> {
const passes = await renderPasses();
const stages = STAGES.filter(([re]) => passes.some((p) => re.test(p.desc))).map(([, name]) => name);
// RTX Video runs in the GPU's video processor, before (and outside) mpv's passes.
if (await vsrRunning()) stages.unshift('RTX Video Super Resolution');
const scaler = passes.map((p) => /(up|down)scaling \(([\w-]+)\)/.exec(p.desc)).find(Boolean);
if (scaler) stages.push(`${scaler[2]} ${scaler[1]}scaling`);
const fps = (await mpv.get<number>('estimated-vf-fps').catch(() => 0)) || (await mpv.get<number>('container-fps').catch(() => 0)) || 24;
@ -355,3 +408,23 @@ useSettings.subscribe((prefs, prev) => {
if (!isNative || !usePlayer.getState().open) return;
if (prefs.upscaling !== prev.upscaling || prefs.enhanceDeband !== prev.enhanceDeband || prefs.enhanceSharpen !== prev.enhanceSharpen || prefs.enhanceDenoise !== prev.enhanceDenoise) requestEnhancement();
});
// RTX Video enlarges by a fixed factor, so Quality follows the video's size
// (known only once decoding starts), the miniplayer and the window.
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
function followSize(delay: number) {
const st = usePlayer.getState();
if (!isNative || !st.open || usable(useSettings.getState().upscaling) !== 'quality') return;
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => requestEnhancement(), delay);
}
let following = false;
/** Called by the player when it opens (not at import: the store imports this module). */
export function followVideoSize() {
if (following) return;
following = true;
usePlayer.subscribe((st, prev) => {
if (st.video?.width !== prev.video?.width || st.video?.height !== prev.video?.height || st.mini !== prev.mini) followSize(st.mini !== prev.mini ? 600 : 0);
});
window.addEventListener('resize', () => followSize(400));
}

View file

@ -4,7 +4,7 @@ import { directUrl, previewUrl, reportTimeline, stopTranscode, transcodeUrl, typ
import type { Item, Stream } from '../plex/types';
import { useSession } from '../app/session';
import { useSettings, SUBTITLE_MARGIN, type Preferences, type Quality, type Upscaling } from '../app/settings';
import { noteMpvLog, requestEnhancement, watchPerformance } from './enhance';
import { followVideoSize, noteMpvLog, requestEnhancement, watchPerformance } from './enhance';
import { channelLabel } from '../app/format';
import { invalidateLibrary } from '../app/queries';
import { keepAwake, isNative, win } from '../platform/native';
@ -41,6 +41,8 @@ interface PlayerState {
quality: Quality;
firstFrame: boolean;
error: string;
/** The server owner stopped this stream (error holds their message). */
terminated: boolean;
position: number;
duration: number;
cacheTime: number;
@ -95,6 +97,8 @@ interface PlayerState {
let session = '';
let startOffsetMs = 0;
let lastReport = 0;
/** Plex has answered a report for this session without a termination. */
let sessionAnswered = false;
let reportTimer: ReturnType<typeof setInterval> | null = null;
let countdownTimer: ReturnType<typeof setInterval> | null = null;
let scrobbled = false;
@ -208,14 +212,49 @@ async function applySubtitleStyle(prefs: Preferences = useSettings.getState()) {
}
}
function report(state: 'playing' | 'paused' | 'buffering' | 'stopped') {
/** Reports progress to Plex; resolves true if the reply says the stream was stopped. */
function report(state: 'playing' | 'paused' | 'buffering' | 'stopped'): Promise<boolean> {
const s = server();
const { item, position, delivery } = usePlayer.getState();
if (!s || !item || !session || item.type === 'clip') return;
if (!s || !item || !session || item.type === 'clip') return Promise.resolve(false);
lastReport = Date.now();
const extra: Record<string, string | number> = {};
if (delivery?.mode === 'transcode' && delivery.session) extra['X-Plex-Session-Identifier'] = delivery.session;
reportTimeline(s, item, state, position * 1000, session, extra).catch(() => {});
const reported = session;
return reportTimeline(s, item, state, position * 1000, session, extra)
.then((reply) => {
if (reported !== session) return false;
if (!reply.terminationText) {
sessionAnswered = true;
return false;
}
// Plex repeats a termination to this client until it reports a stop.
// On a session's first reply it is left over from an earlier stream
// (this one can't have been stopped yet): clear it and carry on.
reportTimeline(s, item, 'stopped', position * 1000, session, extra).catch(() => {});
if (!sessionAnswered) return false;
onTerminated(reply.terminationText);
return true;
})
.catch(() => false);
}
/**
* The server owner stopped this stream. Plex cuts the connection, so mpv would
* play out its buffer and then wait forever; stop it and show their message.
*/
function onTerminated(text: string) {
const st = usePlayer.getState();
if (!st.open || st.terminated) return;
if (reportTimer) clearInterval(reportTimer);
reportTimer = null;
stopCountdown();
keepAwake(false);
watchPerformance(false);
const s = server();
if (st.delivery?.session && s) stopTranscode(s, st.delivery.session);
usePlayer.setState({ error: text, terminated: true, buffering: false, countdown: null });
if (isNative) mpv.command('stop').catch(() => {});
}
function checkScrobble() {
@ -366,6 +405,8 @@ function onEvent(e: MpvEvent) {
break;
case 'paused-for-cache':
usePlayer.setState({ buffering: !!v });
// A stall can mean the server stopped the stream; its reply says so.
if (v && Date.now() - lastReport > 2000) report('buffering');
break;
case 'seeking':
usePlayer.setState({ seeking: !!v });
@ -435,8 +476,14 @@ function onEvent(e: MpvEvent) {
break;
case 'end-file':
if (e.reason === 'error') {
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
fallbackAfterError();
// A stream the server owner stopped can fail outright; don't retry that.
// (Briefly: an unreachable server shouldn't hold up the error.)
const failed = session;
Promise.race([report('buffering'), new Promise<boolean>((r) => setTimeout(() => r(false), 3000))]).then((terminated) => {
if (terminated || !usePlayer.getState().open || session !== failed) return;
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
fallbackAfterError();
});
} else if (e.reason === 'eof') onEnded();
break;
case 'log':
@ -481,6 +528,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
quality: 'original',
firstFrame: false,
error: '',
terminated: false,
position: 0,
duration: 0,
cacheTime: 0,
@ -531,6 +579,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
item: input,
firstFrame: false,
error: '',
terminated: false,
position: (opts.offsetMs ?? 0) / 1000,
duration: input.duration / 1000,
cacheTime: 0,
@ -566,6 +615,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
const local = useSession.getState().connection?.local ?? true;
const quality: Quality = opts.quality ?? (local ? prefs.quality : prefs.remoteQuality);
session = crypto.randomUUID();
sessionAnswered = false;
scrobbled = false;
let delivery: Delivery;
@ -600,11 +650,14 @@ export const usePlayer = create<PlayerState>((set, get) => ({
await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough });
if (!unlisten) unlisten = await mpv.on(onEvent);
if (token !== loadToken) return;
// mpv keeps pause across files: a title paused and closed would start paused.
await mpv.set('pause', false);
await mpv.set('mute', false);
await mpv.set('volume', sliderToMpv(prefs.volume));
await mpv.set('speed', 1);
await mpv.set('audio-delay', 0);
await applySubtitleStyle(prefs);
followVideoSize();
await requestEnhancement();
watchPerformance(true);
await mpv.set('force-media-title', item.type === 'episode' ? `${item.grandparentTitle} — ${item.title}` : item.title);
@ -643,7 +696,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
await mpv.command('stop').catch(() => {});
await mpv.show(false).catch(() => {});
}
set({ open: false, mini: false, item: null, delivery: null, error: '', countdown: null, nextUp: null, firstFrame: false });
set({ open: false, mini: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, firstFrame: false });
const fs = await win.isFullscreen().catch(() => false);
if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false);
if (st.item) invalidateLibrary();