Open History to see the last commit
1/**
2 * Attach a WebRTC stream the way ReactorView does: mute for autoplay, then
3 * re-attach when a track unmutes. Remote tracks often arrive muted; Chrome
4 * keeps the <video> black until srcObject is set again after unmute.
5 */
6export function attachStream(
7 video: HTMLVideoElement,
8 stream: MediaStream,
9 onError?: (error: unknown) => void,
10): () => void {
11 const attach = (reset: boolean) => {
12 if (reset) {
13 video.srcObject = null
14 }
15 video.srcObject = stream
16 void video.play().catch((error: unknown) => {
17 if (error instanceof DOMException && error.name === 'AbortError') return
18 onError?.(error)
19 })
20 }
21 attach(false)
22 const onUnmute = () => attach(true)
23 const tracks = stream.getTracks()
24 for (const track of tracks) {
25 track.addEventListener('unmute', onUnmute)
26 }
27 return () => {
28 for (const track of tracks) {
29 track.removeEventListener('unmute', onUnmute)
30 }
31 }
32}