Spaces:
Running
Running
Download src/hooks/useCamera.ts from evalstate/mcp-webcam: direct link, hf CLI and curl.
- Browser
- Download file 8.21 kB
-
https://huggingface.co/spaces/evalstate/mcp-webcam/resolve/main/src/hooks/useCamera.ts
- Command line
-
hf download hf://spaces/evalstate/mcp-webcam/src/hooks/useCamera.ts
-
curl -L -o useCamera.ts https://huggingface.co/spaces/evalstate/mcp-webcam/resolve/main/src/hooks/useCamera.ts
8.21 kB
| import { useCallback, useEffect, useRef, useState } from 'react'; | |
| export interface CameraDevice { | |
| deviceId: string; | |
| label: string; | |
| } | |
| export interface CapturedFrame { | |
| dataUrl: string; | |
| width: number; | |
| height: number; | |
| frozen: boolean; | |
| } | |
| export type CameraStatus = 'initializing' | 'ready' | 'denied' | 'not-found' | 'error'; | |
| const MAX_CAPTURE_DIM = 1280; | |
| const JPEG_QUALITY = 0.85; | |
| const DEVICE_STORAGE_KEY = 'mcp-webcam-device-id'; | |
| const MIRROR_STORAGE_KEY = 'mcp-webcam-mirror'; | |
| function hasMediaDevices(): boolean { | |
| return typeof navigator !== 'undefined' && Boolean(navigator.mediaDevices?.getUserMedia); | |
| } | |
| export function useCamera() { | |
| const videoRef = useRef<HTMLVideoElement | null>(null); | |
| const streamRef = useRef<MediaStream | null>(null); | |
| const [devices, setDevices] = useState<CameraDevice[]>([]); | |
| const [deviceId, setDeviceIdState] = useState<string>(() => { | |
| if (typeof window === 'undefined') return ''; | |
| try { | |
| return window.localStorage.getItem(DEVICE_STORAGE_KEY) ?? ''; | |
| } catch { | |
| return ''; | |
| } | |
| }); | |
| const [activeDeviceLabel, setActiveDeviceLabel] = useState<string>(''); | |
| const [status, setStatus] = useState<CameraStatus>(() => | |
| hasMediaDevices() ? 'initializing' : 'error', | |
| ); | |
| const [errorMessage, setErrorMessage] = useState<string | null>(() => | |
| hasMediaDevices() | |
| ? null | |
| : 'Camera API (navigator.mediaDevices.getUserMedia) is unavailable in this browser context.', | |
| ); | |
| const [dimensions, setDimensions] = useState<{ width: number; height: number } | null>(null); | |
| const [mirrored, setMirrored] = useState<boolean>(() => { | |
| if (typeof window === 'undefined') return false; | |
| try { | |
| return window.localStorage.getItem(MIRROR_STORAGE_KEY) === '1'; | |
| } catch { | |
| return false; | |
| } | |
| }); | |
| const [frozenFrame, setFrozenFrame] = useState<CapturedFrame | null>(null); | |
| const [retryNonce, setRetryNonce] = useState(0); | |
| const stopStream = useCallback(() => { | |
| if (streamRef.current) { | |
| streamRef.current.getTracks().forEach((t) => t.stop()); | |
| streamRef.current = null; | |
| } | |
| if (videoRef.current) { | |
| videoRef.current.srcObject = null; | |
| } | |
| }, []); | |
| const refreshDevices = useCallback(async () => { | |
| if (!navigator.mediaDevices?.enumerateDevices) return; | |
| try { | |
| const list = await navigator.mediaDevices.enumerateDevices(); | |
| const cams = list | |
| .filter((d) => d.kind === 'videoinput') | |
| .map((d, idx) => ({ | |
| deviceId: d.deviceId, | |
| label: d.label || `Camera ${idx + 1}`, | |
| })); | |
| setDevices(cams); | |
| } catch { | |
| // ignore enumeration errors | |
| } | |
| }, []); | |
| useEffect(() => { | |
| if (!hasMediaDevices()) return; | |
| let cancelled = false; | |
| const start = async () => { | |
| stopStream(); | |
| try { | |
| const videoConstraints: MediaTrackConstraints = deviceId | |
| ? { deviceId: { exact: deviceId }, width: { ideal: 1280 }, height: { ideal: 720 } } | |
| : { width: { ideal: 1280 }, height: { ideal: 720 } }; | |
| let stream: MediaStream; | |
| try { | |
| stream = await navigator.mediaDevices.getUserMedia({ video: videoConstraints, audio: false }); | |
| } catch (err) { | |
| if ( | |
| deviceId && | |
| err instanceof DOMException && | |
| (err.name === 'OverconstrainedError' || err.name === 'NotFoundError') | |
| ) { | |
| setDeviceIdState(''); | |
| stream = await navigator.mediaDevices.getUserMedia({ | |
| video: { width: { ideal: 1280 }, height: { ideal: 720 } }, | |
| audio: false, | |
| }); | |
| } else { | |
| throw err; | |
| } | |
| } | |
| if (cancelled) { | |
| stream.getTracks().forEach((t) => t.stop()); | |
| return; | |
| } | |
| streamRef.current = stream; | |
| const track = stream.getVideoTracks()[0]; | |
| const settings = track?.getSettings(); | |
| setActiveDeviceLabel(track?.label || 'Camera'); | |
| if (settings?.deviceId) { | |
| setDeviceIdState(settings.deviceId); | |
| } | |
| if (settings?.width && settings?.height) { | |
| setDimensions({ width: settings.width, height: settings.height }); | |
| } | |
| const video = videoRef.current; | |
| if (video) { | |
| video.srcObject = stream; | |
| video.onloadedmetadata = () => { | |
| if (video.videoWidth && video.videoHeight) { | |
| setDimensions({ width: video.videoWidth, height: video.videoHeight }); | |
| } | |
| }; | |
| await video.play().catch(() => {}); | |
| } | |
| setErrorMessage(null); | |
| setStatus('ready'); | |
| await refreshDevices(); | |
| } catch (err) { | |
| if (cancelled) return; | |
| const domErr = err as DOMException | Error; | |
| const name = domErr?.name ?? ''; | |
| if (name === 'NotAllowedError' || name === 'PermissionDeniedError') { | |
| setStatus('denied'); | |
| setErrorMessage( | |
| 'Camera permission was denied. Allow camera access in your browser settings and click Retry.', | |
| ); | |
| } else if (name === 'NotFoundError' || name === 'DevicesNotFoundError') { | |
| setStatus('not-found'); | |
| setErrorMessage('No camera device was detected on this machine.'); | |
| } else { | |
| setStatus('error'); | |
| setErrorMessage(domErr?.message || 'Unable to start camera stream.'); | |
| } | |
| } | |
| }; | |
| void start(); | |
| const handleDeviceChange = () => { | |
| void refreshDevices(); | |
| }; | |
| navigator.mediaDevices.addEventListener?.('devicechange', handleDeviceChange); | |
| return () => { | |
| cancelled = true; | |
| navigator.mediaDevices.removeEventListener?.('devicechange', handleDeviceChange); | |
| stopStream(); | |
| }; | |
| }, [deviceId, retryNonce, stopStream, refreshDevices]); | |
| const setDeviceId = useCallback((nextId: string) => { | |
| setFrozenFrame(null); | |
| setStatus('initializing'); | |
| setErrorMessage(null); | |
| setDeviceIdState(nextId); | |
| try { | |
| window.localStorage.setItem(DEVICE_STORAGE_KEY, nextId); | |
| } catch { | |
| // ignore | |
| } | |
| }, []); | |
| const toggleMirror = useCallback(() => { | |
| setMirrored((m) => { | |
| const next = !m; | |
| try { | |
| window.localStorage.setItem(MIRROR_STORAGE_KEY, next ? '1' : '0'); | |
| } catch { | |
| // ignore | |
| } | |
| return next; | |
| }); | |
| }, []); | |
| const grabLiveFrame = useCallback((): CapturedFrame | null => { | |
| const video = videoRef.current; | |
| if (!video || video.readyState < 2 || !video.videoWidth || !video.videoHeight) { | |
| return null; | |
| } | |
| let width = video.videoWidth; | |
| let height = video.videoHeight; | |
| if (width > MAX_CAPTURE_DIM || height > MAX_CAPTURE_DIM) { | |
| const scale = MAX_CAPTURE_DIM / Math.max(width, height); | |
| width = Math.round(width * scale); | |
| height = Math.round(height * scale); | |
| } | |
| const canvas = document.createElement('canvas'); | |
| canvas.width = width; | |
| canvas.height = height; | |
| const ctx = canvas.getContext('2d'); | |
| if (!ctx) return null; | |
| // Always capture the unmirrored video frame so text/details remain legible to agents. | |
| ctx.drawImage(video, 0, 0, width, height); | |
| const dataUrl = canvas.toDataURL('image/jpeg', JPEG_QUALITY); | |
| return { dataUrl, width, height, frozen: false }; | |
| }, []); | |
| const grabFrame = useCallback((): CapturedFrame | null => { | |
| if (frozenFrame) { | |
| return { ...frozenFrame, frozen: true }; | |
| } | |
| return grabLiveFrame(); | |
| }, [frozenFrame, grabLiveFrame]); | |
| const toggleFreeze = useCallback(() => { | |
| if (frozenFrame) { | |
| setFrozenFrame(null); | |
| return; | |
| } | |
| const frame = grabLiveFrame(); | |
| if (frame) { | |
| setFrozenFrame({ ...frame, frozen: true }); | |
| } | |
| }, [frozenFrame, grabLiveFrame]); | |
| const retry = useCallback(() => { | |
| setFrozenFrame(null); | |
| setStatus('initializing'); | |
| setErrorMessage(null); | |
| setRetryNonce((n) => n + 1); | |
| }, []); | |
| return { | |
| videoRef, | |
| devices, | |
| deviceId, | |
| setDeviceId, | |
| activeDeviceLabel, | |
| status, | |
| errorMessage, | |
| dimensions, | |
| mirrored, | |
| toggleMirror, | |
| frozen: Boolean(frozenFrame), | |
| frozenFrame, | |
| toggleFreeze, | |
| grabFrame, | |
| grabLiveFrame, | |
| retry, | |
| }; | |
| } | |