Spaces:
Running
Running
File size: 15,203 Bytes
7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 f40f415 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 7f2a14a 688a2e9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
/**
* Copyright 2024 Google LLC
* ... (لایسنس و توضیحات دیگر مثل قبل) ...
*/
import cn from "classnames";
import { memo, ReactNode, RefObject, useEffect, useRef, useState } from "react";
import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
import { UseMediaStreamResult } from "../../hooks/use-media-stream-mux";
import { useScreenCapture } from "../../hooks/use-screen-capture";
import { useWebcam } from "../../hooks/use-webcam";
import { AudioRecorder } from "../../lib/audio-recorder";
import { isIOS } from "../../lib/platform";
import AudioPulse from "../audio-pulse/AudioPulse";
import "./control-tray.scss";
export type ControlTrayProps = {
videoRef: RefObject<HTMLVideoElement>;
children?: ReactNode;
supportsVideo: boolean;
onVideoStreamChange?: (stream: MediaStream | null) => void;
};
type MediaStreamButtonProps = {
isStreaming: boolean;
onIcon: string;
offIcon: string;
start: () => Promise<any>;
stop: () => any;
disabled?: boolean;
};
const MediaStreamButton = memo(
({ isStreaming, onIcon, offIcon, start, stop, disabled }: MediaStreamButtonProps) =>
isStreaming ? (
<button className="action-button" onClick={stop} title={`Stop ${offIcon}`} disabled={disabled}>
<span className="material-symbols-outlined">{onIcon}</span>
</button>
) : (
<button className="action-button" onClick={start} title={`Start ${offIcon}`} disabled={disabled}>
<span className="material-symbols-outlined">{offIcon}</span>
</button>
),
);
function ControlTray({
videoRef,
children,
onVideoStreamChange = () => {},
supportsVideo,
}: ControlTrayProps) {
const webcam = useWebcam();
const screenCapture = useScreenCapture();
const [activeVideoStream, setActiveVideoStream] = useState<MediaStream | null>(null);
const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment' | null>(null);
const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
const [isLikelyDesktop, setIsLikelyDesktop] = useState(false); // <-- State برای تشخیص دسکتاپ
const [inVolume, setInVolume] = useState(0);
const [audioRecorder] = useState(() => new AudioRecorder());
const [muted, setMuted] = useState(false);
const renderCanvasRef = useRef<HTMLCanvasElement>(null);
const connectButtonRef = useRef<HTMLButtonElement>(null);
const [simulatedVolume, setSimulatedVolume] = useState(0);
const isIOSDevice = isIOS();
const { client, connected, connect, disconnect, volume } = useLiveAPIContext();
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
// --- useEffect ها ---
// بررسی نوع دستگاه (دسکتاپ یا موبایل/تبلت) در زمان Mount
useEffect(() => {
// navigator.maxTouchPoints > 0 معمولا نشاندهنده دستگاه لمسی است
const desktopCheck = typeof navigator !== 'undefined' && navigator.maxTouchPoints <= 0;
setIsLikelyDesktop(desktopCheck);
console.log(`Device check: Likely Desktop? ${desktopCheck} (maxTouchPoints: ${navigator.maxTouchPoints})`);
}, []); // فقط یک بار در زمان Mount اجرا شود
// Focus effect
useEffect(() => {
if (!connected && connectButtonRef.current) {
connectButtonRef.current.focus();
}
}, [connected]);
// iOS volume simulation
useEffect(() => {
let interval: number | undefined;
if (isIOSDevice && connected && !muted) {
interval = window.setInterval(() => {
const pulse = (Math.sin(Date.now() / 500) + 1) / 2;
setSimulatedVolume(0.02 + pulse * 0.03);
}, 50);
}
return () => {
if (interval) clearInterval(interval);
};
}, [connected, muted, isIOSDevice]);
// CSS volume update
useEffect(() => {
document.documentElement.style.setProperty(
"--volume",
`${Math.max(5, Math.min((isIOSDevice ? simulatedVolume : inVolume) * 200, 8))}px`,
);
}, [inVolume, simulatedVolume, isIOSDevice]);
// Audio recording
useEffect(() => {
const onData = (base64: string) => {
if (client && connected) {
client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
}
};
if (connected && !muted && audioRecorder) {
audioRecorder.on("data", onData).on("volume", setInVolume).start();
} else if (audioRecorder) {
audioRecorder.stop();
}
return () => {
if (audioRecorder) {
audioRecorder.off("data", onData).off("volume", setInVolume).stop();
}
};
}, [connected, client, muted, audioRecorder]);
// Stop video on disconnect
useEffect(() => {
if (!connected && activeVideoStream) {
console.log('🔌 Disconnected, stopping video stream.');
activeVideoStream.getTracks().forEach(track => track.stop());
setActiveVideoStream(null);
onVideoStreamChange(null);
setCurrentFacingMode(null);
setIsSwitchingCamera(false);
webcam.stop();
screenCapture.stop();
}
}, [connected, activeVideoStream, onVideoStreamChange, webcam, screenCapture]);
// Video frame sending
useEffect(() => {
let timeoutId = -1;
function sendVideoFrame() {
if (connected && activeVideoStream) {
timeoutId = window.setTimeout(sendVideoFrame, 1000 / 0.5);
}
const video = videoRef.current; const canvas = renderCanvasRef.current;
if (!video || !canvas || video.readyState < video.HAVE_METADATA || video.paused || video.ended || !client) return;
try {
const ctx = canvas.getContext("2d"); if (!ctx) return;
const scale = 0.25; canvas.width = video.videoWidth * scale; canvas.height = video.videoHeight * scale;
if (canvas.width > 0 && canvas.height > 0) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const base64 = canvas.toDataURL("image/jpeg", 0.8);
const data = base64.slice(base64.indexOf(",") + 1);
client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
}
} catch (error) { console.error("❌ Error processing video frame:", error); }
}
if (connected && activeVideoStream && videoRef.current) { setTimeout(sendVideoFrame, 200); }
return () => { clearTimeout(timeoutId); };
}, [connected, activeVideoStream, client, videoRef]);
// Assign stream to video element
useEffect(() => {
if (videoRef.current) {
if (videoRef.current.srcObject !== activeVideoStream) {
videoRef.current.srcObject = activeVideoStream;
if (activeVideoStream) { videoRef.current.play().catch(e => console.warn("Video play failed:", e)); }
}
}
}, [activeVideoStream, videoRef]);
// --- پایان useEffect ها ---
// Function to stop all video streams
const stopAllVideoStreams = () => {
console.log('⏹️ Stopping all video streams...');
if (activeVideoStream) {
activeVideoStream.getTracks().forEach(track => track.stop());
setActiveVideoStream(null);
onVideoStreamChange(null);
}
webcam.stop(); screenCapture.stop(); setCurrentFacingMode(null); setIsSwitchingCamera(false);
};
// Handler for starting/stopping webcam or screen share
const changeStreams = (streamType: 'webcam' | 'screen' | 'none') => async () => {
if (isSwitchingCamera) return;
// Only allow starting screen share if it's likely a desktop
if (streamType === 'screen' && !isLikelyDesktop) {
console.warn("Screen share requested on non-desktop device, ignoring.");
return;
}
stopAllVideoStreams();
if (streamType === 'webcam') {
const initialFacingMode = 'user'; console.log(`🚀 Starting webcam with initial facingMode: ${initialFacingMode}`);
try {
const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: initialFacingMode }, audio: false });
setActiveVideoStream(mediaStream); onVideoStreamChange(mediaStream); setCurrentFacingMode(initialFacingMode);
} catch (error) {
console.error(`❌ Error starting webcam with ${initialFacingMode}:`, error);
try { // Fallback
const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
setActiveVideoStream(fallbackStream); onVideoStreamChange(fallbackStream); setCurrentFacingMode('environment');
} catch (fallbackError) { console.error('❌ Error starting webcam fallback:', fallbackError); setActiveVideoStream(null); onVideoStreamChange(null); setCurrentFacingMode(null); }
}
} else if (streamType === 'screen' && isLikelyDesktop) { // Double check desktop condition
console.log('🚀 Starting screen capture');
try {
const mediaStream = await screenCapture.start();
setActiveVideoStream(mediaStream); onVideoStreamChange(mediaStream); setCurrentFacingMode(null);
} catch (error) { console.error('❌ Error starting screen capture:', error); setActiveVideoStream(null); onVideoStreamChange(null); setCurrentFacingMode(null); }
} else { console.log('ℹ️ Video stream turned off or invalid request.'); }
};
// Handler for rotating webcam
const rotateWebcam = async () => {
if (isSwitchingCamera || !activeVideoStream || currentFacingMode === null) return;
const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
console.log(`🔄 Rotating webcam... Target: ${targetFacingMode}`);
setIsSwitchingCamera(true);
activeVideoStream.getTracks().forEach(track => track.stop()); // Stop tracks only
try {
const newStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { exact: targetFacingMode } }, audio: false });
if (videoRef.current) { videoRef.current.srcObject = newStream; videoRef.current.play().catch(e => console.warn("Play fail switch:", e)); }
setActiveVideoStream(newStream); onVideoStreamChange(newStream); setCurrentFacingMode(targetFacingMode);
} catch (error: any) {
console.error(`❌ Error switching camera:`, error.name);
let recoveredStream: MediaStream | null = null; // Fallback logic...
if (error.name === 'OverconstrainedError' || error.name === 'ConstraintNotSatisfiedError') {
try { recoveredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: targetFacingMode }, audio: false }); setCurrentFacingMode(targetFacingMode); } catch (retryError: any) { console.error(`Retry fail:`, retryError.name); }
}
if (!recoveredStream) { try { recoveredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { exact: currentFacingMode } }, audio: false }); } catch (restoreError) { console.error(`Restore fail:`, restoreError); } }
if (recoveredStream) { if (videoRef.current) { videoRef.current.srcObject = recoveredStream; videoRef.current.play().catch(e => console.warn("Play fail recovery:", e)); } setActiveVideoStream(recoveredStream); onVideoStreamChange(recoveredStream); }
else { if (videoRef.current) videoRef.current.srcObject = null; setActiveVideoStream(null); onVideoStreamChange(null); setCurrentFacingMode(null); }
} finally {
setIsSwitchingCamera(false);
}
};
// Determine stable streaming states
const isWebcamStableStreaming = activeVideoStream !== null && currentFacingMode !== null;
const isScreenCaptureStreaming = screenCapture.isStreaming && activeVideoStream !== null && currentFacingMode === null;
// Determine if the webcam button should appear active
const showWebcamAsActive = isWebcamStableStreaming || (isSwitchingCamera && currentFacingMode !== null);
// **** Condition to show Screen Share Button ****
const showScreenShareButton = supportsVideo && !isIOSDevice && isLikelyDesktop;
return (
<section className="control-tray">
<canvas style={{ display: "none" }} ref={renderCanvasRef} />
<nav className={cn("actions-nav", { disabled: !connected })}>
{/* Mic Button */}
<button
className={cn("action-button mic-button")}
onClick={() => setMuted(!muted)}
disabled={!connected || isSwitchingCamera}
title={muted ? "Unmute Microphone" : "Mute Microphone"}
>
<span className="material-symbols-outlined filled">{muted ? "mic_off" : "mic"}</span>
</button>
{/* Volume Indicator */}
<div className="action-button no-action outlined">
<AudioPulse volume={volume} active={connected && !muted} hover={false} />
</div>
{/* Video Controls */}
{supportsVideo && (
<>
{/* Screen Share Button (Show only on non-iOS Desktop-like devices) */}
{showScreenShareButton && ( // <-- شرط جدید اینجا اعمال شده
<MediaStreamButton
isStreaming={isScreenCaptureStreaming}
start={changeStreams('screen')}
stop={changeStreams('none')}
onIcon="cancel_presentation"
offIcon="present_to_all"
// Disable screen share button also if webcam is active or switching? Your choice.
// disabled={!connected || isSwitchingCamera || showWebcamAsActive}
disabled={!connected || isSwitchingCamera } // Kept simpler for now
/>
)}
{/* Switch Camera Button */}
{ (isWebcamStableStreaming || isSwitchingCamera) && (
<button
className="action-button"
onClick={rotateWebcam}
title="Switch camera"
disabled={!connected || isSwitchingCamera}
>
<span className="material-symbols-outlined">switch_camera</span>
</button>
)}
{/* Webcam On/Off Button */}
<MediaStreamButton
isStreaming={showWebcamAsActive}
start={changeStreams('webcam')}
stop={changeStreams('none')}
onIcon="videocam_off"
offIcon="videocam"
disabled={!connected || isSwitchingCamera}
/>
</>
)}
{children}
</nav>
{/* Connection Controls */}
<div className={cn("connection-container", { connected })}>
<div className="connection-button-container">
<button
ref={connectButtonRef}
className={cn("action-button connect-toggle", { connected })}
onClick={async () => {
if (isSwitchingCamera) return;
try { if (connected) { await disconnect(); } else { await connect(); } }
catch (err) { console.error('❌ Connection/Disconnection error:', err); }
}}
disabled={isSwitchingCamera}
title={connected ? "Disconnect Stream" : "Connect Stream"}
>
<span className="material-symbols-outlined filled">{connected ? "pause" : "play_arrow"}</span>
</button>
</div>
<span className="text-indicator">{connected ? "Streaming" : "Paused"}</span>
</div>
</section>
);
}
export default memo(ControlTray); |