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:
parent
6775d29249
commit
624f01f745
5 changed files with 152 additions and 12 deletions
|
|
@ -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 });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue