-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebRtcVideo.tsx
249 lines (211 loc) · 7.07 KB
/
WebRtcVideo.tsx
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
'use client'
import { useEffect, useState, useRef, type Dispatch, type SetStateAction } from 'react'
import { WebRTCPlayer } from '@eyevinn/webrtc-player'
import { toast } from 'sonner'
import { Progress, type ProgressState } from '@/components/ui/progress'
import { ToastIds, DISMISS_BUTTON } from '@/components/ui/sonner'
import { cn } from '@/lib/utils'
import { Size } from '@/app/place/PlaceInterface'
const PROGRESS_BAR = {
INITIAL: 0,
FINAL: 100,
// Fixed progresses
PLAYER_CONSTRUCTED: 2,
PLAYER_LOADED: 15,
VIDEO_LOAD_START: 30,
VIDEO_LOADED_METADATA: 85,
VIDEO_LOADED_DATA: 99.99,
// Interval increments
// ? https://www.desmos.com/calculator/4pelacztnu
getIncrement: (incrementCount: number) => (50 / (incrementCount + 100)),
INCREMENT_INTERVAL_MS: 25,
// Delay before hiding
LOADED_DELAY_MS: 325,
} as const
type WebRtcVideoProps = {
url: string;
setVideoSize?: Dispatch<SetStateAction<Size | null>>;
setIsVideoStreaming?: Dispatch<SetStateAction<boolean>>;
setHasVideoErrored?: Dispatch<SetStateAction<boolean>>;
};
export function WebRtcVideo({ url, setVideoSize, setIsVideoStreaming, setHasVideoErrored }: WebRtcVideoProps) {
const videoRef = useRef<HTMLVideoElement>(null)
const errorRef = useRef(false)
const [loadProgress, setLoadProgress] = useState<ProgressState<true>>({
current: PROGRESS_BAR.INITIAL,
growthStop: PROGRESS_BAR.INITIAL,
})
// WebRTCPlayer
useEffect(() => {
if (!videoRef?.current) return
const player = new WebRTCPlayer({
video: videoRef.current,
type: 'whep',
statsTypeFilter: '^inbound-rtp',
timeoutThreshold: 5000,
detectTimeout: true,
mediaConstraints: {
videoOnly: true,
},
})
setLoadProgress({
current: PROGRESS_BAR.PLAYER_CONSTRUCTED,
growthStop: PROGRESS_BAR.PLAYER_LOADED,
})
player.load(new URL(url))
.then(() => setLoadProgress({
current: PROGRESS_BAR.PLAYER_LOADED,
growthStop: PROGRESS_BAR.VIDEO_LOAD_START,
}))
function handleConnectError(error?: unknown) {
console.error('Connect error: ', error)
setLoadProgress({
current: PROGRESS_BAR.PLAYER_LOADED,
growthStop: PROGRESS_BAR.PLAYER_LOADED,
})
setIsVideoStreaming?.(false)
setHasVideoErrored?.(true)
if (errorRef.current) return
toast.error('Video stream error!', {
id: ToastIds.VIDEO_ERROR,
cancel: DISMISS_BUTTON,
duration: 6000,
})
errorRef.current = true
}
// Notify error if host is unreachable
fetch(url.replace('/whep', ''), {
method: 'GET',
priority: 'low',
})
.then(response => {
if (response.ok) {
console.log('Host is reachable', response)
}
else {
console.log('Host is not reachable', response)
}
})
.catch(handleConnectError)
player.on('peer-connection-failed', handleConnectError)
player.on('initial-connection-failed', handleConnectError)
player.on('connect-error', handleConnectError)
player.on('no-media', () => {
console.log('Media timeout occurred')
setIsVideoStreaming?.(false)
toast.warning('Stream timed out!', {
id: ToastIds.VIDEO_STATUS,
cancel: DISMISS_BUTTON,
})
})
player.on('media-recovered', () => {
console.log('Media recovered')
setIsVideoStreaming?.(true)
toast.success('Stream recovered!', {
id: ToastIds.VIDEO_STATUS,
cancel: DISMISS_BUTTON,
})
})
player.on('stats:inbound-rtp', console.log)
return () => {
player.unload()
player.destroy()
}
}, [videoRef, setIsVideoStreaming, setHasVideoErrored, url])
// Video size
useEffect(() => {
if (!videoRef?.current) return
if (!setVideoSize) return
const videoElement = videoRef.current
function updateVideoBounds() {
if (videoElement.videoWidth === 0 || videoElement.videoHeight === 0) {
setVideoSize?.(null)
return
}
const scalingFactors = {
width: videoElement.clientWidth / videoElement.videoWidth,
height: videoElement.clientHeight / videoElement.videoHeight,
}
const limitingScalarFactor = (scalingFactors.width >= scalingFactors.height)
// Black bars on the sides
? scalingFactors.height
// Black bars on the top/bottom
: scalingFactors.width
setVideoSize?.({
width: limitingScalarFactor * videoElement.videoWidth,
height: limitingScalarFactor * videoElement.videoHeight,
})
console.log(`Updated video size to ${limitingScalarFactor * videoElement.videoWidth}x${limitingScalarFactor * videoElement.videoHeight}`)
}
window.addEventListener('resize', updateVideoBounds)
videoElement.addEventListener('loadedmetadata', updateVideoBounds)
return () => {
setVideoSize?.(null)
window.removeEventListener('resize', updateVideoBounds)
videoElement.removeEventListener('loadedmetadata', updateVideoBounds)
}
}, [videoRef, setVideoSize])
// Progress bar
useEffect(() => {
if (!videoRef?.current) return
const videoElement = videoRef.current
const handleStart = () => {
setLoadProgress({
current: PROGRESS_BAR.VIDEO_LOAD_START,
growthStop: PROGRESS_BAR.VIDEO_LOADED_METADATA,
})
}
const handleMetadata = () => {
setLoadProgress({
current: PROGRESS_BAR.VIDEO_LOADED_METADATA,
growthStop: PROGRESS_BAR.VIDEO_LOADED_DATA,
})
}
const handleData = async () => {
setLoadProgress({
current: PROGRESS_BAR.VIDEO_LOADED_DATA,
growthStop: PROGRESS_BAR.VIDEO_LOADED_DATA,
})
await new Promise((resolve) => setTimeout(resolve, PROGRESS_BAR.LOADED_DELAY_MS))
setLoadProgress({
current: PROGRESS_BAR.FINAL,
growthStop: PROGRESS_BAR.FINAL,
})
setIsVideoStreaming?.(true)
}
videoElement.addEventListener('loadstart', handleStart)
videoElement.addEventListener('loadedmetadata', handleMetadata)
videoElement.addEventListener('loadeddata', handleData)
return () => {
setIsVideoStreaming?.(false)
videoElement.removeEventListener('loadstart', handleStart)
videoElement.removeEventListener('loadedmetadata', handleMetadata)
videoElement.removeEventListener('loadeddata', handleData)
}
}, [videoRef, setIsVideoStreaming])
return (
<>
{(loadProgress.current !== PROGRESS_BAR.FINAL) && (
<Progress
value={loadProgress.current}
className='absolute max-w-[50%]'
grow={true}
growthStop={loadProgress.growthStop}
setProgress={setLoadProgress}
getIncrement={PROGRESS_BAR.getIncrement}
growthIntervalMs={(errorRef.current) ? 0 : PROGRESS_BAR.INCREMENT_INTERVAL_MS}
/>
)}
<video
ref={videoRef}
autoPlay
muted
playsInline
className={cn(
'object-contain object-center h-full w-full pointer-events-none',
(loadProgress.current !== PROGRESS_BAR.FINAL) && 'invisible'
)}
/>
</>
)
}