Ezmary commited on
Commit
152abf8
·
verified ·
1 Parent(s): f5d2206

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

Browse files
src/components/control-tray/ControlTray.tsx CHANGED
@@ -5,13 +5,17 @@ Copyright 2024 Google LLC
5
  import cn from "classnames";
6
  import React, { memo, RefObject, useEffect, useRef, useState, useCallback } from "react";
7
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
8
- import { useScreenCapture } from "../../hooks/use-screen-capture"; // Keep if screen share is desired
9
  import { AudioRecorder } from "../../lib/audio-recorder";
10
- import { isIOS } from "../../lib/platform";
11
- // import AudioPulse from "../audio-pulse/AudioPulse"; // Original pulse, we'll use CSS for mic
12
- // Make sure your App.scss or equivalent has the .mic-button-wrapper styles
13
 
14
- // SVG Icons for ControlTray
 
 
 
 
 
 
15
  const PauseIcon = () => <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>;
16
  const MicrophoneIcon = () => <svg width="69" height="68" viewBox="0 0 69 68" fill="none" xmlns="http://www.w3.org/2000/svg"><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>;
17
  const CameraIcon = () => <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>;
@@ -25,10 +29,12 @@ const SmallLogoDisplay = ({ isHumanActive }: { isHumanActive: boolean }) => {
25
  if (!isHumanActive) return null;
26
  const size = 80; const iconSize = 35;
27
  const insetBase = { ping: 10, outer: 0, mid: 5, inner: 12, icon: 22.5 };
28
- const bgColorBase = 'blue';
29
 
30
  return (
31
  <div className="relative small-logo-container-inner" style={{ width: `${size}px`, height: `${size}px` }}>
 
 
32
  <div className={`absolute rounded-full opacity-50 animate-ping bg-${bgColorBase}-200 dark:bg-${bgColorBase}-700`} style={{ inset: `${insetBase.ping}px` }}></div>
33
  <div className={`absolute rounded-full opacity-50 bg-${bgColorBase}-200 dark:bg-${bgColorBase}-700`} style={{ inset: `${insetBase.outer}px` }}></div>
34
  <div className={`absolute rounded-full opacity-50 bg-${bgColorBase}-300 dark:bg-${bgColorBase}-600`} style={{ inset: `${insetBase.mid}px` }}></div>
@@ -39,237 +45,242 @@ const SmallLogoDisplay = ({ isHumanActive }: { isHumanActive: boolean }) => {
39
  </div>
40
  );
41
  };
 
42
 
43
 
44
  export type ControlTrayProps = {
45
  videoRef: RefObject<HTMLVideoElement>;
46
  onVideoStreamChange: (stream: MediaStream | null) => void;
47
- setIsMicActive: (isActive: boolean) => void; // To inform App.tsx
48
- setIsCamActiveExternal: (isActive: boolean) => void; // To inform App.tsx
49
- isCamActiveApp: boolean; // Cam state from App.tsx
50
  };
51
 
52
  function ControlTray({
53
  videoRef,
54
  onVideoStreamChange,
55
- setIsMicActive: setIsMicActiveApp,
56
- setIsCamActiveExternal: setIsCamActiveAppExternal,
57
- isCamActiveApp,
58
  }: ControlTrayProps) {
59
  const { client, connected, connect, disconnect } = useLiveAPIContext();
60
- const screenCapture = useScreenCapture(); // Retain for potential screen share
61
 
62
  const [audioRecorder] = useState(() => new AudioRecorder());
63
- const [inVolume, setInVolume] = useState(0); // For mic pulse animation
64
 
65
- const [isMicEnabled, setIsMicEnabled] = useState(false); // Internal: is mic supposed to be on
66
- const [isCamEnabled, setIsCamEnabled] = useState(false); // Internal: is cam supposed to be on
 
67
 
68
- const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
69
  const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>('user');
70
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
71
 
72
- const renderCanvasRef = useRef<HTMLCanvasElement>(null);
73
 
74
- // Sync internal mic/cam enabled state with App's state (via props)
75
  useEffect(() => {
76
- setIsMicActiveApp(isMicEnabled && connected);
77
- }, [isMicEnabled, connected, setIsMicActiveApp]);
78
 
79
  useEffect(() => {
80
- setIsCamActiveAppExternal(isCamEnabled && !!activeLocalVideoStream);
81
- }, [isCamEnabled, activeLocalVideoStream, setIsCamActiveAppExternal]);
82
-
83
 
84
- // Connect/Disconnect based on mic/cam state
85
  useEffect(() => {
86
- const shouldBeConnected = isMicEnabled || isCamEnabled;
87
  if (shouldBeConnected && !connected) {
88
- connect().catch(err => console.error("Failed to connect:", err));
 
89
  } else if (!shouldBeConnected && connected) {
90
- disconnect().catch(err => console.error("Failed to disconnect:", err));
 
91
  }
92
- }, [isMicEnabled, isCamEnabled, connected, connect, disconnect]);
93
 
94
- // Audio recording
95
  useEffect(() => {
96
  const onData = (base64: string) => {
97
- if (client && connected && isMicEnabled) { // Send only if mic is intended to be active
98
  client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
99
  }
100
  };
101
- if (connected && isMicEnabled && audioRecorder) {
102
  audioRecorder.on("data", onData).on("volume", setInVolume).start();
 
103
  } else if (audioRecorder) {
104
  audioRecorder.stop();
105
- setInVolume(0); // Reset volume when stopped
 
106
  }
107
  return () => {
108
  if (audioRecorder) {
109
  audioRecorder.off("data", onData).off("volume", setInVolume).stop();
110
  }
111
  };
112
- }, [connected, client, isMicEnabled, audioRecorder]);
113
 
114
- // Update CSS --volume for mic pulse
115
  useEffect(() => {
116
  document.documentElement.style.setProperty(
117
  "--volume",
118
- `${Math.max(5, Math.min(inVolume * 200, 15))}px` // Adjusted max for new design
 
 
119
  );
120
- }, [inVolume]);
121
-
122
 
123
- // Video frame sending
124
  useEffect(() => {
125
  let frameTimeoutId = -1;
126
  function sendVideoFrame() {
127
- if (connected && isCamEnabled && activeLocalVideoStream && client) {
128
- frameTimeoutId = window.setTimeout(sendVideoFrame, 1000 / 2); // Approx 2 FPS
129
- const video = videoRef.current;
130
- const canvas = renderCanvasRef.current;
131
- if (!video || !canvas || video.readyState < video.HAVE_METADATA || video.paused || video.ended) return;
132
 
133
  try {
134
- const ctx = canvas.getContext("2d");
135
  if (!ctx) return;
136
- const scale = 0.25; // Lower scale for performance
137
- canvas.width = video.videoWidth * scale;
138
- canvas.height = video.videoHeight * scale;
139
- if (canvas.width > 0 && canvas.height > 0) {
140
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
141
- const base64 = canvas.toDataURL("image/jpeg", 0.7); // Adjust quality
142
  const data = base64.slice(base64.indexOf(",") + 1);
143
  client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
144
  }
145
  } catch (error) {
146
- console.error("Error processing video frame:", error);
147
  }
148
  }
149
  }
150
-
151
- if (connected && isCamEnabled && activeLocalVideoStream) {
152
  frameTimeoutId = window.setTimeout(sendVideoFrame, 200); // Initial delay
153
  }
154
- return () => {
155
- clearTimeout(frameTimeoutId);
156
- };
157
- }, [connected, client, isCamEnabled, activeLocalVideoStream, videoRef, renderCanvasRef]);
158
-
159
 
160
- const stopAllVideo = useCallback(() => {
161
- if (activeLocalVideoStream) {
162
- activeLocalVideoStream.getTracks().forEach(track => track.stop());
163
- setActiveLocalVideoStream(null);
164
  }
165
- onVideoStreamChange(null); // Inform App.tsx
166
- }, [activeLocalVideoStream, onVideoStreamChange]);
 
167
 
 
 
 
 
168
 
169
- // Start/Stop Webcam
170
- const toggleWebcam = async () => {
171
  if (isSwitchingCamera) return;
172
 
173
- if (isCamEnabled) { // Turning off
174
- setIsCamEnabled(false);
175
- stopAllVideo();
176
- } else { // Turning on
177
- setIsCamEnabled(true);
 
 
178
  try {
179
- const mediaStream = await navigator.mediaDevices.getUserMedia({
180
  video: { facingMode: currentFacingMode },
181
- audio: false // Audio is handled by AudioRecorder
182
  });
183
- setActiveLocalVideoStream(mediaStream);
184
- onVideoStreamChange(mediaStream); // Inform App.tsx
 
185
  } catch (error) {
186
- console.error(`Error starting webcam with ${currentFacingMode}:`, error);
187
- setIsCamEnabled(false); // Revert state on error
188
- // Try fallback if OverconstrainedError (e.g., exact facingMode not available)
189
- if ((error as Error).name === 'OverconstrainedError' || (error as Error).name === 'NotAllowedError' || (error as Error).name === 'NotFoundError') {
 
 
 
190
  try {
191
- const fallbackMode = currentFacingMode === 'user' ? 'environment' : 'user';
192
- console.log(`Attempting fallback to ${fallbackMode} camera`);
193
- const fallbackStream = await navigator.mediaDevices.getUserMedia({
194
- video: { facingMode: fallbackMode },
195
- audio: false,
196
- });
197
- setActiveLocalVideoStream(fallbackStream);
198
  onVideoStreamChange(fallbackStream);
199
  setCurrentFacingMode(fallbackMode);
200
- setIsCamEnabled(true); // Set true on successful fallback
 
201
  } catch (fallbackError) {
202
- console.error('Webcam fallback also failed:', fallbackError);
203
- onVideoStreamChange(null);
204
  }
205
- } else {
206
- onVideoStreamChange(null);
207
  }
208
  }
209
  }
210
  };
211
 
212
- const rotateWebcam = async () => {
213
- if (isSwitchingCamera || !isCamEnabled || !activeLocalVideoStream) return;
 
214
 
215
  setIsSwitchingCamera(true);
216
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
217
-
 
218
  // Stop current tracks before requesting new ones
219
- activeLocalVideoStream.getTracks().forEach(track => track.stop());
220
 
221
  try {
222
- console.log(`Switching camera to: ${targetFacingMode}`);
223
  const newStream = await navigator.mediaDevices.getUserMedia({
224
  video: { facingMode: { exact: targetFacingMode } },
225
  audio: false
226
  });
227
- setActiveLocalVideoStream(newStream);
228
  onVideoStreamChange(newStream);
229
  setCurrentFacingMode(targetFacingMode);
 
230
  } catch (error: any) {
231
  console.error(`Error switching camera to ${targetFacingMode}: ${error.name}`, error);
232
- // Attempt to recover with the previous facing mode or any available camera
 
233
  try {
234
- console.log(`Fallback: trying previous mode ${currentFacingMode} or any video`);
235
  const recoveryStream = await navigator.mediaDevices.getUserMedia({
236
- video: true, // Try with non-specific facing mode
237
  audio: false
238
  });
239
- setActiveLocalVideoStream(recoveryStream);
240
  onVideoStreamChange(recoveryStream);
241
- // Try to determine the facing mode of the recovery stream if possible, or reset
242
- const settings = recoveryStream.getVideoTracks()[0]?.getSettings();
243
- if (settings?.facingMode) {
244
- setCurrentFacingMode(settings.facingMode as 'user' | 'environment');
245
- }
246
  } catch (recoveryError) {
247
- console.error('Camera recovery failed:', recoveryError);
248
- setIsCamEnabled(false); // Disable cam if all attempts fail
249
- stopAllVideo();
250
  }
251
  } finally {
252
  setIsSwitchingCamera(false);
253
  }
254
  };
255
-
256
- // Cleanup on unmount or when connection drops externally
257
  useEffect(() => {
 
 
 
 
 
 
 
 
 
 
258
  return () => {
259
- stopAllVideo();
 
260
  if (audioRecorder) audioRecorder.stop();
261
  };
262
- }, [stopAllVideo, audioRecorder]);
263
-
264
- useEffect(() => {
265
- if (!connected) { // If connection drops for any reason
266
- setIsMicEnabled(false); // Assume mic should be off
267
- // Optionally, also turn off camera if connection is lost
268
- // if (isCamEnabled) {
269
- // toggleWebcam(); // This will set isCamEnabled to false and stop video
270
- // }
271
- }
272
- }, [connected]);
273
 
274
 
275
  return (
@@ -277,54 +288,88 @@ function ControlTray({
277
  <canvas style={{ display: "none" }} ref={renderCanvasRef} />
278
  <div
279
  id="footer-controls"
280
- className={cn("footer-controls", {
281
- "layout-default": !isCamActiveApp, // Use App's view of cam state for layout
282
- "layout-with-small-logo": isCamActiveApp,
283
- })}
 
 
 
 
284
  >
285
- {/* Cam Button Wrapper (Left) */}
286
  <div id="cam-button-wrapper" className="relative flex justify-center">
 
287
  <button
288
  id="cam-button"
289
- className="control-button cam-button-color"
290
- onClick={toggleWebcam}
291
  disabled={isSwitchingCamera}
292
- title={isCamEnabled ? "Stop Camera" : "Start Camera"}
 
 
 
 
 
 
 
293
  >
294
- {isCamEnabled ? <StopCamIcon /> : <CameraIcon />}
295
  </button>
 
 
296
  <div
297
  id="switch-camera-button-container"
298
- className={cn("switch-camera-button-container", { visible: isCamEnabled && activeLocalVideoStream })}
 
 
 
 
 
 
 
 
299
  >
300
  <button
301
  id="switch-camera-button"
302
  aria-label="Switch Camera"
303
- className="switch-camera-button-content"
304
- onClick={rotateWebcam}
305
- disabled={isSwitchingCamera || !isCamEnabled || !activeLocalVideoStream}
 
 
 
 
 
 
306
  >
307
- <SwitchCameraIcon />
308
  </button>
309
  </div>
310
  </div>
311
 
312
- {/* Small Logo (Center when cam is active) */}
313
- {isCamActiveApp && ( // Use App's view of cam state for layout
314
- <div id="small-logo-container" className="small-logo-container">
315
  <SmallLogoDisplay isHumanActive={true} />
316
  </div>
317
  )}
318
 
319
- {/* Mic Button (Right) */}
320
  <div id="mic-button-wrapper" className="mic-button-wrapper relative flex justify-center">
321
- <button
322
  id="mic-button"
323
- className={cn("control-button mic-button-color", { active: isMicEnabled && connected })}
324
- onClick={() => setIsMicEnabled(!isMicEnabled)}
325
- title={isMicEnabled ? "Mute Microphone" : "Unmute Microphone"}
 
 
 
 
 
 
 
326
  >
327
- {(isMicEnabled && connected) ? <PauseIcon /> : <MicrophoneIcon />}
328
  </button>
329
  </div>
330
  </div>
 
5
  import cn from "classnames";
6
  import React, { memo, RefObject, useEffect, useRef, useState, useCallback } from "react";
7
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
8
+ // import { useScreenCapture } from "../../hooks/use-screen-capture"; // اگر نیاز به اشتراک صفحه نیست، کامنت کنید
9
  import { AudioRecorder } from "../../lib/audio-recorder";
10
+ // import { isIOS } from "../../lib/platform"; // اگر منطق خاص iOS در این کامپوننت نداریم، می‌توان حذف کرد
 
 
11
 
12
+ // --- SVG Icons (Ensure these are correctly defined as in your HTML or converted to React components) ---
13
+ // For brevity, I'll assume these are defined as React functional components similar to previous examples
14
+ // e.g., const PauseIcon = () => <svg>...</svg>;
15
+ // Make sure to import or define:
16
+ // PauseIcon, MicrophoneIcon, CameraIcon, StopCamIcon, SwitchCameraIcon, HumanIconSVGSmall
17
+
18
+ // آیکون‌ها باید اینجا تعریف یا وارد شوند
19
  const PauseIcon = () => <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>;
20
  const MicrophoneIcon = () => <svg width="69" height="68" viewBox="0 0 69 68" fill="none" xmlns="http://www.w3.org/2000/svg"><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>;
21
  const CameraIcon = () => <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>;
 
29
  if (!isHumanActive) return null;
30
  const size = 80; const iconSize = 35;
31
  const insetBase = { ping: 10, outer: 0, mid: 5, inner: 12, icon: 22.5 };
32
+ const bgColorBase = 'blue'; // Tailwind color prefix
33
 
34
  return (
35
  <div className="relative small-logo-container-inner" style={{ width: `${size}px`, height: `${size}px` }}>
36
+ {/* For Tailwind JIT detection. Use actual Tailwind classes on elements for styling. */}
37
+ {/* <div className="hidden bg-blue-200 bg-blue-300 bg-blue-400 dark:bg-blue-700 dark:bg-blue-600 dark:bg-blue-500"></div> */}
38
  <div className={`absolute rounded-full opacity-50 animate-ping bg-${bgColorBase}-200 dark:bg-${bgColorBase}-700`} style={{ inset: `${insetBase.ping}px` }}></div>
39
  <div className={`absolute rounded-full opacity-50 bg-${bgColorBase}-200 dark:bg-${bgColorBase}-700`} style={{ inset: `${insetBase.outer}px` }}></div>
40
  <div className={`absolute rounded-full opacity-50 bg-${bgColorBase}-300 dark:bg-${bgColorBase}-600`} style={{ inset: `${insetBase.mid}px` }}></div>
 
45
  </div>
46
  );
47
  };
48
+ // --- End SVG Icons ---
49
 
50
 
51
  export type ControlTrayProps = {
52
  videoRef: RefObject<HTMLVideoElement>;
53
  onVideoStreamChange: (stream: MediaStream | null) => void;
54
+ setIsMicActive: (isActive: boolean) => void;
55
+ setIsCamActiveExternal: (isActive: boolean) => void;
56
+ isCamActiveApp: boolean; // Camera state from App.tsx, used for layout
57
  };
58
 
59
  function ControlTray({
60
  videoRef,
61
  onVideoStreamChange,
62
+ setIsMicActive: setIsMicActiveApp, // Callback to inform App.tsx about mic state
63
+ setIsCamActiveExternal: setIsCamActiveAppExternal, // Callback to inform App.tsx about cam state
64
+ isCamActiveApp, // Camera state from App.tsx, used for layout decisions (e.g., small logo)
65
  }: ControlTrayProps) {
66
  const { client, connected, connect, disconnect } = useLiveAPIContext();
 
67
 
68
  const [audioRecorder] = useState(() => new AudioRecorder());
69
+ const [inVolume, setInVolume] = useState(0); // For mic pulse CSS animation
70
 
71
+ // Internal states for this component
72
+ const [micActuallyEnabled, setMicActuallyEnabled] = useState(false); // Is mic hardware/permission enabled?
73
+ const [camActuallyEnabled, setCamActuallyEnabled] = useState(false); // Is cam hardware/permission enabled?
74
 
75
+ const [localStream, setLocalStream] = useState<MediaStream | null>(null);
76
  const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>('user');
77
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
78
 
79
+ const renderCanvasRef = useRef<HTMLCanvasElement>(null); // For sending video frames
80
 
81
+ // Effect to inform App.tsx about the actual state of mic/cam
82
  useEffect(() => {
83
+ setIsMicActiveApp(micActuallyEnabled && connected);
84
+ }, [micActuallyEnabled, connected, setIsMicActiveApp]);
85
 
86
  useEffect(() => {
87
+ setIsCamActiveAppExternal(camActuallyEnabled && !!localStream);
88
+ }, [camActuallyEnabled, localStream, setIsCamActiveAppExternal]);
 
89
 
90
+ // Auto-connect/disconnect based on whether mic or cam is requested to be active
91
  useEffect(() => {
92
+ const shouldBeConnected = micActuallyEnabled || camActuallyEnabled;
93
  if (shouldBeConnected && !connected) {
94
+ console.log("ControlTray: Mic or Cam active, attempting to connect...");
95
+ connect().catch(err => console.error("ControlTray: Connection failed", err));
96
  } else if (!shouldBeConnected && connected) {
97
+ console.log("ControlTray: Mic and Cam inactive, attempting to disconnect...");
98
+ disconnect().catch(err => console.error("ControlTray: Disconnection failed", err));
99
  }
100
+ }, [micActuallyEnabled, camActuallyEnabled, connected, connect, disconnect]);
101
 
102
+ // Audio Recorder Logic
103
  useEffect(() => {
104
  const onData = (base64: string) => {
105
+ if (client && connected && micActuallyEnabled) {
106
  client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
107
  }
108
  };
109
+ if (connected && micActuallyEnabled && audioRecorder) {
110
  audioRecorder.on("data", onData).on("volume", setInVolume).start();
111
+ console.log("Audio recorder started");
112
  } else if (audioRecorder) {
113
  audioRecorder.stop();
114
+ setInVolume(0);
115
+ console.log("Audio recorder stopped");
116
  }
117
  return () => {
118
  if (audioRecorder) {
119
  audioRecorder.off("data", onData).off("volume", setInVolume).stop();
120
  }
121
  };
122
+ }, [connected, client, micActuallyEnabled, audioRecorder]);
123
 
124
+ // Update CSS --volume for mic pulse animation
125
  useEffect(() => {
126
  document.documentElement.style.setProperty(
127
  "--volume",
128
+ // The pulse visibility should be controlled by micActuallyEnabled && connected
129
+ // The value of --volume can be based on inVolume
130
+ micActuallyEnabled && connected ? `${Math.max(5, Math.min(inVolume * 200, 15))}px` : "0px"
131
  );
132
+ }, [inVolume, micActuallyEnabled, connected]);
 
133
 
134
+ // Video Frame Sending Logic
135
  useEffect(() => {
136
  let frameTimeoutId = -1;
137
  function sendVideoFrame() {
138
+ if (connected && camActuallyEnabled && localStream && client && videoRef.current && renderCanvasRef.current) {
139
+ frameTimeoutId = window.setTimeout(sendVideoFrame, 1000 / 2); // ~2 FPS
140
+ const videoEl = videoRef.current;
141
+ const canvasEl = renderCanvasRef.current;
142
+ if (videoEl.readyState < videoEl.HAVE_METADATA || videoEl.paused || videoEl.ended) return;
143
 
144
  try {
145
+ const ctx = canvasEl.getContext("2d");
146
  if (!ctx) return;
147
+ const scale = 0.25;
148
+ canvasEl.width = videoEl.videoWidth * scale;
149
+ canvasEl.height = videoEl.videoHeight * scale;
150
+ if (canvasEl.width > 0 && canvasEl.height > 0) {
151
+ ctx.drawImage(videoEl, 0, 0, canvasEl.width, canvasEl.height);
152
+ const base64 = canvasEl.toDataURL("image/jpeg", 0.7);
153
  const data = base64.slice(base64.indexOf(",") + 1);
154
  client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
155
  }
156
  } catch (error) {
157
+ console.error("Error processing/sending video frame:", error);
158
  }
159
  }
160
  }
161
+ if (connected && camActuallyEnabled && localStream) {
 
162
  frameTimeoutId = window.setTimeout(sendVideoFrame, 200); // Initial delay
163
  }
164
+ return () => { clearTimeout(frameTimeoutId); };
165
+ }, [connected, client, camActuallyEnabled, localStream, videoRef, renderCanvasRef]);
 
 
 
166
 
167
+ const stopAllLocalVideo = useCallback(() => {
168
+ if (localStream) {
169
+ localStream.getTracks().forEach(track => track.stop());
170
+ setLocalStream(null);
171
  }
172
+ if (videoRef.current) videoRef.current.srcObject = null;
173
+ onVideoStreamChange(null); // Inform App.tsx the stream is gone
174
+ }, [localStream, onVideoStreamChange, videoRef]);
175
 
176
+ // Toggle Mic Button
177
+ const handleMicToggle = () => {
178
+ setMicActuallyEnabled(prev => !prev);
179
+ };
180
 
181
+ // Toggle Cam Button (Start/Stop Webcam)
182
+ const handleCamToggle = async () => {
183
  if (isSwitchingCamera) return;
184
 
185
+ if (camActuallyEnabled) { // Turning OFF
186
+ console.log("Turning camera OFF");
187
+ setCamActuallyEnabled(false);
188
+ stopAllLocalVideo();
189
+ } else { // Turning ON
190
+ console.log("Turning camera ON, currentFacingMode:", currentFacingMode);
191
+ setCamActuallyEnabled(true); // Optimistically set to true
192
  try {
193
+ const stream = await navigator.mediaDevices.getUserMedia({
194
  video: { facingMode: currentFacingMode },
195
+ audio: false // Audio is separate
196
  });
197
+ setLocalStream(stream);
198
+ onVideoStreamChange(stream); // Inform App.tsx
199
+ console.log("Camera stream acquired:", stream.id);
200
  } catch (error) {
201
+ console.error(`Error starting webcam (${currentFacingMode}):`, error);
202
+ setCamActuallyEnabled(false); // Revert on error
203
+ stopAllLocalVideo(); // Ensure cleanup
204
+ // Optionally, try fallback if specific facing mode failed
205
+ if ((error as Error).name === 'OverconstrainedError' || (error as Error).name === 'NotFoundError') {
206
+ const fallbackMode = currentFacingMode === 'user' ? 'environment' : 'user';
207
+ console.log(`Attempting fallback to ${fallbackMode} camera`);
208
  try {
209
+ const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: fallbackMode }, audio: false });
210
+ setLocalStream(fallbackStream);
 
 
 
 
 
211
  onVideoStreamChange(fallbackStream);
212
  setCurrentFacingMode(fallbackMode);
213
+ setCamActuallyEnabled(true); // Success with fallback
214
+ console.log("Camera fallback stream acquired:", fallbackStream.id);
215
  } catch (fallbackError) {
216
+ console.error("Webcam fallback also failed:", fallbackError);
 
217
  }
 
 
218
  }
219
  }
220
  }
221
  };
222
 
223
+ // Rotate Webcam
224
+ const handleRotateWebcam = async () => {
225
+ if (isSwitchingCamera || !camActuallyEnabled || !localStream) return;
226
 
227
  setIsSwitchingCamera(true);
228
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
229
+ console.log(`Attempting to switch camera to: ${targetFacingMode}`);
230
+
231
  // Stop current tracks before requesting new ones
232
+ localStream.getTracks().forEach(track => track.stop());
233
 
234
  try {
 
235
  const newStream = await navigator.mediaDevices.getUserMedia({
236
  video: { facingMode: { exact: targetFacingMode } },
237
  audio: false
238
  });
239
+ setLocalStream(newStream);
240
  onVideoStreamChange(newStream);
241
  setCurrentFacingMode(targetFacingMode);
242
+ console.log(`Camera switched to ${targetFacingMode}. New stream:`, newStream.id);
243
  } catch (error: any) {
244
  console.error(`Error switching camera to ${targetFacingMode}: ${error.name}`, error);
245
+ // Attempt to recover with the previous (now current) facing mode or any available camera
246
+ console.log(`Fallback: trying previous mode ${currentFacingMode} or any video again`);
247
  try {
 
248
  const recoveryStream = await navigator.mediaDevices.getUserMedia({
249
+ video: { facingMode: currentFacingMode }, // Try previous again
250
  audio: false
251
  });
252
+ setLocalStream(recoveryStream);
253
  onVideoStreamChange(recoveryStream);
254
+ // currentFacingMode is already set to the one we tried to recover
255
+ console.log("Camera recovery stream acquired:", recoveryStream.id);
 
 
 
256
  } catch (recoveryError) {
257
+ console.error('Camera recovery after switch failed:', recoveryError);
258
+ setCamActuallyEnabled(false); // Disable cam if all attempts fail
259
+ stopAllLocalVideo();
260
  }
261
  } finally {
262
  setIsSwitchingCamera(false);
263
  }
264
  };
265
+
266
+ // Cleanup on unmount or if connection drops externally (e.g., server disconnects)
267
  useEffect(() => {
268
+ const isComponentMounted = true;
269
+ if (!connected && isComponentMounted) {
270
+ // If connection drops externally, reset mic/cam states
271
+ // This might be too aggressive if there are retries, adjust as needed
272
+ if (micActuallyEnabled) setMicActuallyEnabled(false);
273
+ if (camActuallyEnabled) {
274
+ setCamActuallyEnabled(false);
275
+ stopAllLocalVideo();
276
+ }
277
+ }
278
  return () => {
279
+ // isComponentMounted = false; // This pattern is for classes, not hooks directly
280
+ stopAllLocalVideo();
281
  if (audioRecorder) audioRecorder.stop();
282
  };
283
+ }, [connected, stopAllLocalVideo, audioRecorder, micActuallyEnabled, camActuallyEnabled]); // Added mic/cam states to dependencies
 
 
 
 
 
 
 
 
 
 
284
 
285
 
286
  return (
 
288
  <canvas style={{ display: "none" }} ref={renderCanvasRef} />
289
  <div
290
  id="footer-controls"
291
+ className={cn(
292
+ "footer-controls", // from App.scss or your global styles
293
+ // Tailwind classes for layout based on HTML structure:
294
+ "w-full flex gap-4 absolute bottom-0 px-6 sm:px-12 py-8 items-center",
295
+ isCamActiveApp // Use state from App.tsx for layout: shows small logo or not
296
+ ? "justify-around layout-with-small-logo" // Corresponds to layout-with-small-logo
297
+ : "justify-between layout-default" // Corresponds to layout-default
298
+ )}
299
  >
300
+ {/* Cam Button Wrapper (Now on the Left) */}
301
  <div id="cam-button-wrapper" className="relative flex justify-center">
302
+ {/* Main Camera Toggle Button */}
303
  <button
304
  id="cam-button"
305
+ onClick={handleCamToggle}
 
306
  disabled={isSwitchingCamera}
307
+ title={camActuallyEnabled ? "Stop Camera" : "Start Camera"}
308
+ // Tailwind classes for the button itself
309
+ className={cn(
310
+ "control-button cam-button-color", // Base classes from App.scss or your CSS
311
+ "h-20 w-20 rounded-full p-0 flex items-center justify-center border",
312
+ "shadow-md hover:scale-105 hover:shadow-lg transition-transform transition-shadow ease-out",
313
+ "dark:border-neutral-700 border-neutral-300" // Example border colors
314
+ )}
315
  >
316
+ {camActuallyEnabled ? <StopCamIcon /> : <CameraIcon />}
317
  </button>
318
+
319
+ {/* Switch Camera Button (Appears above cam button when cam is active) */}
320
  <div
321
  id="switch-camera-button-container"
322
+ // Tailwind classes for positioning and visibility
323
+ className={cn(
324
+ "switch-camera-button-container", // Base class for CSS transitions from App.scss
325
+ "absolute bottom-[calc(100%+0.65rem)] left-1/2 z-[5] transform -translate-x-1/2",
326
+ "transition-opacity duration-300 ease-[cubic-bezier(0.68,-0.55,0.27,1.55)]",
327
+ "transform-origin-center-bottom",
328
+ (camActuallyEnabled && localStream) ? "opacity-100 scale-100 pointer-events-auto translate-y-0 visible"
329
+ : "opacity-0 scale-75 pointer-events-none translate-y-[15px]"
330
+ )}
331
  >
332
  <button
333
  id="switch-camera-button"
334
  aria-label="Switch Camera"
335
+ onClick={handleRotateWebcam}
336
+ disabled={isSwitchingCamera || !camActuallyEnabled || !localStream}
337
+ // Tailwind classes for the switch camera button content
338
+ className={cn(
339
+ "switch-camera-button-content", // Base class from App.scss
340
+ "w-12 h-12 bg-background dark:bg-neutral-800 border dark:border-neutral-700 border-neutral-300",
341
+ "rounded-full flex items-center justify-center shadow-lg hover:scale-110 hover:rotate-[-6deg]",
342
+ "active:scale-105 active:rotate-0 transition-transform transform-origin-center"
343
+ )}
344
  >
345
+ <SwitchCameraIcon /> {/* SVG should have stroke set by CSS (var --foreground) */}
346
  </button>
347
  </div>
348
  </div>
349
 
350
+ {/* Small Logo Container (middle) */}
351
+ {isCamActiveApp && ( // Displayed when cam is active (based on App.tsx's perspective)
352
+ <div id="small-logo-container" className="flex items-center justify-center">
353
  <SmallLogoDisplay isHumanActive={true} />
354
  </div>
355
  )}
356
 
357
+ {/* Mic Button (Now on the Right) */}
358
  <div id="mic-button-wrapper" className="mic-button-wrapper relative flex justify-center">
359
+ <button
360
  id="mic-button"
361
+ onClick={handleMicToggle}
362
+ title={micActuallyEnabled ? "Mute Microphone" : "Unmute Microphone"}
363
+ // Tailwind classes for the button itself
364
+ className={cn(
365
+ "control-button mic-button-color", // Base classes from App.scss
366
+ "h-20 w-20 rounded-full p-0 flex items-center justify-center border",
367
+ "shadow-md hover:scale-105 hover:shadow-lg transition-transform transition-shadow ease-out",
368
+ "dark:border-neutral-700 border-neutral-300", // Example border colors
369
+ { 'active': micActuallyEnabled && connected } // For CSS pulse via .mic-button-wrapper .active:before
370
+ )}
371
  >
372
+ {(micActuallyEnabled && connected) ? <PauseIcon /> : <MicrophoneIcon />}
373
  </button>
374
  </div>
375
  </div>