|
| 1 | +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; |
| 2 | + |
| 3 | +export type ConnectionState = 'idle' | 'connecting' | 'connected' | 'error'; |
| 4 | + |
| 5 | +function normalizeOfferUrl(raw?: string): string { |
| 6 | + const fallback = 'http://localhost:8001/offer'; |
| 7 | + if (!raw) return fallback; |
| 8 | + try { |
| 9 | + const url = new URL(raw); |
| 10 | + const path = url.pathname.replace(/\/+$/, ''); |
| 11 | + url.pathname = path.endsWith('/offer') ? path : `${path}/offer`; |
| 12 | + return url.toString(); |
| 13 | + } catch { |
| 14 | + try { |
| 15 | + const withScheme = /^https?:\/\//.test(raw) ? raw : `http://${raw}`; |
| 16 | + const url = new URL(withScheme); |
| 17 | + const path = url.pathname.replace(/\/+$/, ''); |
| 18 | + url.pathname = path.endsWith('/offer') ? path : `${path}/offer`; |
| 19 | + return url.toString(); |
| 20 | + } catch { |
| 21 | + return fallback; |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +export interface UseWebRTCPlayerOptions { |
| 27 | + signalingEndpoint?: string; |
| 28 | + autoPlay?: boolean; |
| 29 | +} |
| 30 | + |
| 31 | +export interface UseWebRTCPlayerResult { |
| 32 | + videoRef: React.RefObject<HTMLVideoElement>; |
| 33 | + connectionState: ConnectionState; |
| 34 | + errorReason: string; |
| 35 | + isPaused: boolean; |
| 36 | + connect: () => Promise<void>; |
| 37 | + disconnect: () => void; |
| 38 | + togglePlayPause: () => Promise<void>; |
| 39 | + enterFullscreen: () => void; |
| 40 | +} |
| 41 | + |
| 42 | +export function useWebRTCPlayer({ signalingEndpoint, autoPlay = false }: UseWebRTCPlayerOptions): UseWebRTCPlayerResult { |
| 43 | + const offerUrl = useMemo(() => { |
| 44 | + const envUrl = (import.meta as any)?.env?.VITE_BACKEND_URL as string | undefined; |
| 45 | + const base = signalingEndpoint ?? envUrl ?? 'http://localhost:8001'; |
| 46 | + return normalizeOfferUrl(base); |
| 47 | + }, [signalingEndpoint]); |
| 48 | + |
| 49 | + const videoRef = useRef<HTMLVideoElement | null>(null); |
| 50 | + const pcRef = useRef<RTCPeerConnection | null>(null); |
| 51 | + |
| 52 | + const [connectionState, setConnectionState] = useState<ConnectionState>('idle'); |
| 53 | + const [errorReason, setErrorReason] = useState(''); |
| 54 | + const [isPaused, setIsPaused] = useState(false); |
| 55 | + |
| 56 | + const connect = useCallback(async () => { |
| 57 | + if (pcRef.current) return; |
| 58 | + setErrorReason(''); |
| 59 | + setConnectionState('connecting'); |
| 60 | + |
| 61 | + const pc = new RTCPeerConnection({ iceServers: [{ urls: ['stun:stun.l.google.com:19302'] }] }); |
| 62 | + pcRef.current = pc; |
| 63 | + |
| 64 | + pc.addTransceiver('video', { direction: 'recvonly' }); |
| 65 | + |
| 66 | + pc.ontrack = (e) => { |
| 67 | + const [stream] = e.streams; |
| 68 | + if (!videoRef.current) return; |
| 69 | + videoRef.current.srcObject = stream; |
| 70 | + videoRef.current.onloadedmetadata = () => { |
| 71 | + if (autoPlay) { |
| 72 | + videoRef.current?.play().catch(() => {}); |
| 73 | + } |
| 74 | + }; |
| 75 | + }; |
| 76 | + |
| 77 | + try { |
| 78 | + const offer = await pc.createOffer(); |
| 79 | + await pc.setLocalDescription(offer); |
| 80 | + |
| 81 | + await new Promise<void>((resolve) => { |
| 82 | + if (pc.iceGatheringState === 'complete') return resolve(); |
| 83 | + const handler = () => { |
| 84 | + if (pc.iceGatheringState === 'complete') { |
| 85 | + pc.removeEventListener('icegatheringstatechange', handler); |
| 86 | + resolve(); |
| 87 | + } |
| 88 | + }; |
| 89 | + pc.addEventListener('icegatheringstatechange', handler); |
| 90 | + }); |
| 91 | + |
| 92 | + const res = await fetch(offerUrl, { |
| 93 | + method: 'POST', |
| 94 | + headers: { 'Content-Type': 'application/json' }, |
| 95 | + body: JSON.stringify({ sdp: pc.localDescription?.sdp ?? '', type: 'offer' }), |
| 96 | + }); |
| 97 | + if (!res.ok) throw new Error(`HTTP ${res.status}`); |
| 98 | + const answer = await res.json(); |
| 99 | + await pc.setRemoteDescription(new RTCSessionDescription(answer)); |
| 100 | + setConnectionState('connected'); |
| 101 | + setIsPaused(false); |
| 102 | + } catch (err) { |
| 103 | + setConnectionState('error'); |
| 104 | + setErrorReason(String(err)); |
| 105 | + try { |
| 106 | + pc.close(); |
| 107 | + } catch {} |
| 108 | + pcRef.current = null; |
| 109 | + } |
| 110 | + }, [offerUrl, autoPlay]); |
| 111 | + |
| 112 | + const disconnect = useCallback(() => { |
| 113 | + const pc = pcRef.current; |
| 114 | + if (pc) { |
| 115 | + try { |
| 116 | + pc.getReceivers().forEach((r) => r.track && (r.track.enabled = false)); |
| 117 | + pc.close(); |
| 118 | + } catch {} |
| 119 | + } |
| 120 | + pcRef.current = null; |
| 121 | + if (videoRef.current) { |
| 122 | + try { |
| 123 | + videoRef.current.pause(); |
| 124 | + (videoRef.current as any).srcObject = null; |
| 125 | + } catch {} |
| 126 | + } |
| 127 | + setIsPaused(false); |
| 128 | + setConnectionState('idle'); |
| 129 | + }, []); |
| 130 | + |
| 131 | + const togglePlayPause = useCallback(async () => { |
| 132 | + if (connectionState !== 'connected') { |
| 133 | + await connect(); |
| 134 | + return; |
| 135 | + } |
| 136 | + if (!videoRef.current) return; |
| 137 | + if (isPaused) { |
| 138 | + try { |
| 139 | + pcRef.current?.getReceivers().forEach((r) => r.track && (r.track.enabled = true)); |
| 140 | + } catch {} |
| 141 | + await videoRef.current.play().catch(() => {}); |
| 142 | + setIsPaused(false); |
| 143 | + } else { |
| 144 | + try { |
| 145 | + pcRef.current?.getReceivers().forEach((r) => r.track && (r.track.enabled = false)); |
| 146 | + } catch {} |
| 147 | + videoRef.current.pause(); |
| 148 | + setIsPaused(true); |
| 149 | + } |
| 150 | + }, [connectionState, isPaused, connect]); |
| 151 | + |
| 152 | + const enterFullscreen = useCallback(() => { |
| 153 | + const el = videoRef.current?.parentElement ?? videoRef.current; |
| 154 | + if (!el) return; |
| 155 | + const anyEl = el as any; |
| 156 | + const req = anyEl.requestFullscreen || anyEl.webkitRequestFullscreen || anyEl.msRequestFullscreen; |
| 157 | + if (req) req.call(anyEl); |
| 158 | + }, []); |
| 159 | + |
| 160 | + useEffect(() => { |
| 161 | + return () => disconnect(); |
| 162 | + }, [disconnect]); |
| 163 | + |
| 164 | + return { |
| 165 | + videoRef, |
| 166 | + connectionState, |
| 167 | + errorReason, |
| 168 | + isPaused, |
| 169 | + connect, |
| 170 | + disconnect, |
| 171 | + togglePlayPause, |
| 172 | + enterFullscreen, |
| 173 | + }; |
| 174 | +} |
0 commit comments