Ezmary commited on
Commit
6a9ed5b
·
verified ·
1 Parent(s): d17837b

Update src/components/control-tray/ControlTray.tsx

Browse files
src/components/control-tray/ControlTray.tsx CHANGED
@@ -7,7 +7,7 @@ import React, { memo, ReactNode, RefObject, useEffect, useRef, useState } from "
7
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
8
  import { AudioRecorder } from "../../lib/audio-recorder";
9
 
10
- // SVG Icons for Controls
11
  const SvgPauseIcon = () => <svg width="37" height="37" viewBox="0 0 37 37" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M15.9872 29.6198V8.28342C15.9872 6.25781 15.132 5.44757 12.9713 5.44757H7.52469C5.36404 5.44757 4.50879 6.25781 4.50879 8.28342V29.6198C4.50879 31.6454 5.36404 32.4556 7.52469 32.4556H12.9713C15.132 32.4556 15.9872 31.6454 15.9872 29.6198Z" fill="#BE123C"/><path opacity="0.4" d="M31.5175 29.6198V8.28342C31.5175 6.25781 30.6622 5.44757 28.5016 5.44757H23.055C20.9093 5.44757 20.0391 6.25781 20.0391 8.28342V29.6198C20.0391 31.6454 20.8943 32.4556 23.055 32.4556H28.5016C30.6622 32.4556 31.5175 31.6454 31.5175 29.6198Z" fill="#BE123C"/></svg>;
12
  const SvgMicrophoneIcon = () => <svg width="38" height="38" viewBox="0 0 69 68" fill="none" xmlns="http://www.w3.org/2000/svg" transform="scale(0.55)"><path opacity="0.4" d="M49.9479 27.1824C49.0803 27.1824 48.3907 27.872 48.3907 28.7396V32.2544C48.3907 40.1293 41.984 46.5361 34.109 46.5361C26.234 46.5361 19.8273 40.1293 19.8273 32.2544V28.7173C19.8273 27.8497 19.1377 27.1601 18.2701 27.1601C17.4025 27.1601 16.7129 27.8497 16.7129 28.7173V32.2321C16.7129 41.2861 23.6758 48.7384 32.5518 49.5393V54.2776C32.5518 55.1452 33.2414 55.8348 34.109 55.8348C34.9766 55.8348 35.6662 55.1452 35.6662 54.2776V49.5393C44.52 48.7607 51.5051 41.2861 51.5051 32.2321V28.7173C51.4829 27.872 50.7933 27.1824 49.9479 27.1824Z" fill="#BE123C"/><path d="M34.1099 11.3434C28.682 11.3434 24.2773 15.7481 24.2773 21.176V32.5658C24.2773 37.9938 28.682 42.3984 34.1099 42.3984C39.5379 42.3984 43.9425 37.9938 43.9425 32.5658V21.176C43.9425 15.7481 39.5379 11.3434 34.1099 11.3434ZM37.0241 26.8042C36.8684 27.3826 36.3567 27.7608 35.7784 27.7608C35.6671 27.7608 35.5559 27.7385 35.4447 27.7163C34.5771 27.4716 33.665 27.4716 32.7974 27.7163C32.0856 27.9165 31.396 27.4938 31.218 26.8042C31.0178 26.1146 31.4404 25.4027 32.1301 25.2247C33.4426 24.8688 34.8218 24.8688 36.1343 25.2247C36.8017 25.4027 37.2021 26.1146 37.0241 26.8042ZM38.2031 22.4885C38.0029 23.0224 37.5135 23.3339 36.9796 23.3339C36.8239 23.3339 36.6904 23.3116 36.5347 23.2671C34.9775 22.6887 33.2423 22.6887 31.6852 23.2671C31.0178 23.5118 30.2614 23.1559 30.0167 22.4885C29.772 21.8212 30.128 21.0648 30.7953 20.8423C32.9309 20.0637 35.289 20.0637 37.4245 20.8423C38.0919 21.087 38.4478 21.8212 38.2031 22.4885Z" fill="#BE123C"/></svg>;
13
  const SvgCameraIcon = () => <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.4" d="M21.8118 5.52235H11.9265C6.29183 5.52235 4.10059 7.7136 4.10059 13.3482V26.5286C4.10059 30.318 6.16002 34.3545 11.9265 34.3545H21.8118C27.4464 34.3545 29.6376 32.1633 29.6376 26.5286V13.3482C29.6376 7.7136 27.4464 5.52235 21.8118 5.52235Z" fill="#2252A0"/><path d="M19.3406 18.9169C21.0512 18.9169 22.438 17.5302 22.438 15.8195C22.438 14.1089 21.0512 12.7222 19.3406 12.7222C17.6299 12.7222 16.2432 14.1089 16.2432 15.8195C16.2432 17.5302 17.6299 18.9169 19.3406 18.9169Z" fill="#2252A0"/><path d="M36.0629 10.3332C35.3874 9.98721 33.9705 9.5918 32.0429 10.9428L29.6045 12.6562C29.621 12.8869 29.6374 13.1011 29.6374 13.3482V26.5286C29.6374 26.7758 29.6045 26.9899 29.6045 27.2206L32.0429 28.934C33.0643 29.659 33.954 29.8896 34.6625 29.8896C35.2721 29.8896 35.7499 29.7249 36.0629 29.5601C36.7384 29.2141 37.8752 28.275 37.8752 25.919V13.9743C37.8752 11.6183 36.7384 10.6792 36.0629 10.3332Z" fill="#2252A0"/></svg>;
@@ -38,18 +38,11 @@ function ControlTray({
38
  }: ControlTrayProps) {
39
  const { client, connected, connect, disconnect } = useLiveAPIContext();
40
  const [audioRecorder] = useState(() => new AudioRecorder());
41
- const [muted, setMuted] = useState(true); // Internal state for AudioRecorder
42
- const [inVolume, setInVolume] = useState(0); // For visual feedback if needed
43
  const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
44
  const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>('user');
45
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
46
  const renderCanvasRef = useRef<HTMLCanvasElement>(null);
47
 
48
- // Sync internal muted state with app-level mic active state
49
- useEffect(() => {
50
- setMuted(!isAppMicActive);
51
- }, [isAppMicActive]);
52
-
53
  // Manage webcam based on app-level camera active state
54
  useEffect(() => {
55
  if (isAppCamActive && !activeLocalVideoStream && !isSwitchingCamera) {
@@ -58,51 +51,52 @@ function ControlTray({
58
  stopWebcam();
59
  }
60
  // eslint-disable-next-line react-hooks/exhaustive-deps
61
- }, [isAppCamActive]); // Removed activeLocalVideoStream to prevent loops on start failure
62
 
63
  // Audio Recorder Logic
64
  useEffect(() => {
65
  const onData = (base64: string) => {
66
- if (client && connected && isAppMicActive) { // Send audio if mic is on at app level
67
  client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
68
  }
69
  };
70
- if (connected && isAppMicActive && audioRecorder) { // Use isAppMicActive here
71
- audioRecorder.on("data", onData).on("volume", setInVolume).start();
72
  } else if (audioRecorder && audioRecorder.recording) {
73
  audioRecorder.stop();
74
  }
75
  return () => {
76
  if (audioRecorder) {
77
- audioRecorder.off("data", onData).off("volume", setInVolume);
78
  if (audioRecorder.recording) audioRecorder.stop();
79
  }
80
  };
81
- }, [connected, client, isAppMicActive, audioRecorder]); // Depend on isAppMicActive
82
 
83
- // Send Video Frame Logic (with increased frequency and quality)
84
  useEffect(() => {
85
  let timeoutId = -1;
86
  function sendVideoFrame() {
 
87
  if (connected && activeLocalVideoStream && client && videoRef.current) {
88
  const video = videoRef.current;
89
- const canvas = renderCanvasRef.current; // Use the ref for canvas
90
  if (!canvas || video.readyState < video.HAVE_METADATA || video.paused || video.ended) {
91
- if (activeLocalVideoStream) timeoutId = window.setTimeout(sendVideoFrame, 1000 / 4); // Retry if stream active
92
  return;
93
  }
94
  try {
95
  const ctx = canvas.getContext("2d");
96
  if (!ctx) return;
97
- const scale = 0.5; // Increased scale for better quality
98
  canvas.width = video.videoWidth * scale;
99
  canvas.height = video.videoHeight * scale;
100
  if (canvas.width > 0 && canvas.height > 0) {
101
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
102
- const base64 = canvas.toDataURL("image/jpeg", 0.8); // Good quality
103
  const data = base64.slice(base64.indexOf(",") + 1);
104
  if (data) {
105
- // console.log(`🖼️ Sending video frame (length: ${data.length}) at ${new Date().toLocaleTimeString()}`);
106
  client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
107
  }
108
  }
@@ -110,21 +104,14 @@ function ControlTray({
110
  console.error("❌ Error processing video frame:", error);
111
  }
112
  }
113
- // Schedule next frame if conditions still met
114
  if (connected && activeLocalVideoStream) {
115
- timeoutId = window.setTimeout(sendVideoFrame, 1000 / 4); // Send ~4 FPS
116
  }
117
  }
118
-
119
  if (connected && activeLocalVideoStream && videoRef.current) {
120
- console.log("🚀 Initializing video frame sending...");
121
- timeoutId = window.setTimeout(sendVideoFrame, 200); // Initial delay
122
  }
123
-
124
- return () => {
125
- clearTimeout(timeoutId);
126
- console.log("🛑 Video frame sending stopped.");
127
- };
128
  }, [connected, activeLocalVideoStream, client, videoRef, renderCanvasRef]);
129
 
130
 
@@ -140,13 +127,15 @@ function ControlTray({
140
  }
141
  }, [activeLocalVideoStream, videoRef]);
142
 
143
- const ensureConnected = async () => {
144
  if (!connected) {
145
  try {
 
146
  await connect();
 
147
  return true;
148
  } catch (err) {
149
- console.error('❌ Connection error in ensureConnected:', err);
150
  return false;
151
  }
152
  }
@@ -156,29 +145,22 @@ function ControlTray({
156
  const handleMicToggle = async () => {
157
  if (isSwitchingCamera) return;
158
  const newMicState = !isAppMicActive;
 
159
  if (newMicState) { // Turning mic ON
160
- if(!await ensureConnected()) {
161
- onAppMicToggle(false); // Keep it off if connection fails
162
  return;
163
  }
164
  }
165
  onAppMicToggle(newMicState);
166
- // If turning off and cam is also off, consider disconnecting
167
- // if (!newMicState && !isAppCamActive && connected) {
168
- // disconnect();
169
- // }
170
  };
171
 
172
  const startWebcam = async (facingModeToTry: 'user' | 'environment' = currentFacingMode) => {
173
  if (isSwitchingCamera) return;
174
  setIsSwitchingCamera(true);
175
 
176
- if(!await ensureConnected()) {
177
- onAppCamToggle(false);
178
- setIsSwitchingCamera(false);
179
- return;
180
- }
181
-
182
  try {
183
  const mediaStream = await navigator.mediaDevices.getUserMedia({
184
  video: { facingMode: facingModeToTry },
@@ -187,13 +169,12 @@ function ControlTray({
187
  setActiveLocalVideoStream(mediaStream);
188
  onVideoStreamChange(mediaStream);
189
  setCurrentFacingMode(facingModeToTry);
190
- // onAppCamToggle(true); // This will be set by the useEffect in App.tsx if isAppCamActive changes
191
  } catch (error) {
192
- console.error(`❌ Error starting webcam with ${facingModeToTry}:`, error);
193
- // Fallback or error handling logic...
194
  setActiveLocalVideoStream(null);
195
  onVideoStreamChange(null);
196
- onAppCamToggle(false); // Explicitly turn off if start fails
197
  } finally {
198
  setIsSwitchingCamera(false);
199
  }
@@ -205,66 +186,71 @@ function ControlTray({
205
  }
206
  setActiveLocalVideoStream(null);
207
  onVideoStreamChange(null);
208
- // onAppCamToggle(false); // This will be set by the useEffect in App.tsx
209
  };
210
 
211
- const handleCamToggle = () => {
212
  if (isSwitchingCamera) return;
213
- onAppCamToggle(!isAppCamActive); // Let App.tsx manage the state and trigger start/stopWebcam
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  };
215
 
216
  const handleSwitchCamera = async () => {
 
217
  if (!isAppCamActive || !activeLocalVideoStream || isSwitchingCamera) return;
218
 
219
  setIsSwitchingCamera(true);
220
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
221
 
222
- // Stop current stream first
223
  activeLocalVideoStream.getTracks().forEach(track => track.stop());
224
- // setActiveLocalVideoStream(null); // Let new stream assignment handle this
225
- // onVideoStreamChange(null);
226
 
227
  try {
228
  const newStream = await navigator.mediaDevices.getUserMedia({
229
  video: { facingMode: { exact: targetFacingMode } },
230
  audio: false,
231
  });
232
- setActiveLocalVideoStream(newStream); // This will trigger videoRef update
233
  onVideoStreamChange(newStream);
234
  setCurrentFacingMode(targetFacingMode);
235
  } catch (error) {
236
  console.error(`❌ Error switching camera to ${targetFacingMode}:`, error);
237
- // Attempt to restore previous stream or stop
238
  try {
239
  const restoredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: currentFacingMode }, audio: false });
240
  setActiveLocalVideoStream(restoredStream);
241
  onVideoStreamChange(restoredStream);
242
  } catch (restoreError) {
243
  console.error('❌ Error restoring camera:', restoreError);
244
- setActiveLocalVideoStream(null); // Ensure stream is cleared
245
  onVideoStreamChange(null);
246
- onAppCamToggle(false); // Turn off cam at app level if all fails
247
  }
248
  } finally {
249
  setIsSwitchingCamera(false);
250
  }
251
  };
252
 
253
- // Disconnect logic (optional: if both mic and cam are off)
254
- useEffect(() => {
255
- if (!isAppMicActive && !isAppCamActive && connected) {
256
- console.log("🎤❌ 📸❌ Both Mic and Cam are off. Disconnecting stream.");
257
- // disconnect(); // Uncomment if you want to auto-disconnect
258
- }
259
- }, [isAppMicActive, isAppCamActive, connected, disconnect]);
260
-
261
-
262
  return (
263
- <footer id="footer-controls" className={cn("footer-controls fixed bottom-0 left-1/2 transform -translate-x-1/2 z-50", { // Added positioning classes
264
  'layout-default': !isAppCamActive,
265
  'layout-with-small-logo': isAppCamActive
266
  })}>
267
- <canvas style={{ display: "none" }} ref={renderCanvasRef} /> {/* Canvas for video frame processing */}
268
 
269
  <div id="cam-button-wrapper" className="relative flex justify-center">
270
  <button
@@ -272,7 +258,7 @@ function ControlTray({
272
  className="control-button cam-button-color"
273
  onClick={handleCamToggle}
274
  disabled={isSwitchingCamera || !supportsVideo}
275
- title={isAppCamActive ? "Stop Camera" : "Start Camera"}
276
  >
277
  {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
278
  </button>
@@ -280,7 +266,7 @@ function ControlTray({
280
  <button
281
  id="switch-camera-button"
282
  aria-label="Switch Camera"
283
- className="switch-camera-button-content group" // Added group for icon hover effects
284
  onClick={handleSwitchCamera}
285
  disabled={!isAppCamActive || isSwitchingCamera}
286
  >
@@ -304,18 +290,6 @@ function ControlTray({
304
  >
305
  {isAppMicActive ? <SvgPauseIcon /> : <SvgMicrophoneIcon />}
306
  </button>
307
-
308
- {/* Hidden button for manual connect/disconnect for debugging if needed */}
309
- <button
310
- style={{ display: 'none'}}
311
- onClick={async () => {
312
- if (connected) await disconnect();
313
- else await connect();
314
- }}
315
- title={connected ? "Disconnect Stream (Debug)" : "Connect Stream (Debug)"}
316
- >
317
- {connected ? "D" : "C"}
318
- </button>
319
  </footer>
320
  );
321
  }
 
7
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
8
  import { AudioRecorder } from "../../lib/audio-recorder";
9
 
10
+ // SVG Icons for Controls (مثل قبل)
11
  const SvgPauseIcon = () => <svg width="37" height="37" viewBox="0 0 37 37" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M15.9872 29.6198V8.28342C15.9872 6.25781 15.132 5.44757 12.9713 5.44757H7.52469C5.36404 5.44757 4.50879 6.25781 4.50879 8.28342V29.6198C4.50879 31.6454 5.36404 32.4556 7.52469 32.4556H12.9713C15.132 32.4556 15.9872 31.6454 15.9872 29.6198Z" fill="#BE123C"/><path opacity="0.4" d="M31.5175 29.6198V8.28342C31.5175 6.25781 30.6622 5.44757 28.5016 5.44757H23.055C20.9093 5.44757 20.0391 6.25781 20.0391 8.28342V29.6198C20.0391 31.6454 20.8943 32.4556 23.055 32.4556H28.5016C30.6622 32.4556 31.5175 31.6454 31.5175 29.6198Z" fill="#BE123C"/></svg>;
12
  const SvgMicrophoneIcon = () => <svg width="38" height="38" viewBox="0 0 69 68" fill="none" xmlns="http://www.w3.org/2000/svg" transform="scale(0.55)"><path opacity="0.4" d="M49.9479 27.1824C49.0803 27.1824 48.3907 27.872 48.3907 28.7396V32.2544C48.3907 40.1293 41.984 46.5361 34.109 46.5361C26.234 46.5361 19.8273 40.1293 19.8273 32.2544V28.7173C19.8273 27.8497 19.1377 27.1601 18.2701 27.1601C17.4025 27.1601 16.7129 27.8497 16.7129 28.7173V32.2321C16.7129 41.2861 23.6758 48.7384 32.5518 49.5393V54.2776C32.5518 55.1452 33.2414 55.8348 34.109 55.8348C34.9766 55.8348 35.6662 55.1452 35.6662 54.2776V49.5393C44.52 48.7607 51.5051 41.2861 51.5051 32.2321V28.7173C51.4829 27.872 50.7933 27.1824 49.9479 27.1824Z" fill="#BE123C"/><path d="M34.1099 11.3434C28.682 11.3434 24.2773 15.7481 24.2773 21.176V32.5658C24.2773 37.9938 28.682 42.3984 34.1099 42.3984C39.5379 42.3984 43.9425 37.9938 43.9425 32.5658V21.176C43.9425 15.7481 39.5379 11.3434 34.1099 11.3434ZM37.0241 26.8042C36.8684 27.3826 36.3567 27.7608 35.7784 27.7608C35.6671 27.7608 35.5559 27.7385 35.4447 27.7163C34.5771 27.4716 33.665 27.4716 32.7974 27.7163C32.0856 27.9165 31.396 27.4938 31.218 26.8042C31.0178 26.1146 31.4404 25.4027 32.1301 25.2247C33.4426 24.8688 34.8218 24.8688 36.1343 25.2247C36.8017 25.4027 37.2021 26.1146 37.0241 26.8042ZM38.2031 22.4885C38.0029 23.0224 37.5135 23.3339 36.9796 23.3339C36.8239 23.3339 36.6904 23.3116 36.5347 23.2671C34.9775 22.6887 33.2423 22.6887 31.6852 23.2671C31.0178 23.5118 30.2614 23.1559 30.0167 22.4885C29.772 21.8212 30.128 21.0648 30.7953 20.8423C32.9309 20.0637 35.289 20.0637 37.4245 20.8423C38.0919 21.087 38.4478 21.8212 38.2031 22.4885Z" fill="#BE123C"/></svg>;
13
  const SvgCameraIcon = () => <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.4" d="M21.8118 5.52235H11.9265C6.29183 5.52235 4.10059 7.7136 4.10059 13.3482V26.5286C4.10059 30.318 6.16002 34.3545 11.9265 34.3545H21.8118C27.4464 34.3545 29.6376 32.1633 29.6376 26.5286V13.3482C29.6376 7.7136 27.4464 5.52235 21.8118 5.52235Z" fill="#2252A0"/><path d="M19.3406 18.9169C21.0512 18.9169 22.438 17.5302 22.438 15.8195C22.438 14.1089 21.0512 12.7222 19.3406 12.7222C17.6299 12.7222 16.2432 14.1089 16.2432 15.8195C16.2432 17.5302 17.6299 18.9169 19.3406 18.9169Z" fill="#2252A0"/><path d="M36.0629 10.3332C35.3874 9.98721 33.9705 9.5918 32.0429 10.9428L29.6045 12.6562C29.621 12.8869 29.6374 13.1011 29.6374 13.3482V26.5286C29.6374 26.7758 29.6045 26.9899 29.6045 27.2206L32.0429 28.934C33.0643 29.659 33.954 29.8896 34.6625 29.8896C35.2721 29.8896 35.7499 29.7249 36.0629 29.5601C36.7384 29.2141 37.8752 28.275 37.8752 25.919V13.9743C37.8752 11.6183 36.7384 10.6792 36.0629 10.3332Z" fill="#2252A0"/></svg>;
 
38
  }: ControlTrayProps) {
39
  const { client, connected, connect, disconnect } = useLiveAPIContext();
40
  const [audioRecorder] = useState(() => new AudioRecorder());
 
 
41
  const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
42
  const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>('user');
43
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
44
  const renderCanvasRef = useRef<HTMLCanvasElement>(null);
45
 
 
 
 
 
 
46
  // Manage webcam based on app-level camera active state
47
  useEffect(() => {
48
  if (isAppCamActive && !activeLocalVideoStream && !isSwitchingCamera) {
 
51
  stopWebcam();
52
  }
53
  // eslint-disable-next-line react-hooks/exhaustive-deps
54
+ }, [isAppCamActive]);
55
 
56
  // Audio Recorder Logic
57
  useEffect(() => {
58
  const onData = (base64: string) => {
59
+ if (client && connected && isAppMicActive) {
60
  client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
61
  }
62
  };
63
+ if (connected && isAppMicActive && audioRecorder) {
64
+ audioRecorder.on("data", onData).start(); // Removed .on("volume", setInVolume) if not used
65
  } else if (audioRecorder && audioRecorder.recording) {
66
  audioRecorder.stop();
67
  }
68
  return () => {
69
  if (audioRecorder) {
70
+ audioRecorder.off("data", onData);
71
  if (audioRecorder.recording) audioRecorder.stop();
72
  }
73
  };
74
+ }, [connected, client, isAppMicActive, audioRecorder]);
75
 
76
+ // Send Video Frame Logic
77
  useEffect(() => {
78
  let timeoutId = -1;
79
  function sendVideoFrame() {
80
+ // ... (مثل قبل، با فرکانس 4FPS و scale 0.5) ...
81
  if (connected && activeLocalVideoStream && client && videoRef.current) {
82
  const video = videoRef.current;
83
+ const canvas = renderCanvasRef.current;
84
  if (!canvas || video.readyState < video.HAVE_METADATA || video.paused || video.ended) {
85
+ if (activeLocalVideoStream) timeoutId = window.setTimeout(sendVideoFrame, 1000 / 4);
86
  return;
87
  }
88
  try {
89
  const ctx = canvas.getContext("2d");
90
  if (!ctx) return;
91
+ const scale = 0.5;
92
  canvas.width = video.videoWidth * scale;
93
  canvas.height = video.videoHeight * scale;
94
  if (canvas.width > 0 && canvas.height > 0) {
95
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
96
+ const base64 = canvas.toDataURL("image/jpeg", 0.8);
97
  const data = base64.slice(base64.indexOf(",") + 1);
98
  if (data) {
99
+ // console.log(`🖼️ Sending video frame`);
100
  client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
101
  }
102
  }
 
104
  console.error("❌ Error processing video frame:", error);
105
  }
106
  }
 
107
  if (connected && activeLocalVideoStream) {
108
+ timeoutId = window.setTimeout(sendVideoFrame, 1000 / 4);
109
  }
110
  }
 
111
  if (connected && activeLocalVideoStream && videoRef.current) {
112
+ timeoutId = window.setTimeout(sendVideoFrame, 200);
 
113
  }
114
+ return () => clearTimeout(timeoutId);
 
 
 
 
115
  }, [connected, activeLocalVideoStream, client, videoRef, renderCanvasRef]);
116
 
117
 
 
127
  }
128
  }, [activeLocalVideoStream, videoRef]);
129
 
130
+ const ensureConnectedAndReady = async (): Promise<boolean> => {
131
  if (!connected) {
132
  try {
133
+ console.log("ControlTray: Not connected. Attempting to connect...");
134
  await connect();
135
+ console.log("ControlTray: Connection successful.");
136
  return true;
137
  } catch (err) {
138
+ console.error('❌ ControlTray: Connection error:', err);
139
  return false;
140
  }
141
  }
 
145
  const handleMicToggle = async () => {
146
  if (isSwitchingCamera) return;
147
  const newMicState = !isAppMicActive;
148
+
149
  if (newMicState) { // Turning mic ON
150
+ if (!(await ensureConnectedAndReady())) {
151
+ onAppMicToggle(false); // Keep mic state off if connection fails
152
  return;
153
  }
154
  }
155
  onAppMicToggle(newMicState);
156
+ console.log(`ControlTray: Mic toggled to ${newMicState}`);
 
 
 
157
  };
158
 
159
  const startWebcam = async (facingModeToTry: 'user' | 'environment' = currentFacingMode) => {
160
  if (isSwitchingCamera) return;
161
  setIsSwitchingCamera(true);
162
 
163
+ // ensureConnectedAndReady is now called by handleCamToggle before this
 
 
 
 
 
164
  try {
165
  const mediaStream = await navigator.mediaDevices.getUserMedia({
166
  video: { facingMode: facingModeToTry },
 
169
  setActiveLocalVideoStream(mediaStream);
170
  onVideoStreamChange(mediaStream);
171
  setCurrentFacingMode(facingModeToTry);
172
+ console.log(`ControlTray: Webcam started with ${facingModeToTry}`);
173
  } catch (error) {
174
+ console.error(`❌ ControlTray: Error starting webcam with ${facingModeToTry}:`, error);
 
175
  setActiveLocalVideoStream(null);
176
  onVideoStreamChange(null);
177
+ onAppCamToggle(false); // Signal App to turn off cam state if start fails
178
  } finally {
179
  setIsSwitchingCamera(false);
180
  }
 
186
  }
187
  setActiveLocalVideoStream(null);
188
  onVideoStreamChange(null);
189
+ console.log("ControlTray: Webcam stopped.");
190
  };
191
 
192
+ const handleCamToggle = async () => {
193
  if (isSwitchingCamera) return;
194
+ const newCamState = !isAppCamActive;
195
+
196
+ if (newCamState) { // Turning camera ON
197
+ if (!(await ensureConnectedAndReady())) {
198
+ onAppCamToggle(false); // Keep cam state off if connection fails
199
+ return;
200
+ }
201
+ // If mic is not already active, activate it as well
202
+ if (!isAppMicActive) {
203
+ onAppMicToggle(true); // This will trigger AudioRecorder via useEffect
204
+ console.log("ControlTray: Mic also activated with camera.");
205
+ }
206
+ onAppCamToggle(true); // This will trigger startWebcam via useEffect
207
+ } else { // Turning camera OFF
208
+ onAppCamToggle(false); // This will trigger stopWebcam via useEffect
209
+ // The disconnect logic if both are off is now in App.tsx's AppLogic
210
+ }
211
+ console.log(`ControlTray: Camera toggled to ${newCamState}`);
212
  };
213
 
214
  const handleSwitchCamera = async () => {
215
+ // ... (منطق تعویض دوربین مثل قبل، اما مطمئن شوید که isAppCamActive را به درستی مدیریت می‌کند) ...
216
  if (!isAppCamActive || !activeLocalVideoStream || isSwitchingCamera) return;
217
 
218
  setIsSwitchingCamera(true);
219
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
220
 
 
221
  activeLocalVideoStream.getTracks().forEach(track => track.stop());
 
 
222
 
223
  try {
224
  const newStream = await navigator.mediaDevices.getUserMedia({
225
  video: { facingMode: { exact: targetFacingMode } },
226
  audio: false,
227
  });
228
+ setActiveLocalVideoStream(newStream);
229
  onVideoStreamChange(newStream);
230
  setCurrentFacingMode(targetFacingMode);
231
  } catch (error) {
232
  console.error(`❌ Error switching camera to ${targetFacingMode}:`, error);
 
233
  try {
234
  const restoredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: currentFacingMode }, audio: false });
235
  setActiveLocalVideoStream(restoredStream);
236
  onVideoStreamChange(restoredStream);
237
  } catch (restoreError) {
238
  console.error('❌ Error restoring camera:', restoreError);
239
+ setActiveLocalVideoStream(null);
240
  onVideoStreamChange(null);
241
+ onAppCamToggle(false);
242
  }
243
  } finally {
244
  setIsSwitchingCamera(false);
245
  }
246
  };
247
 
 
 
 
 
 
 
 
 
 
248
  return (
249
+ <footer id="footer-controls" className={cn("footer-controls fixed bottom-0 left-1/2 transform -translate-x-1/2 z-50", {
250
  'layout-default': !isAppCamActive,
251
  'layout-with-small-logo': isAppCamActive
252
  })}>
253
+ <canvas style={{ display: "none" }} ref={renderCanvasRef} />
254
 
255
  <div id="cam-button-wrapper" className="relative flex justify-center">
256
  <button
 
258
  className="control-button cam-button-color"
259
  onClick={handleCamToggle}
260
  disabled={isSwitchingCamera || !supportsVideo}
261
+ title={isAppCamActive ? "Stop Camera & Mic (if not used)" : "Start Camera & Mic"}
262
  >
263
  {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
264
  </button>
 
266
  <button
267
  id="switch-camera-button"
268
  aria-label="Switch Camera"
269
+ className="switch-camera-button-content group"
270
  onClick={handleSwitchCamera}
271
  disabled={!isAppCamActive || isSwitchingCamera}
272
  >
 
290
  >
291
  {isAppMicActive ? <SvgPauseIcon /> : <SvgMicrophoneIcon />}
292
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
293
  </footer>
294
  );
295
  }