All files / src/hooks useMpv.ts

86.71% Statements 261/301
85.5% Branches 59/69
100% Functions 2/2
86.71% Lines 261/301

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 3961x 1x   1x                   1x 1x 1x 1x 1x 1x 1x 1x   1x 77x 77x 77x 77x       77x 77x     77x         77x                   77x 77x 77x 77x 4x 4x 4x 1x 1x 4x 77x 77x 77x     77x 26x 1x 1x 26x 26x     77x     77x 26x 1x 26x 26x     77x       77x 26x 26x 26x 4x 4x 4x 4x 4x 4x 4x 26x 26x 3x 3x 3x           3x 3x       3x 26x       26x 3x 3x 2x 2x 2x 3x 26x 26x 1x 1x 1x 1x 1x 26x 26x 1x 1x 1x 1x 1x 1x       26x 26x                             77x             77x 77x 26x 26x 26x 26x 26x 26x 26x 5x 5x 26x 26x 77x       77x 77x 77x             77x 77x 27x 77x 77x 33x 77x 77x 35x 77x 77x 35x 6x 6x 77x           77x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x       6x             6x 4x 4x   5x 5x 5x 5x 5x 5x 5x 5x 5x     4x 6x 1x 1x 1x 6x 5x 5x 77x                     77x 26x 49x 49x 49x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 49x 26x 26x 77x   77x 2x 2x 2x 1x 1x 1x 1x 77x   77x 2x 2x 2x 1x 1x 1x 1x 77x   77x 1x 1x 1x 1x 1x     77x   77x 1x 1x 1x 1x 1x     77x   77x 1x 1x 1x 1x 1x     77x             77x   77x 34x 34x 33x 33x 33x 33x 33x 33x 33x 33x 33x 34x 1x 1x 77x   77x 26x 26x 26x 26x       77x   77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x  
import { useState, useCallback, useRef, useEffect } from "react";
import { listen } from "@tauri-apps/api/event";
import type { PlayerState } from "@/lib/types";
import {
	mpvLoad,
	mpvPlay,
	mpvPause,
	mpvStop,
	mpvSeek,
	mpvSetVolume,
	mpvGetState,
} from "@/lib/tauri";
 
const DEFAULT_STATE: PlayerState = {
	isPlaying: false,
	isPaused: false,
	currentUrl: null,
	volume: 100,
	position: 0,
	duration: 0,
};
 
export const useMpv = () => {
	const [state, setState] = useState<PlayerState>(DEFAULT_STATE);
	const [error, setError] = useState<string | null>(null);
	const [fallbackActive, setFallbackActive] = useState(false);
	const [firstFrameReady, setFirstFrameReady] = useState(false);
	// Set while the Rust-side reconnect monitor is re-issuing loadfile after
	// a network-induced EndFile(Error). Cleared on the matching `mpv://reconnected`
	// event or whenever the user starts a fresh load.
	const [reconnecting, setReconnecting] = useState(false);
	const [reconnectAttempt, setReconnectAttempt] = useState(0);
	// `buffering` reflects mpv's `paused-for-cache` flag with a short debounce
	// so brief stalls during startup / seeks don't flash the indicator.
	const [buffering, setBuffering] = useState(false);
	// Set to true when the Rust-side reconnect monitor has exhausted its
	// retry budget. Indicates the URL is genuinely unreachable (DNS failure,
	// server down, or the user is offline). Cleared on the next successful
	// load / explicit stop.
	const [loadFailed, setLoadFailed] = useState(false);
	// `recentlyRecovered` is an explicit positive-acknowledgement signal that
	// powers the green "Connection restored" banner. We drive it directly off
	// the `mpv://reconnected` event (and the navigator.onLine auto-recovery
	// path) rather than inferring it from "all flags are false now" because
	// the flag transitions don't always collapse to idle in one render tick:
	// e.g. when our `eof-reached` path triggered the retry, the demuxer EOF'd
	// before the cache "refilled" event, so `mpv://buffered` may never fire
	// and `buffering` stays stuck true — which would mask the recovered
	// transition under the old flag-inference logic.
	const [recentlyRecovered, setRecentlyRecovered] = useState(false);
	const bufferingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
	const recoveredTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
	const flashRecovered = useCallback(() => {
		if (recoveredTimerRef.current) clearTimeout(recoveredTimerRef.current);
		setRecentlyRecovered(true);
		recoveredTimerRef.current = setTimeout(() => {
			setRecentlyRecovered(false);
			recoveredTimerRef.current = null;
		}, 2500);
	}, []);
	const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
	const loadingRef = useRef(false);
 
	// Listen for fallback event emitted when embedded renderer fails.
	useEffect(() => {
		const unlistenPromise = listen<{ reason: string }>("mpv://render-fallback", (event) => {
			console.warn("[useMpv] render fallback:", event.payload.reason);
			setFallbackActive(true);
		});
		return () => {
			unlistenPromise.then((fn) => fn());
		};
	}, []);
 
	// Listen for first-frame event so the frontend knows when the video is actually visible.
	useEffect(() => {
		const unlistenPromise = listen("mpv://first-frame", () => {
			setFirstFrameReady(true);
		});
		return () => {
			unlistenPromise.then((fn) => fn());
		};
	}, []);
 
	// Listen for reconnect lifecycle events emitted by the Rust-side
	// auto-reconnect monitor (see crates/tauri-plugin-mpv/src/reconnect.rs).
	useEffect(() => {
		const reconnectingP = listen<{ url: string; attempt: number }>(
			"mpv://reconnecting",
			(event) => {
				console.warn(
					`[useMpv] reconnecting (attempt #${event.payload.attempt}):`,
					event.payload.url
				);
				setReconnecting(true);
				setReconnectAttempt(event.payload.attempt);
			}
		);
		const reconnectedP = listen<{ url: string }>("mpv://reconnected", (event) => {
			console.info("[useMpv] reconnected:", event.payload.url);
			setReconnecting(false);
			setReconnectAttempt(0);
			// Defensive: if our `eof-reached` path drove the retry, the
			// demuxer EOF'd while paused-for-cache was already false, so the
			// Rust monitor's "buffered" emission would never fire and
			// `buffering` would stay stuck true. Clear it explicitly here so
			// the recovered banner isn't masked by stale buffering state.
			setBuffering(false);
			if (bufferingTimerRef.current) {
				clearTimeout(bufferingTimerRef.current);
				bufferingTimerRef.current = null;
			}
			flashRecovered();
		});
		// Buffering lifecycle (paused-for-cache observation in Rust). Debounce
		// the "true" transition by 1.5 s so brief stalls during startup or seek
		// don't flash the connection-issues indicator.
		const bufferingP = listen<{ url: string }>("mpv://buffering", () => {
			if (bufferingTimerRef.current) clearTimeout(bufferingTimerRef.current);
			bufferingTimerRef.current = setTimeout(() => {
				console.warn("[useMpv] buffering (stream stalled)");
				setBuffering(true);
				bufferingTimerRef.current = null;
			}, 1500);
		});
		const bufferedP = listen<{ url: string }>("mpv://buffered", () => {
			if (bufferingTimerRef.current) {
				clearTimeout(bufferingTimerRef.current);
				bufferingTimerRef.current = null;
			}
			setBuffering(false);
		});
		const loadFailedP = listen<{ url: string }>("mpv://load-failed", (event) => {
			console.error("[useMpv] load failed (retries exhausted):", event.payload.url);
			setLoadFailed(true);
			setReconnecting(false);
			setReconnectAttempt(0);
			setBuffering(false);
			if (bufferingTimerRef.current) {
				clearTimeout(bufferingTimerRef.current);
				bufferingTimerRef.current = null;
			}
		});
		return () => {
			reconnectingP.then((fn) => fn());
			reconnectedP.then((fn) => fn());
			bufferingP.then((fn) => fn());
			bufferedP.then((fn) => fn());
			loadFailedP.then((fn) => fn());
			if (bufferingTimerRef.current) {
				clearTimeout(bufferingTimerRef.current);
				bufferingTimerRef.current = null;
			}
			if (recoveredTimerRef.current) {
				clearTimeout(recoveredTimerRef.current);
				recoveredTimerRef.current = null;
			}
		};
	}, [flashRecovered]);
 
	// On mount, check if mpv is already playing (e.g. user navigated away and back).
	// If so, restore firstFrameReady immediately so the background turns transparent.
	// Skip if a load was triggered during this mount cycle — the loadedThisMountRef
	// flag prevents a race where the async mpvGetState() resolves after load()
	// completes and incorrectly sets firstFrameReady before the first frame renders.
	const loadedThisMountRef = useRef(false);
	useEffect(() => {
		mpvGetState()
			.then((s) => {
				if (
					!loadingRef.current &&
					!loadedThisMountRef.current &&
					(s.isPlaying || s.isPaused)
				) {
					setFirstFrameReady(true);
				}
			})
			.catch(() => {});
	}, []);
 
	// Refs that mirror state so the `online` listener (registered once)
	// reads the latest values without re-binding on every poll.
	const loadFailedRef = useRef(false);
	const reconnectingRef = useRef(false);
	const currentUrlRef = useRef<string | null>(null);
	// Sticky last-good position. We need this (rather than `state.position`)
	// for resume-on-recovery because during a Rust-side retry the polled
	// position can briefly drop to 0 as the new loadfile is initialising —
	// capturing the position at the moment of recovery would land us at
	// 00:00. `lastKnownPositionRef` only ever takes ON forward progress,
	// so an outage-time recovery sees the pre-outage position.
	const lastKnownPositionRef = useRef(0);
	useEffect(() => {
		loadFailedRef.current = loadFailed;
	}, [loadFailed]);
	useEffect(() => {
		reconnectingRef.current = reconnecting;
	}, [reconnecting]);
	useEffect(() => {
		currentUrlRef.current = state.currentUrl;
	}, [state.currentUrl]);
	useEffect(() => {
		if (state.position > 1.0) {
			lastKnownPositionRef.current = state.position;
		}
	}, [state.position]);
 
	// `load(url)` is a fresh start from 00:00 (used for channel switches /
	// initial play). `load(url, startPos)` is a resume — used by the
	// `online`-triggered auto-recovery and by the Retry button to preserve
	// playback position across a hard restart of the mpv instance.
	const load = useCallback(async (url: string, startPos?: number) => {
		if (loadingRef.current) return;
		loadingRef.current = true;
		loadedThisMountRef.current = true;
		setError(null);
		setFallbackActive(false);
		setFirstFrameReady(false);
		setReconnecting(false);
		setReconnectAttempt(0);
		setBuffering(false);
		setLoadFailed(false);
		setRecentlyRecovered(false);
		if (bufferingTimerRef.current) {
			clearTimeout(bufferingTimerRef.current);
			bufferingTimerRef.current = null;
		}
		if (recoveredTimerRef.current) {
			clearTimeout(recoveredTimerRef.current);
			recoveredTimerRef.current = null;
		}
		// Fresh-start load resets the sticky position so a subsequent
		// recovery for this URL can't accidentally resume into a position
		// inherited from a previous channel.
		if (startPos === undefined) {
			lastKnownPositionRef.current = 0;
		}
		// Reset playing state and position immediately so the bar doesn't show stale values.
		setState((s) => ({
			...s,
			isPlaying: false,
			isPaused: false,
			position: startPos ?? 0,
			duration: 0,
		}));
		try {
			await mpvLoad(url, startPos);
			// Don't set isPlaying optimistically — let the next poll confirm it from Rust
			// so transparency only kicks in once MPV is actually rendering frames.
			setState((s) => ({ ...s, currentUrl: url }));
		} catch (e) {
			const msg = String(e);
			setError(msg);
			throw e;
		} finally {
			loadingRef.current = false;
		}
	}, []);
 
	// Auto-recover when the OS reports the network came back online while
	// we're either parked in `loadFailed` OR actively `reconnecting`. The
	// Rust-side reconnect monitor sits on an exponential backoff between
	// attempts (up to 30 s); without this hook the red banner would stay up
	// for the full backoff window even though the user knows their internet
	// is already back. By calling `load(currentUrl)` we hard-reset the mpv
	// instance immediately: the new load clears `reconnecting`/`loadFailed`
	// in the same tick, and `flashRecovered()` lights the green "Connection
	// restored" banner so the user gets positive confirmation.
	useEffect(() => {
		const handleOnline = () => {
			const url = currentUrlRef.current;
			const needsRecover = loadFailedRef.current || reconnectingRef.current;
			if (needsRecover && url) {
				const resumeAt = lastKnownPositionRef.current;
				console.info(
					`[useMpv] online event (loadFailed=${loadFailedRef.current} reconnecting=${reconnectingRef.current}) — auto-recovering at pos=${resumeAt.toFixed(2)}:`,
					url
				);
				load(url, resumeAt > 1.0 ? resumeAt : undefined)
					.then(() => {
						flashRecovered();
					})
					.catch((e) => {
						console.warn("[useMpv] auto-recover load failed:", e);
					});
			}
		};
		window.addEventListener("online", handleOnline);
		return () => window.removeEventListener("online", handleOnline);
	}, [load, flashRecovered]);
 
	const play = useCallback(async () => {
		console.log("[useMpv] play called");
		try {
			await mpvPlay();
			setState((s) => ({ ...s, isPlaying: true, isPaused: false }));
		} catch (e) {
			console.error("[useMpv] mpvPlay failed:", e);
		}
	}, []);
 
	const pause = useCallback(async () => {
		console.log("[useMpv] pause called");
		try {
			await mpvPause();
			setState((s) => ({ ...s, isPaused: true }));
		} catch (e) {
			console.error("[useMpv] mpvPause failed:", e);
		}
	}, []);
 
	const stop = useCallback(async () => {
		console.log("[useMpv] stop called");
		try {
			await mpvStop();
			setState(DEFAULT_STATE);
		} catch (e) {
			console.error("[useMpv] mpvStop failed:", e);
		}
	}, []);
 
	const seek = useCallback(async (position: number) => {
		console.log("[useMpv] seek position=", position);
		try {
			await mpvSeek(position);
			setState((s) => ({ ...s, position }));
		} catch (e) {
			console.error("[useMpv] mpvSeek failed:", e);
		}
	}, []);
 
	const setVolume = useCallback(async (volume: number) => {
		console.log("[useMpv] setVolume volume=", volume);
		try {
			await mpvSetVolume(volume);
			setState((s) => ({ ...s, volume }));
		} catch (e) {
			console.error("[useMpv] mpvSetVolume failed:", e);
		}
	}, []);
 
	// Read-only accessor for the sticky last-known position. Callers (e.g.
	// the Retry button) should prefer this over `state.position` for resume
	// points across hard restarts — `state.position` is polled and can read 0
	// transiently if a fresh `loadfile` is in flight; `lastKnownPositionRef`
	// only ever takes ON forward progress, so it survives the retry window.
	const getLastKnownPosition = useCallback(() => lastKnownPositionRef.current, []);
 
	const refresh = useCallback(async () => {
		try {
			const s = await mpvGetState();
			console.debug("[useMpv] poll state:", JSON.stringify(s));
			setState({
				isPlaying: s.isPlaying,
				isPaused: s.isPaused,
				currentUrl: s.currentUrl,
				volume: s.volume,
				position: s.position,
				duration: s.duration,
			});
		} catch (e) {
			console.warn("[useMpv] poll failed:", e);
		}
	}, []);
 
	useEffect(() => {
		console.log("[useMpv] starting poll interval");
		refresh();
		pollRef.current = setInterval(refresh, 1000);
		return () => {
			console.log("[useMpv] clearing poll interval");
			if (pollRef.current) clearInterval(pollRef.current);
		};
	}, [refresh]);
 
	return {
		state,
		error,
		fallbackActive,
		firstFrameReady,
		reconnecting,
		reconnectAttempt,
		buffering,
		loadFailed,
		recentlyRecovered,
		load,
		getLastKnownPosition,
		play,
		pause,
		stop,
		seek,
		setVolume,
		refresh,
	};
};