Ezmary commited on
Commit
a77f50e
·
verified ·
1 Parent(s): bcf74e1

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

Browse files
src/components/control-tray/ControlTray.tsx CHANGED
@@ -6,7 +6,8 @@ import cn from "classnames";
6
  import React, { memo, ReactNode, RefObject, useEffect, useRef, useState } from "react";
7
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
8
  import { AudioRecorder } from "../../lib/audio-recorder";
9
- // SVG Icons for Controls (همانطور که قبلا تعریف شد)
 
10
  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>;
11
  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>;
12
  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>;
@@ -37,37 +38,38 @@ function ControlTray({
37
  }: ControlTrayProps) {
38
  const { client, connected, connect, disconnect } = useLiveAPIContext();
39
  const [audioRecorder] = useState(() => new AudioRecorder());
40
- const [muted, setMuted] = useState(true);
41
- const [inVolume, setInVolume] = useState(0);
42
  const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
43
  const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>('user');
44
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
 
45
 
 
46
  useEffect(() => {
47
  setMuted(!isAppMicActive);
48
  }, [isAppMicActive]);
49
 
 
50
  useEffect(() => {
51
- console.log(`isAppCamActive effect: ${isAppCamActive}, current activeLocalVideoStream: ${activeLocalVideoStream ? 'Exists' : 'Null'}`);
52
- if (isAppCamActive && !activeLocalVideoStream) {
53
- console.log("isAppCamActive TRUE and no stream, calling startWebcam()");
54
  startWebcam();
55
  } else if (!isAppCamActive && activeLocalVideoStream) {
56
- console.log("isAppCamActive FALSE and stream exists, calling stopWebcam()");
57
  stopWebcam();
58
  }
59
- // eslint-disable-next-line react-hooks/exhaustive-deps
60
- }, [isAppCamActive]); // activeLocalVideoStream removed to prevent re-triggering startWebcam if it fails and sets stream to null
61
 
 
62
  useEffect(() => {
63
  const onData = (base64: string) => {
64
- if (client && connected) {
65
  client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
66
  }
67
  };
68
- if (connected && !muted && audioRecorder) {
69
  audioRecorder.on("data", onData).on("volume", setInVolume).start();
70
- } else if (audioRecorder && audioRecorder.recording) { // Check if it's recording before stopping
71
  audioRecorder.stop();
72
  }
73
  return () => {
@@ -76,253 +78,194 @@ function ControlTray({
76
  if (audioRecorder.recording) audioRecorder.stop();
77
  }
78
  };
79
- }, [connected, client, muted, audioRecorder]);
80
 
81
- const renderCanvasRef = useRef<HTMLCanvasElement>(null);
82
  useEffect(() => {
83
  let timeoutId = -1;
84
  function sendVideoFrame() {
85
- if (connected && activeLocalVideoStream) {
86
- timeoutId = window.setTimeout(sendVideoFrame, 1000 / 0.5);
87
- }
88
- const video = videoRef.current;
89
- const canvas = renderCanvasRef.current;
90
- if (!video || !canvas || video.readyState < video.HAVE_METADATA || video.paused || video.ended || !client) return;
91
- try {
92
- const ctx = canvas.getContext("2d");
93
- if (!ctx) return;
94
- const scale = 0.25;
95
- canvas.width = video.videoWidth * scale;
96
- canvas.height = video.videoHeight * scale;
97
- if (canvas.width > 0 && canvas.height > 0) {
98
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
99
- const base64 = canvas.toDataURL("image/jpeg", 0.7);
100
- const data = base64.slice(base64.indexOf(",") + 1);
101
- client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
 
 
 
 
 
 
 
102
  }
103
- } catch (error) {
104
- console.error("❌ Error processing video frame:", error);
 
 
105
  }
106
  }
 
107
  if (connected && activeLocalVideoStream && videoRef.current) {
108
- setTimeout(sendVideoFrame, 200);
 
109
  }
110
- return () => { clearTimeout(timeoutId); };
111
- }, [connected, activeLocalVideoStream, client, videoRef]);
 
 
 
 
112
 
 
 
113
  useEffect(() => {
114
  if (videoRef.current) {
115
- console.log("VideoRef Effect: Current srcObject:", videoRef.current.srcObject ? 'Exists' : 'Null', "New activeLocalVideoStream:", activeLocalVideoStream ? 'Exists' : 'Null');
116
  if (videoRef.current.srcObject !== activeLocalVideoStream) {
117
  videoRef.current.srcObject = activeLocalVideoStream;
118
- console.log("VideoRef Effect: Assigned new stream to srcObject.");
119
  if (activeLocalVideoStream) {
120
- console.log("VideoRef Effect: Attempting to play video.");
121
- videoRef.current.play().then(() => {
122
- console.log("VideoRef Effect: Video playback started successfully.");
123
- }).catch(e => {
124
- console.warn("VideoRef Effect: Video play failed:", e);
125
- });
126
- } else {
127
- console.log("VideoRef Effect: activeLocalVideoStream is null, video srcObject set to null.");
128
  }
129
  }
130
- } else {
131
- console.warn("VideoRef Effect: videoRef.current is null.");
132
  }
133
  }, [activeLocalVideoStream, videoRef]);
134
 
135
  const ensureConnected = async () => {
136
- console.log("ensureConnected called. Current connected state:", connected);
137
  if (!connected) {
138
  try {
139
- console.log("ensureConnected: Attempting to connect...");
140
  await connect();
141
- console.log("ensureConnected: Connection successful.");
142
  return true;
143
  } catch (err) {
144
- console.error('❌ ensureConnected: Connection error:', err);
145
  return false;
146
  }
147
  }
148
- console.log("ensureConnected: Already connected.");
149
  return true;
150
  };
151
 
152
  const handleMicToggle = async () => {
153
- console.log("handleMicToggle called. isSwitchingCamera:", isSwitchingCamera, "Current isAppMicActive:", isAppMicActive);
154
  if (isSwitchingCamera) return;
155
  const newMicState = !isAppMicActive;
156
- if (newMicState) {
157
  if(!await ensureConnected()) {
158
- console.log("handleMicToggle: ensureConnected failed while trying to turn mic ON.");
159
- onAppMicToggle(false);
160
  return;
161
  }
162
  }
163
  onAppMicToggle(newMicState);
164
- console.log("handleMicToggle: Mic state toggled to", newMicState);
 
 
 
165
  };
166
 
167
  const startWebcam = async (facingModeToTry: 'user' | 'environment' = currentFacingMode) => {
168
- console.log("Attempting to start webcam. Current facingMode:", facingModeToTry, "isSwitchingCamera:", isSwitchingCamera);
169
- if (isSwitchingCamera) {
170
- console.log("startWebcam: Already switching camera, aborting.");
171
- return;
172
- }
173
- setIsSwitchingCamera(true);
174
 
175
  if(!await ensureConnected()) {
176
- console.error("startWebcam: ensureConnected failed. Aborting webcam start.");
177
  onAppCamToggle(false);
178
  setIsSwitchingCamera(false);
179
  return;
180
  }
181
- console.log("startWebcam: ensureConnected succeeded.");
182
 
183
  try {
184
- console.log(`🚀 Getting user media with facingMode: ${facingModeToTry}`);
185
  const mediaStream = await navigator.mediaDevices.getUserMedia({
186
  video: { facingMode: facingModeToTry },
187
  audio: false,
188
  });
189
- console.log("startWebcam: getUserMedia successful. Stream ID:", mediaStream.id);
190
  setActiveLocalVideoStream(mediaStream);
191
  onVideoStreamChange(mediaStream);
192
  setCurrentFacingMode(facingModeToTry);
193
- onAppCamToggle(true);
194
- console.log("startWebcam: Webcam started and states updated.");
195
  } catch (error) {
196
  console.error(`❌ Error starting webcam with ${facingModeToTry}:`, error);
197
- if (facingModeToTry === 'user' && (error as Error).name !== 'NotFoundError') {
198
- try {
199
- console.log("startWebcam: Attempting fallback to 'environment' facingMode.");
200
- const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
201
- console.log("startWebcam: Fallback getUserMedia successful. Stream ID:", fallbackStream.id);
202
- setActiveLocalVideoStream(fallbackStream);
203
- onVideoStreamChange(fallbackStream);
204
- setCurrentFacingMode('environment');
205
- onAppCamToggle(true);
206
- } catch (fallbackError) {
207
- console.error('❌ Error starting webcam fallback:', fallbackError);
208
- setActiveLocalVideoStream(null);
209
- onVideoStreamChange(null);
210
- onAppCamToggle(false);
211
- }
212
- } else {
213
- setActiveLocalVideoStream(null);
214
- onVideoStreamChange(null);
215
- onAppCamToggle(false);
216
- }
217
  } finally {
218
  setIsSwitchingCamera(false);
219
- console.log("startWebcam: Finished attempt, isSwitchingCamera set to false.");
220
  }
221
  };
222
 
223
  const stopWebcam = () => {
224
- console.log("stopWebcam called.");
225
  if (activeLocalVideoStream) {
226
- console.log("stopWebcam: Stopping tracks for stream ID:", activeLocalVideoStream.id);
227
  activeLocalVideoStream.getTracks().forEach(track => track.stop());
228
- } else {
229
- console.log("stopWebcam: No activeLocalVideoStream to stop.");
230
  }
231
  setActiveLocalVideoStream(null);
232
  onVideoStreamChange(null);
233
- onAppCamToggle(false);
234
- console.log("stopWebcam: Webcam stopped and states updated.");
235
  };
236
 
237
  const handleCamToggle = () => {
238
- console.log("handleCamToggle called. Current isAppCamActive:", isAppCamActive);
239
- if (isAppCamActive) {
240
- console.log("handleCamToggle: Current cam is active, calling stopWebcam.");
241
- stopWebcam();
242
- } else {
243
- console.log("handleCamToggle: Current cam is inactive, calling startWebcam.");
244
- startWebcam();
245
- }
246
  };
247
 
248
  const handleSwitchCamera = async () => {
249
- console.log("handleSwitchCamera called. isAppCamActive:", isAppCamActive, "Stream exists:", !!activeLocalVideoStream, "isSwitchingCamera:", isSwitchingCamera);
250
- if (!isAppCamActive || !activeLocalVideoStream || isSwitchingCamera) {
251
- console.log("handleSwitchCamera: Pre-conditions not met, aborting.");
252
- return;
253
- }
254
 
255
  setIsSwitchingCamera(true);
256
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
257
- console.log(`handleSwitchCamera: Stopping current stream tracks (Stream ID: ${activeLocalVideoStream.id}). Target facingMode: ${targetFacingMode}`);
258
 
 
259
  activeLocalVideoStream.getTracks().forEach(track => track.stop());
260
- setActiveLocalVideoStream(null);
261
- onVideoStreamChange(null);
262
 
263
  try {
264
- console.log(`🔄 Attempting to switch camera to: ${targetFacingMode}`);
265
  const newStream = await navigator.mediaDevices.getUserMedia({
266
  video: { facingMode: { exact: targetFacingMode } },
267
  audio: false,
268
  });
269
- console.log("handleSwitchCamera: Switched camera successfully. New Stream ID:", newStream.id);
270
- setActiveLocalVideoStream(newStream);
271
  onVideoStreamChange(newStream);
272
  setCurrentFacingMode(targetFacingMode);
273
- if (videoRef.current) {
274
- videoRef.current.srcObject = newStream;
275
- videoRef.current.play().catch(e => console.warn("Play failed on switch:", e));
276
- }
277
  } catch (error) {
278
  console.error(`❌ Error switching camera to ${targetFacingMode}:`, error);
279
- console.log(`handleSwitchCamera: Attempting to restore camera to previous mode: ${currentFacingMode}`);
280
  try {
281
- const restoredStream = await navigator.mediaDevices.getUserMedia({
282
- video: { facingMode: currentFacingMode },
283
- audio: false,
284
- });
285
- console.log("handleSwitchCamera: Restored camera successfully. Stream ID:", restoredStream.id);
286
  setActiveLocalVideoStream(restoredStream);
287
  onVideoStreamChange(restoredStream);
288
- if (videoRef.current) {
289
- videoRef.current.srcObject = restoredStream;
290
- videoRef.current.play().catch(e => console.warn("Play failed on restore:", e));
291
- }
292
  } catch (restoreError) {
293
  console.error('❌ Error restoring camera:', restoreError);
294
- stopWebcam();
295
- onAppCamToggle(false);
 
296
  }
297
  } finally {
298
  setIsSwitchingCamera(false);
299
- console.log("handleSwitchCamera: Finished attempt, isSwitchingCamera set to false.");
300
  }
301
  };
302
 
 
303
  useEffect(() => {
304
- if (!connected) {
305
- console.log("Not connected: Stopping video and audio if active.");
306
- if (activeLocalVideoStream) {
307
- activeLocalVideoStream.getTracks().forEach(track => track.stop());
308
- setActiveLocalVideoStream(null);
309
- onVideoStreamChange(null);
310
- onAppCamToggle(false);
311
- }
312
- if (audioRecorder.recording) {
313
- audioRecorder.stop();
314
- onAppMicToggle(false);
315
- }
316
  }
317
- }, [connected, audioRecorder, activeLocalVideoStream, onAppCamToggle, onAppMicToggle, onVideoStreamChange]);
318
 
319
 
320
  return (
321
- <footer id="footer-controls" className={cn("footer-controls", {
322
  'layout-default': !isAppCamActive,
323
  'layout-with-small-logo': isAppCamActive
324
  })}>
325
- <canvas style={{ display: "none" }} ref={renderCanvasRef} />
 
326
  <div id="cam-button-wrapper" className="relative flex justify-center">
327
  <button
328
  id="cam-button"
@@ -333,11 +276,11 @@ function ControlTray({
333
  >
334
  {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
335
  </button>
336
- <div id="switch-camera-button-container" className={cn("switch-camera-button-container", { 'visible': isAppCamActive })}>
337
  <button
338
  id="switch-camera-button"
339
  aria-label="Switch Camera"
340
- className="switch-camera-button-content"
341
  onClick={handleSwitchCamera}
342
  disabled={!isAppCamActive || isSwitchingCamera}
343
  >
@@ -362,15 +305,16 @@ function ControlTray({
362
  {isAppMicActive ? <SvgPauseIcon /> : <SvgMicrophoneIcon />}
363
  </button>
364
 
 
365
  <button
366
  style={{ display: 'none'}}
367
  onClick={async () => {
368
  if (connected) await disconnect();
369
  else await connect();
370
  }}
371
- title={connected ? "Disconnect Stream" : "Connect Stream"}
372
  >
373
- {connected ? "Connected (Internal)" : "Disconnected (Internal)"}
374
  </button>
375
  </footer>
376
  );
 
6
  import React, { memo, ReactNode, RefObject, useEffect, useRef, useState } from "react";
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 [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) {
 
 
56
  startWebcam();
57
  } else if (!isAppCamActive && activeLocalVideoStream) {
 
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 () => {
 
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
+ }
109
+ } catch (error) {
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
+
131
+ // Assign stream to video element
132
  useEffect(() => {
133
  if (videoRef.current) {
 
134
  if (videoRef.current.srcObject !== activeLocalVideoStream) {
135
  videoRef.current.srcObject = activeLocalVideoStream;
 
136
  if (activeLocalVideoStream) {
137
+ videoRef.current.play().catch(e => console.warn("Video play failed:", e));
 
 
 
 
 
 
 
138
  }
139
  }
 
 
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
  }
 
153
  return true;
154
  };
155
 
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 },
185
  audio: false,
186
  });
 
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
  }
200
  };
201
 
202
  const stopWebcam = () => {
 
203
  if (activeLocalVideoStream) {
 
204
  activeLocalVideoStream.getTracks().forEach(track => track.stop());
 
 
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
271
  id="cam-button"
 
276
  >
277
  {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
278
  </button>
279
+ <div id="switch-camera-button-container" className={cn("switch-camera-button-container", { 'visible': isAppCamActive && !isSwitchingCamera })}>
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
  >
 
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
  );