diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx
index 5843ece..568bd6a 100644
--- a/src/player/PlayerOverlay.tsx
+++ b/src/player/PlayerOverlay.tsx
@@ -758,7 +758,7 @@ function MiniPlayer() {
- {(loading || st.buffering) && !st.error ? (
+ {(loading || st.buffering || st.reconnecting) && !st.error ? (
) : st.error ? (
Playback stopped
@@ -965,10 +965,12 @@ export function PlayerOverlay() {
{!st.fullscreen && }
- {(loading || st.buffering || st.seeking || preparing) && !st.error && (
+ {(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
- {preparing && (
+ {st.reconnecting ? (
+
Lost connection to {server?.name ?? 'the server'}
+ ) : preparing && (
Preparing {UPSCALING[st.enhance.active].label} upscaling
First time on this computer only
@@ -1057,6 +1059,9 @@ export function PlayerOverlay() {
)}
+
diff --git a/src/player/miniWindow.ts b/src/player/miniWindow.ts
index 2f1966c..eebe2b2 100644
--- a/src/player/miniWindow.ts
+++ b/src/player/miniWindow.ts
@@ -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,
};
}
diff --git a/src/player/store.test.ts b/src/player/store.test.ts
index e129b1d..df87345 100644
--- a/src/player/store.test.ts
+++ b/src/player/store.test.ts
@@ -5,7 +5,7 @@ const harness = vi.hoisted(() => {
const memory = new Map
();
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();
+ });
+});
diff --git a/src/player/store.ts b/src/player/store.ts
index bbdd4d8..0606a41 100644
--- a/src/player/store.ts
+++ b/src/player/store.ts
@@ -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((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 | 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 {
+ 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((set, get) => ({
firstFrame: false,
error: '',
terminated: false,
+ reconnecting: false,
position: 0,
duration: 0,
cacheTime: 0,
@@ -720,6 +785,8 @@ export const usePlayer = create((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((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((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((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((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((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((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 });
diff --git a/src/ui/Icon.tsx b/src/ui/Icon.tsx
index 04d1b54..0d94c62 100644
--- a/src/ui/Icon.tsx
+++ b/src/ui/Icon.tsx
@@ -13,6 +13,7 @@ const PATHS: Record = {
arrowLeft: '',
play: '',
pause: '',
+ stop: '',
plus: '',
minus: '',
check: '',