-
Notifications
You must be signed in to change notification settings - Fork 718
/
FaceControls.tsx
416 lines (362 loc) · 12.6 KB
/
FaceControls.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/* eslint react-hooks/exhaustive-deps: 1 */
import * as THREE from 'three'
import * as React from 'react'
import {
useState,
Suspense,
useEffect,
useRef,
useCallback,
forwardRef,
useMemo,
useImperativeHandle,
RefObject,
createContext,
useContext,
} from 'react'
import { useFrame, useThree } from '@react-three/fiber'
import type { FaceLandmarkerResult } from '@mediapipe/tasks-vision'
import { easing } from 'maath'
import { suspend, clear } from 'suspend-react'
import { useVideoTexture } from './useVideoTexture'
import { Facemesh, FacemeshApi, FacemeshProps } from './Facemesh'
import { useFaceLandmarker } from './FaceLandmarker'
type VideoTextureSrc = Parameters<typeof useVideoTexture>[0] // useVideoTexture 1st arg `src` type
function mean(v1: THREE.Vector3, v2: THREE.Vector3) {
return v1.clone().add(v2).multiplyScalar(0.5)
}
function localToLocal(objSrc: THREE.Object3D, v: THREE.Vector3, objDst: THREE.Object3D) {
// see: https://discourse.threejs.org/t/object3d-localtolocal/51564
const v_world = objSrc.localToWorld(v)
return objDst.worldToLocal(v_world)
}
//
//
//
export type FaceControlsProps = {
/** The camera to be controlled, default: global state camera */
camera?: THREE.Camera
/** Whether to autostart the webcam, default: true */
autostart?: boolean
/** Enable/disable the webcam, default: true */
webcam?: boolean
/** A custom video URL or mediaStream, default: undefined */
webcamVideoTextureSrc?: VideoTextureSrc
/** Disable the rAF camera position/rotation update, default: false */
manualUpdate?: boolean
/** Disable the rVFC face-detection, default: false */
manualDetect?: boolean
/** Callback function to call on "videoFrame" event, default: undefined */
onVideoFrame?: (e: THREE.Event) => void
/** Reference this FaceControls instance as state's `controls` */
makeDefault?: boolean
/** Approximate time to reach the target. A smaller value will reach the target faster. */
smoothTime?: number
/** Apply position offset extracted from `facialTransformationMatrix` */
offset?: boolean
/** Offset sensitivity factor, less is more sensible, default: 80 */
offsetScalar?: number
/** Enable eye-tracking */
eyes?: boolean
/** Force Facemesh's `origin` to be the middle of the 2 eyes, default: true */
eyesAsOrigin?: boolean
/** Constant depth of the Facemesh, default: .15 */
depth?: number
/** Enable debug mode, default: false */
debug?: boolean
/** Facemesh options, default: undefined */
facemesh?: FacemeshProps
}
export type FaceControlsApi = THREE.EventDispatcher & {
/** Detect faces from the video */
detect: (video: HTMLVideoElement, time: number) => void
/** Compute the target for the camera */
computeTarget: () => THREE.Object3D
/** Update camera's position/rotation to the `target` */
update: (delta: number, target?: THREE.Object3D) => void
/** <Facemesh> ref api */
facemeshApiRef: RefObject<FacemeshApi>
/** <Webcam> ref api */
webcamApiRef: RefObject<WebcamApi>
/** Play the video */
play: () => void
/** Pause the video */
pause: () => void
}
const FaceControlsContext = /* @__PURE__ */ createContext({} as FaceControlsApi)
export const FaceControls = /* @__PURE__ */ forwardRef<FaceControlsApi, FaceControlsProps>(
(
{
camera,
autostart = true,
webcam = true,
webcamVideoTextureSrc,
manualUpdate = false,
manualDetect = false,
onVideoFrame,
smoothTime = 0.25,
offset = true,
offsetScalar = 80,
eyes = false,
eyesAsOrigin = true,
depth = 0.15,
debug = false,
facemesh,
makeDefault,
},
fref
) => {
const scene = useThree((state) => state.scene)
const defaultCamera = useThree((state) => state.camera)
const set = useThree((state) => state.set)
const get = useThree((state) => state.get)
const explCamera = camera || defaultCamera
const webcamApiRef = useRef<WebcamApi>(null)
const facemeshApiRef = useRef<FacemeshApi>(null)
//
// computeTarget()
//
// Compute `target` position and rotation for the camera (according to <Facemesh>)
//
// 1. 👀 either following the 2 eyes
// 2. 👤 or just the head mesh
//
const [target] = useState(() => new THREE.Object3D())
const [irisRightDirPos] = useState(() => new THREE.Vector3())
const [irisLeftDirPos] = useState(() => new THREE.Vector3())
const [irisRightLookAt] = useState(() => new THREE.Vector3())
const [irisLeftLookAt] = useState(() => new THREE.Vector3())
const computeTarget = useCallback<FaceControlsApi['computeTarget']>(() => {
// same parent as the camera
target.parent = explCamera.parent
const facemeshApi = facemeshApiRef.current
if (facemeshApi) {
const { outerRef, eyeRightRef, eyeLeftRef } = facemeshApi
if (eyeRightRef.current && eyeLeftRef.current) {
// 1. 👀
const { irisDirRef: irisRightDirRef } = eyeRightRef.current
const { irisDirRef: irisLeftDirRef } = eyeLeftRef.current
if (irisRightDirRef.current && irisLeftDirRef.current && outerRef.current) {
//
// position: mean of irisRightDirPos,irisLeftDirPos
//
irisRightDirPos.copy(localToLocal(irisRightDirRef.current, new THREE.Vector3(0, 0, 0), outerRef.current))
irisLeftDirPos.copy(localToLocal(irisLeftDirRef.current, new THREE.Vector3(0, 0, 0), outerRef.current))
target.position.copy(
localToLocal(outerRef.current, mean(irisRightDirPos, irisLeftDirPos), explCamera.parent || scene)
)
//
// lookAt: mean of irisRightLookAt,irisLeftLookAt
//
irisRightLookAt.copy(localToLocal(irisRightDirRef.current, new THREE.Vector3(0, 0, 1), outerRef.current))
irisLeftLookAt.copy(localToLocal(irisLeftDirRef.current, new THREE.Vector3(0, 0, 1), outerRef.current))
target.lookAt(outerRef.current.localToWorld(mean(irisRightLookAt, irisLeftLookAt)))
}
} else {
// 2. 👤
if (outerRef.current) {
target.position.copy(localToLocal(outerRef.current, new THREE.Vector3(0, 0, 0), explCamera.parent || scene))
target.lookAt(outerRef.current.localToWorld(new THREE.Vector3(0, 0, 1)))
}
}
}
return target
}, [explCamera, irisLeftDirPos, irisLeftLookAt, irisRightDirPos, irisRightLookAt, scene, target])
//
// update()
//
// Updating the camera `current` position and rotation, following `target`
//
const [current] = useState(() => new THREE.Object3D())
const update = useCallback<FaceControlsApi['update']>(
function (delta, target) {
if (explCamera) {
target ??= computeTarget()
if (smoothTime > 0) {
// damping current
const eps = 1e-9
easing.damp3(current.position, target.position, smoothTime, delta, undefined, undefined, eps)
easing.dampE(current.rotation, target.rotation, smoothTime, delta, undefined, undefined, eps)
} else {
// instant
current.position.copy(target.position)
current.rotation.copy(target.rotation)
}
explCamera.position.copy(current.position)
explCamera.rotation.copy(current.rotation)
}
},
[explCamera, computeTarget, smoothTime, current.position, current.rotation]
)
//
// detect()
//
const [faces, setFaces] = useState<FaceLandmarkerResult>()
const faceLandmarker = useFaceLandmarker()
const detect = useCallback<FaceControlsApi['detect']>(
(video, time) => {
const faces = faceLandmarker?.detectForVideo(video, time)
setFaces(faces)
},
[faceLandmarker]
)
useFrame((_, delta) => {
if (!manualUpdate) {
update(delta)
}
})
// Ref API
const api = useMemo<FaceControlsApi>(
() =>
Object.assign(Object.create(THREE.EventDispatcher.prototype), {
detect,
computeTarget,
update,
facemeshApiRef,
webcamApiRef,
// shorthands
play: () => {
webcamApiRef.current?.videoTextureApiRef.current?.texture.source.data.play()
},
pause: () => {
webcamApiRef.current?.videoTextureApiRef.current?.texture.source.data.pause()
},
}),
[detect, computeTarget, update]
)
useImperativeHandle(fref, () => api, [api])
//
// events callbacks
//
useEffect(() => {
const onVideoFrameCb = (e: THREE.Event) => {
if (!manualDetect) detect(e.texture.source.data, e.time)
if (onVideoFrame) onVideoFrame(e)
}
api.addEventListener('videoFrame', onVideoFrameCb)
return () => {
api.removeEventListener('videoFrame', onVideoFrameCb)
}
}, [api, detect, faceLandmarker, manualDetect, onVideoFrame])
// `controls` global state
useEffect(() => {
if (makeDefault) {
const old = get().controls
set({ controls: api })
return () => set({ controls: old })
}
}, [makeDefault, api, get, set])
const points = faces?.faceLandmarks[0]
const facialTransformationMatrix = faces?.facialTransformationMatrixes?.[0]
const faceBlendshapes = faces?.faceBlendshapes?.[0]
return (
<FaceControlsContext.Provider value={api}>
{webcam && (
<Suspense fallback={null}>
<Webcam ref={webcamApiRef} autostart={autostart} videoTextureSrc={webcamVideoTextureSrc} />
</Suspense>
)}
<Facemesh
ref={facemeshApiRef}
{...facemesh}
points={points}
depth={depth}
facialTransformationMatrix={facialTransformationMatrix}
faceBlendshapes={faceBlendshapes}
eyes={eyes}
eyesAsOrigin={eyesAsOrigin}
offset={offset}
offsetScalar={offsetScalar}
debug={debug}
rotation-z={Math.PI}
visible={debug}
>
<meshBasicMaterial side={THREE.DoubleSide} />
</Facemesh>
</FaceControlsContext.Provider>
)
}
)
export const useFaceControls = () => useContext(FaceControlsContext)
//
// Webcam
//
type WebcamApi = {
videoTextureApiRef: RefObject<VideoTextureApi>
}
type WebcamProps = {
videoTextureSrc?: VideoTextureSrc
autostart?: boolean
}
const Webcam = /* @__PURE__ */ forwardRef<WebcamApi, WebcamProps>(({ videoTextureSrc, autostart = true }, fref) => {
const videoTextureApiRef = useRef<VideoTextureApi>(null)
const faceControls = useFaceControls()
const stream: MediaStream | null = suspend(async () => {
return !videoTextureSrc
? await navigator.mediaDevices.getUserMedia({
audio: false,
video: { facingMode: 'user' },
})
: Promise.resolve(null)
}, [videoTextureSrc])
useEffect(() => {
faceControls.dispatchEvent({ type: 'stream', stream })
return () => {
stream?.getTracks().forEach((track) => track.stop())
clear([videoTextureSrc])
}
}, [stream, faceControls, videoTextureSrc])
// ref-api
const api = useMemo<WebcamApi>(
() => ({
videoTextureApiRef,
}),
[]
)
useImperativeHandle(fref, () => api, [api])
return (
<Suspense fallback={null}>
<VideoTexture ref={videoTextureApiRef} src={videoTextureSrc || stream!} start={autostart} />
</Suspense>
)
})
//
// VideoTexture
//
type VideoTextureApi = { texture: THREE.VideoTexture }
type VideoTextureProps = { src: VideoTextureSrc; start: boolean }
const VideoTexture = /* @__PURE__ */ forwardRef<VideoTextureApi, VideoTextureProps>(({ src, start }, fref) => {
const texture = useVideoTexture(src, { start })
const video = texture.source.data
const faceControls = useFaceControls()
const onVideoFrame = useCallback(
(time: number) => {
faceControls.dispatchEvent({ type: 'videoFrame', texture, time })
},
[texture, faceControls]
)
useVideoFrame(video, onVideoFrame)
// ref-api
const api = useMemo<VideoTextureApi>(
() => ({
texture,
}),
[texture]
)
useImperativeHandle(fref, () => api, [api])
return <></>
})
const useVideoFrame = (video: HTMLVideoElement, f: (...args: any) => any) => {
// https://web.dev/requestvideoframecallback-rvfc/
// https://www.remotion.dev/docs/video-manipulation
useEffect(() => {
if (!video || !video.requestVideoFrameCallback) return
let handle: number
function callback(...args: any) {
f(...args)
handle = video.requestVideoFrameCallback(callback)
}
video.requestVideoFrameCallback(callback)
return () => video.cancelVideoFrameCallback(handle)
}, [video, f])
}