Add a stop button to the player and resume after a server outage

The full player had no way to stop: Back only moved playback to the
miniplayer. A stop button now sits with the right-hand controls and
closes the player outright, as the miniplayer's close button does.

When the server went away mid-stream, mpv played out its buffer and then
took the cut-off stream for the end of the file: the title counted as
ended (opening Up Next for episodes), and Play restarted it from 0. A
stream ending more than 15 s before its duration is now treated as a
lost connection: the player shows "Lost connection to <server>", checks
/identity every few seconds, and reloads in place at the same position
(staying in the miniplayer) once the server answers; Play tries at once.
A second cut-off at the same spot counts as the real end of the file.

A file left paused at its end (keep-open) re-paused as soon as it was
unpaused, so the reload is unpaused again after loadfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-17 10:41:52 -07:00
parent 6775d29249
commit 624f01f745
5 changed files with 152 additions and 12 deletions

View file

@ -758,7 +758,7 @@ function MiniPlayer() {
</button>
</div>
<div className="mini-center">
{(loading || st.buffering) && !st.error ? (
{(loading || st.buffering || st.reconnecting) && !st.error ? (
<Spinner size={30} />
) : st.error ? (
<span className="mini-error">Playback stopped</span>
@ -965,10 +965,12 @@ export function PlayerOverlay() {
{!st.fullscreen && <WindowControls />}
</div>
{(loading || st.buffering || st.seeking || preparing) && !st.error && (
{(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
<div className="player-center">
<Spinner size={44} />
{preparing && (
{st.reconnecting ? (
<p className="player-preparing">Lost connection to {server?.name ?? 'the server'}</p>
) : preparing && (
<p className="player-preparing">
Preparing {UPSCALING[st.enhance.active].label} upscaling
<small>First time on this computer only</small>
@ -1057,6 +1059,9 @@ export function PlayerOverlay() {
)}
</div>
<div className="player-controls-right">
<button className="player-icon" aria-label="Stop playback" title="Stop" onClick={() => st.close()}>
<Icon name="stop" size={19} />
</button>
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
<Icon name="captions" size={23} />
</button>

View file

@ -30,6 +30,7 @@ interface PlayerView {
duration: number;
firstFrame: boolean;
buffering: boolean;
reconnecting: boolean;
error: string;
}
@ -50,7 +51,8 @@ function view(st: PlayerView): MiniState {
position: st.position,
duration: st.duration,
loading: !st.firstFrame && !st.error,
buffering: st.buffering,
// Waiting for the server to come back shows as buffering.
buffering: st.buffering || st.reconnecting,
error: !!st.error,
};
}

View file

@ -5,7 +5,7 @@ const harness = vi.hoisted(() => {
const memory = new Map<string, string>();
vi.stubGlobal('localStorage', { getItem: (k: string) => memory.get(k) ?? null, setItem: (k: string, v: string) => memory.set(k, v), removeItem: (k: string) => memory.delete(k) });
vi.stubGlobal('document', Object.assign(new EventTarget(), { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } }));
return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true };
return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true, identity: vi.fn() };
});
vi.mock('../platform/native', () => ({
@ -20,7 +20,7 @@ vi.mock('./engine', () => ({ mpv: {
} }));
vi.mock('../app/session', async () => {
const { create } = await import('zustand');
return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only' }, connection: { local: true } })) };
return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only', name: 'Test', get: harness.identity }, connection: { local: true } })) };
});
vi.mock('../downloads/store', () => ({ useDownloads: { getState: () => ({ items: [] }) } }));
vi.mock('../app/queries', () => ({ invalidateLibrary: vi.fn() }));
@ -42,7 +42,11 @@ const episode = (id = '1') => parseItem({ ratingKey: id, type: 'episode', title:
Media: [{ Part: [{ key: '/video', Stream: [{ id: 'audio', streamType: 2 }] }] }],
});
const time = (position: number) => harness.event({ type: 'property', name: 'time-pos', value: position });
const eof = () => harness.event({ type: 'end-file', reason: 'eof' });
/** The stream ending at `position` (by default the real end of the 100 s episode). */
const eof = (position = 99.6) => {
usePlayer.setState({ position });
harness.event({ type: 'end-file', reason: 'eof' });
};
beforeEach(async () => {
vi.useFakeTimers();
@ -226,3 +230,51 @@ describe('Up Next playback lifecycle', () => {
expect(usePlayer.getState()).toMatchObject({ open: false, postPlay: false, countdown: null });
});
});
describe('Losing the server mid-stream', () => {
it('waits for the server instead of ending when the stream is cut off early', () => {
eof(42);
expect(usePlayer.getState()).toMatchObject({ reconnecting: true, ended: false, postPlay: false });
});
it('resumes from where it stopped once the server answers again', async () => {
const original = usePlayer.getState().play;
const play = vi.fn().mockResolvedValue(undefined);
usePlayer.setState({ play });
harness.identity.mockRejectedValueOnce(new Error('unreachable'));
eof(42);
await vi.advanceTimersByTimeAsync(2000);
expect(play).not.toHaveBeenCalled();
expect(usePlayer.getState().reconnecting).toBe(true);
harness.identity.mockResolvedValueOnce({});
await vi.advanceTimersByTimeAsync(3000);
expect(play).toHaveBeenCalledWith(expect.objectContaining({ id: '1' }), expect.objectContaining({ offsetMs: 42000, keepMini: true }));
expect(usePlayer.getState().reconnecting).toBe(false);
usePlayer.setState({ play: original });
});
it('tries straight away on Play instead of starting over', async () => {
const original = usePlayer.getState().play;
const play = vi.fn().mockResolvedValue(undefined);
usePlayer.setState({ play });
harness.identity.mockResolvedValueOnce({});
eof(42);
usePlayer.getState().togglePause();
await vi.waitFor(() => expect(play).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ offsetMs: 42000 })));
expect(mpv.command).not.toHaveBeenCalledWith('seek', '0.000', 'absolute+exact');
usePlayer.setState({ play: original });
});
it('treats a second cut-off at the same place as the real end of the file', async () => {
harness.identity.mockResolvedValueOnce({});
eof(42);
await vi.advanceTimersByTimeAsync(2000);
usePlayer.setState({ firstFrame: true });
eof(42.5);
expect(usePlayer.getState()).toMatchObject({ reconnecting: false, ended: true });
});
it('stops waiting when the player is closed', async () => {
eof(42);
await usePlayer.getState().close();
harness.identity.mockClear();
await vi.advanceTimersByTimeAsync(10000);
expect(harness.identity).not.toHaveBeenCalled();
});
});

View file

@ -36,6 +36,8 @@ export interface PlayOptions {
quality?: Quality;
/** Keep these track choices (UI keys) instead of applying the preferences again. */
tracks?: { audioKey: string; subKey: string };
/** Reloading the same title in place (after an outage): stay in the miniplayer if it's there. */
keepMini?: boolean;
}
interface PlayerState {
@ -48,6 +50,8 @@ interface PlayerState {
error: string;
/** The server owner stopped this stream (error holds their message). */
terminated: boolean;
/** The stream was cut off before the end (the server went away); waiting for it to come back. */
reconnecting: boolean;
position: number;
duration: number;
cacheTime: number;
@ -597,7 +601,7 @@ function onEvent(e: MpvEvent) {
}
break;
case 'eof-reached':
if (v === true) onEnded();
if (v === true) onStreamEnd();
break;
}
break;
@ -618,11 +622,14 @@ function onEvent(e: MpvEvent) {
// (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;
const now = usePlayer.getState();
if (terminated || !now.open || session !== failed) return;
// Partway through a stream that was playing, it's the connection that failed.
if (cutShort(now)) return onStreamEnd();
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
fallbackAfterError();
});
} else if (e.reason === 'eof') onEnded();
} else if (e.reason === 'eof') onStreamEnd();
break;
case 'log':
noteMpvLog(e.level, e.prefix, e.text);
@ -655,6 +662,63 @@ function maybeCredits(pos: number) {
} else if (!st.postPlayDismissed) openPostPlay();
}
/**
* A streamed title stopping well short of its end means the connection went
* (mpv plays out its buffer, then sees the cut-off stream as the end of the file).
*/
const CUT_SHORT_MARGIN = 15;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
/** Where the last cut-off happened, so a file that really does end early isn't retried forever. */
let lastCutAt: number | null = null;
function cutShort(st: PlayerState) {
return st.delivery?.mode !== 'local' && st.firstFrame && st.duration > 0 && st.position < st.duration - CUT_SHORT_MARGIN;
}
/** The stream ran out: a real ending, or a lost connection to wait out. */
function onStreamEnd() {
const st = usePlayer.getState();
if (!cutShort(st)) return onEnded();
if (st.reconnecting || st.ended) return;
// Cut off at the same place again once the server answered: the file itself ends there.
if (lastCutAt !== null && Math.abs(st.position - lastCutAt) < 5) return onEnded();
lastCutAt = st.position;
usePlayer.setState({ reconnecting: true, buffering: false });
keepAwake(false);
scheduleReconnect(2000);
}
function stopReconnecting() {
if (reconnectTimer) clearTimeout(reconnectTimer);
reconnectTimer = null;
}
function scheduleReconnect(delay: number) {
stopReconnecting();
reconnectTimer = setTimeout(() => void tryReconnect(), delay);
}
/** Resumes where the stream was cut off if the server answers; otherwise checks again shortly. */
async function tryReconnect(): Promise<boolean> {
stopReconnecting();
const st = usePlayer.getState();
const s = server();
if (!st.open || !st.reconnecting || !st.item || !s) return false;
const reachable = await s.get('/identity', undefined, { timeout: 4000 }).then(
() => true,
() => false,
);
const now = usePlayer.getState();
if (!now.open || !now.reconnecting || now.item?.id !== st.item.id) return false;
if (!reachable) {
scheduleReconnect(3000);
return false;
}
usePlayer.setState({ reconnecting: false });
await now.play(now.item, { offsetMs: now.position * 1000, mediaIndex: now.mediaIndex, quality: now.quality, tracks: currentTracks(now), keepMini: true });
return true;
}
function onEnded() {
const st = usePlayer.getState();
if (st.ended) return;
@ -677,6 +741,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
firstFrame: false,
error: '',
terminated: false,
reconnecting: false,
position: 0,
duration: 0,
cacheTime: 0,
@ -720,6 +785,8 @@ export const usePlayer = create<PlayerState>((set, get) => ({
return;
}
const previous = get();
stopReconnecting();
if (previous.item?.id !== input.id) lastCutAt = null;
// The previous title's reporting ends here, against its own server.
if (reportTimer) clearInterval(reportTimer);
reportTimer = null;
@ -748,6 +815,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
firstFrame: false,
error: '',
terminated: false,
reconnecting: false,
position: (opts.offsetMs ?? 0) / 1000,
lastSeek: 0,
duration: input.duration / 1000,
@ -769,7 +837,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
subKey: opts.tracks?.subKey ?? '__init',
video: null,
fullscreen: fullscreenNow,
mini: false,
mini: opts.keepMini ? previous.open && previous.mini : false,
videoGamma: '',
enhance: { ...previous.enhance, bypass: false, preparing: false },
});
@ -866,6 +934,9 @@ export const usePlayer = create<PlayerState>((set, get) => ({
offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none',
].join(',');
await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts);
// A file left paused at its end (keep-open) re-pauses as soon as it's unpaused
// above, so a reload in place (after an outage) would open paused: unpause again.
await mpv.set('pause', false);
if (stale()) return;
keepAwake(true);
report('buffering');
@ -884,6 +955,8 @@ export const usePlayer = create<PlayerState>((set, get) => ({
loadToken++;
const st = get();
stopCountdown();
stopReconnecting();
lastCutAt = null;
if (reportTimer) clearInterval(reportTimer);
reportTimer = null;
if (st.item && !st.error) report('stopped');
@ -901,7 +974,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
await mpv.command('stop').catch(() => {});
await mpv.show(false).catch(() => {});
}
set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false });
set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, reconnecting: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false });
// Closing the full player hands back the window it found; closing the
// miniplayer leaves browsing as it is, full screen or not.
if (!st.mini) {
@ -913,6 +986,13 @@ export const usePlayer = create<PlayerState>((set, get) => ({
togglePause() {
const st = get();
// Play while the server is away: try it now rather than at the next check.
if (st.reconnecting) {
tryReconnect().then((resumed) => {
if (!resumed && get().reconnecting) toast(`Still can’t reach ${server()?.name ?? 'the server'}.`);
});
return;
}
if (st.ended) {
st.seek(0);
set({ ended: false });

View file

@ -13,6 +13,7 @@ const PATHS: Record<string, string> = {
arrowLeft: '<path d="M19 12H5m6-6-6 6 6 6"/>',
play: '<path d="M7 4.8v14.4a.8.8 0 0 0 1.2.7l11.6-7.2a.8.8 0 0 0 0-1.4L8.2 4.1a.8.8 0 0 0-1.2.7Z" fill="currentColor" stroke="none"/>',
pause: '<rect x="6" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/><rect x="14" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/>',
stop: '<rect x="5.5" y="5.5" width="13" height="13" rx="1.6" fill="currentColor" stroke="none"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
minus: '<path d="M5 12h14"/>',
check: '<path d="m5 12.5 4.2 4.2L19 7"/>',