useOverlayCameraRecovery.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { useCallback, useEffect, useRef, useState, type SyntheticEvent } from 'react';
  2. // MJPEG <img> connections can stop delivering frames without firing onError.
  3. // Renew only the camera connection, keeping the overlay and its credentials.
  4. // This also renews healthy connections; it does not measure frame freshness.
  5. const STREAM_RENEWAL_MS = 60_000;
  6. const ERROR_RETRY_MS = 3_000;
  7. // The old stream is closed this long before the new one opens: a detached img
  8. // keeps its connection open (measured in Chromium, which OBS browser sources
  9. // run on), and a USB camera serves one reader.
  10. const RENEWAL_GAP_MS = 200;
  11. export function useOverlayCameraRecovery(enabled: boolean) {
  12. const [imageKey, setImageKey] = useState(Date.now);
  13. // While true the img renders with no src, so no re-render reopens it early.
  14. const [closing, setClosing] = useState(false);
  15. const imgRef = useRef<HTMLImageElement | null>(null);
  16. const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  17. const close = useCallback(() => {
  18. // Closed now, not at the next render, which may already be the reopen.
  19. imgRef.current?.removeAttribute('src');
  20. setClosing(true);
  21. }, []);
  22. const renew = useCallback(() => {
  23. if (retryTimer.current !== null) {
  24. clearTimeout(retryTimer.current);
  25. retryTimer.current = null;
  26. }
  27. setClosing(false);
  28. setImageKey((key) => key + 1);
  29. }, []);
  30. useEffect(() => {
  31. if (!enabled) return;
  32. // Start a fresh deadline after each retry so a newly opened connection
  33. // isn't immediately replaced by the previous connection's renewal timer.
  34. const closeTimer = setTimeout(close, STREAM_RENEWAL_MS - RENEWAL_GAP_MS);
  35. const renewalTimer = setTimeout(renew, STREAM_RENEWAL_MS);
  36. return () => {
  37. clearTimeout(closeTimer);
  38. clearTimeout(renewalTimer);
  39. if (retryTimer.current !== null) {
  40. clearTimeout(retryTimer.current);
  41. retryTimer.current = null;
  42. }
  43. setClosing(false);
  44. };
  45. }, [enabled, imageKey, renew, close]);
  46. const handleStreamError = useCallback(
  47. (event?: SyntheticEvent<HTMLImageElement>) => {
  48. if (!enabled || retryTimer.current !== null) return;
  49. // Closing the stream (src removed) fires error too.
  50. if (event && !event.currentTarget.getAttribute('src')) return;
  51. close();
  52. retryTimer.current = setTimeout(renew, ERROR_RETRY_MS);
  53. },
  54. [enabled, renew, close],
  55. );
  56. return { imageKey, closing, imgRef, handleStreamError };
  57. }