Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FaceControls #1461

Merged
merged 16 commits into from
Jun 5, 2023
33 changes: 16 additions & 17 deletions src/core/FaceControls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { useFrame, useThree } from '@react-three/fiber'
import { FaceLandmarkerResult } from '@mediapipe/tasks-vision'
import { easing } from 'maath'
import { suspend } from 'suspend-react'

import { useVideoTexture } from './useVideoTexture'
import { Facemesh, FacemeshApi, FacemeshProps } from './Facemesh'
Expand Down Expand Up @@ -284,7 +285,11 @@ export const FaceControls = forwardRef<FaceControlsApi, FaceControlsProps>(
const faceBlendshapes = faces?.faceBlendshapes?.[0]
return (
<FaceControlsContext.Provider value={api}>
{webcam && <Webcam ref={webcamApiRef} autostart={autostart} videoTextureSrc={webcamVideoTextureSrc} />}
{webcam && (
<Suspense fallback={null}>
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: is Suspense really required? I'm not sure

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your call whether suspense should go here or in user-land around the component.

<Webcam ref={webcamApiRef} autostart={autostart} videoTextureSrc={webcamVideoTextureSrc} />
</Suspense>
)}

<Facemesh
ref={facemeshApiRef}
Expand Down Expand Up @@ -324,30 +329,24 @@ type WebcamProps = {
}

const Webcam = forwardRef<WebcamApi, WebcamProps>(({ videoTextureSrc, autostart = true }, fref) => {
const [stream, setStream] = useState<MediaStream>()

const videoTextureApiRef = useRef<VideoTextureApi>(null)

const faceControls = useFaceControls()
useEffect(() => {
let strm: MediaStream

if (!videoTextureSrc) {
navigator.mediaDevices
.getUserMedia({
const stream: MediaStream | null = suspend(async () => {
return !videoTextureSrc
? await navigator.mediaDevices.getUserMedia({
audio: false,
video: { facingMode: 'user' },
})
.then((s) => {
strm = s
faceControls.dispatchEvent({ type: 'stream', stream: strm })
setStream(strm)
})
.catch(console.error)
}
: Promise.resolve(null)
}, [])

useEffect(() => {
faceControls.dispatchEvent({ type: 'stream', stream })

return () => strm?.getTracks().forEach((track) => track.stop())
}, [faceControls, videoTextureSrc])
return () => stream?.getTracks().forEach((track) => track.stop())
}, [stream, faceControls])

// ref-api
const api = useMemo<WebcamApi>(
Expand Down