forked from yondonfu/comfystream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebcam.tsx
189 lines (165 loc) · 4.83 KB
/
webcam.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
import { useCallback, useEffect, useRef, useState } from "react";
/**
* Internal component that renders and captures camera feed at exactly 512x512.
* Handles both display and stream capture in a single canvas element,
* ensuring consistent dimensions while maintaining aspect ratio.
*/
function StreamCanvas({
stream,
frameRate,
onStreamReady,
}: {
stream: MediaStream | null;
frameRate: number;
onStreamReady: (stream: MediaStream) => void;
}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const videoRef = useRef<HTMLVideoElement | null>(null);
useEffect(() => {
if (!stream) return;
const canvas = canvasRef.current!;
const videoOnlyStream = canvas.captureStream(frameRate);
const audioTracks = stream.getAudioTracks();
const combinedStream = new MediaStream([
...videoOnlyStream.getVideoTracks(),
...audioTracks,
]);
onStreamReady(combinedStream);
return () => {
combinedStream.getTracks().forEach((track) => track.stop());
};
}, [stream, frameRate, onStreamReady]);
// Set up canvas animation loop
useEffect(() => {
const canvas = canvasRef.current!;
const ctx = canvas.getContext("2d")!;
let isActive = true;
const drawFrame = () => {
if (!isActive) {
// return without scheduling another frame
return;
}
const video = videoRef.current!;
if (!video?.videoWidth) {
// video is not ready yet
requestAnimationFrame(drawFrame);
return;
}
const scale = Math.max(512 / video.videoWidth, 512 / video.videoHeight);
const scaledWidth = video.videoWidth * scale;
const scaledHeight = video.videoHeight * scale;
const offsetX = (512 - scaledWidth) / 2;
const offsetY = (512 - scaledHeight) / 2;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 512, 512);
ctx.drawImage(video, offsetX, offsetY, scaledWidth, scaledHeight);
requestAnimationFrame(drawFrame);
};
drawFrame();
return () => {
isActive = false;
};
}, []);
useEffect(() => {
if (!stream) return;
if (!videoRef.current) {
videoRef.current = document.createElement("video");
// videoRef.current.muted = true;
}
const video = videoRef.current;
video.srcObject = stream;
video.onloadedmetadata = () => {
video.play().catch((error) => {
console.log("Video play failed:", error);
});
};
return () => {
video.pause();
video.srcObject = null;
};
}, [stream]);
return (
<canvas
ref={canvasRef}
width={512}
height={512}
className="w-full h-full"
style={{
backgroundColor: "black",
}}
/>
);
}
interface WebcamProps {
onStreamReady: (stream: MediaStream) => void;
deviceId: string;
frameRate: number;
selectedAudioDeviceId: string;
}
export function Webcam({ onStreamReady, deviceId, frameRate, selectedAudioDeviceId }: WebcamProps) {
const [stream, setStream] = useState<MediaStream | null>(null);
const replaceStream = useCallback((newStream: MediaStream | null) => {
setStream((oldStream) => {
// Clean up old stream if it exists
if (oldStream) {
oldStream.getTracks().forEach((track) => track.stop());
}
if (newStream) {
const videoTrack = newStream.getVideoTracks()[0];
const settings = videoTrack.getSettings();
}
return newStream;
});
}, []);
const startWebcam = useCallback(async () => {
if (!deviceId || !selectedAudioDeviceId) {
return null;
}
if (frameRate == 0) {
return null;
}
try {
const newStream = await navigator.mediaDevices.getUserMedia({
video: {
...(deviceId ? { deviceId: { exact: deviceId } } : {}),
width: { ideal: 512 },
height: { ideal: 512 },
aspectRatio: { ideal: 1 },
frameRate: { ideal: frameRate, max: frameRate },
},
audio: {
...(selectedAudioDeviceId ? { deviceId: { exact: selectedAudioDeviceId } } : {}),
sampleRate: 16000,
sampleSize: 16,
channelCount: 1,
},
});
return newStream;
} catch (error) {
console.error("Error accessing media devices.", error);
return null;
}
}, [deviceId, frameRate, selectedAudioDeviceId]);
useEffect(() => {
if (!deviceId || !selectedAudioDeviceId) return;
if (frameRate == 0) return;
startWebcam().then((newStream) => {
replaceStream(newStream);
if (newStream) {
onStreamReady(newStream);
}
});
return () => {
replaceStream(null);
};
}, [deviceId, frameRate, selectedAudioDeviceId, startWebcam, replaceStream, onStreamReady]);
return (
<div>
<StreamCanvas
stream={stream}
frameRate={frameRate}
onStreamReady={onStreamReady}
/>
</div>
);
}