File size: 14,813 Bytes
7f2a14a
848947d
 
 
7f2a14a
7da7877
7f2a14a
7da7877
 
 
7f2a14a
7da7877
 
 
7f2a14a
848947d
7da7877
 
 
 
 
848947d
7f2a14a
7da7877
 
 
7f2a14a
7da7877
 
 
 
 
7f2a14a
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848947d
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848947d
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152abf8
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152abf8
7da7877
848947d
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
7f2a14a
7da7877
 
 
 
 
 
 
 
 
7f2a14a
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152abf8
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848947d
7da7877
 
 
 
 
 
 
848947d
7da7877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
Copyright 2024 Google LLC
... (لایسنس و توضیحات دیگر مثل قبل) ...
*/
import cn from "classnames";
import { memo, ReactNode, RefObject, useEffect, useRef, useState, useCallback } from "react"; // useCallback added
import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
// import { UseMediaStreamResult } from "../../hooks/use-media-stream-mux"; // Seem unused directly here
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; // Might not be used if UI is hidden
  supportsVideo: boolean;
  onVideoStreamChange?: (stream: MediaStream | null) => void;
  isUiHidden?: boolean; // New prop to hide default UI
};

// MediaStreamButton might not be needed if App.tsx handles buttons
// const MediaStreamButton = memo(...);

function ControlTray({
  videoRef,
  children,
  onVideoStreamChange = () => {},
  supportsVideo,
  isUiHidden = false, // Default to false
}: ControlTrayProps) {
  const webcam = useWebcam();
  const screenCapture = useScreenCapture();
  const [activeVideoStream, setActiveVideoStream] = useState<MediaStream | null>(null);
  const [currentFacingModeInternal, setCurrentFacingModeInternal] = useState<'user' | 'environment' | null>(null);
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
  const [isLikelyDesktop, setIsLikelyDesktop] = useState(false);
  const [inVolume, setInVolume] = useState(0);
  const [audioRecorder] = useState(() => new AudioRecorder());
  // const [muted, setMuted] = useState(false); // Muted state will be controlled by LiveAPIContext
  const renderCanvasRef = useRef<HTMLCanvasElement>(null);
  const connectButtonRef = useRef<HTMLButtonElement>(null); // May not be needed if App.tsx handles connect button
  const [simulatedVolume, setSimulatedVolume] = useState(0);
  const isIOSDevice = isIOS();
  const { client, connected, connect, disconnect, volume, setMuted: contextSetMuted, setSystemInstruction, updateLiveConfig, currentFacingMode, setCurrentFacingMode, rotateWebcam: contextRotateWebcam, changeStreams: contextChangeStreams } = useLiveAPIContext();
  // const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

  // Expose rotateWebcam and changeStreams to context if they are not already there
  useEffect(() => {
    if (setCurrentFacingMode) setCurrentFacingMode(currentFacingModeInternal);
  }, [currentFacingModeInternal, setCurrentFacingMode]);
  
  const changeStreamsInternal = useCallback(async (streamType: 'webcam' | 'screen' | 'none') => {
    if (isSwitchingCamera) return;
    if (streamType === 'screen' && !isLikelyDesktop) {
      console.warn("Screen share requested on non-desktop device, ignoring.");
      return;
    }

    // Stop existing streams first
    if (activeVideoStream) {
        activeVideoStream.getTracks().forEach(track => track.stop());
    }
    webcam.stop();
    screenCapture.stop();
    setActiveVideoStream(null);
    onVideoStreamChange(null);
    setCurrentFacingModeInternal(null);
    
    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);
        setCurrentFacingModeInternal(initialFacingMode);
      } catch (error) {
        console.error(`❌ Error starting webcam with ${initialFacingMode}:`, error);
        try {
          const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
          setActiveVideoStream(fallbackStream);
          onVideoStreamChange(fallbackStream);
          setCurrentFacingModeInternal('environment');
        } catch (fallbackError) {
          console.error('❌ Error starting webcam fallback:', fallbackError);
          // No stream set
        }
      }
    } else if (streamType === 'screen' && isLikelyDesktop) {
      console.log('🚀 Starting screen capture');
      try {
        const mediaStream = await screenCapture.start();
        setActiveVideoStream(mediaStream);
        onVideoStreamChange(mediaStream);
        setCurrentFacingModeInternal(null); // Screen share doesn't have a facing mode
      } catch (error) {
        console.error('❌ Error starting screen capture:', error);
      }
    } else {
      console.log('ℹ️ Video stream turned off or invalid request.');
    }
  }, [isSwitchingCamera, isLikelyDesktop, webcam, screenCapture, onVideoStreamChange, activeVideoStream]);

  const rotateWebcamInternal = useCallback(async () => {
    if (isSwitchingCamera || !activeVideoStream || currentFacingModeInternal === null) return;
    const targetFacingMode = currentFacingModeInternal === 'user' ? 'environment' : 'user';
    console.log(`🔄 Rotating webcam... Target: ${targetFacingMode}`);
    setIsSwitchingCamera(true);
    
    // Stop only the tracks of the active video stream
    activeVideoStream.getTracks().forEach(track => track.stop());

    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);
      setCurrentFacingModeInternal(targetFacingMode);
    } catch (error: any) {
      console.error(`❌ Error switching camera:`, error.name);
      // Fallback logic...
      let recoveredStream: MediaStream | null = null;
      if (error.name === 'OverconstrainedError' || error.name === 'ConstraintNotSatisfiedError') {
        try {
          recoveredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: targetFacingMode }, audio: false }); // Try without exact
          setCurrentFacingModeInternal(targetFacingMode);
        } catch (retryError: any) { console.error(`Retry fail:`, retryError.name); }
      }
      if (!recoveredStream) { // Try to restore original
        try {
          recoveredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { exact: currentFacingModeInternal } }, 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 { // Total failure
        if (videoRef.current) videoRef.current.srcObject = null;
        setActiveVideoStream(null);
        onVideoStreamChange(null);
        setCurrentFacingModeInternal(null);
      }
    } finally {
      setIsSwitchingCamera(false);
    }
  }, [isSwitchingCamera, activeVideoStream, currentFacingModeInternal, videoRef, onVideoStreamChange]);


  // Provide these functions to the context if they don't exist or need overriding
  useEffect(() => {
    if (updateLiveConfig && !contextChangeStreams) {
        updateLiveConfig({ changeStreams: changeStreamsInternal });
    }
    if (updateLiveConfig && !contextRotateWebcam) {
        updateLiveConfig({ rotateWebcam: rotateWebcamInternal });
    }
  }, [updateLiveConfig, changeStreamsInternal, contextChangeStreams, rotateWebcamInternal, contextRotateWebcam]);


  // --- useEffect ها ---
  useEffect(() => {
    const desktopCheck = typeof navigator !== 'undefined' && navigator.maxTouchPoints <= 0;
    setIsLikelyDesktop(desktopCheck);
  }, []);

  // iOS volume simulation
  useEffect(() => {
    let interval: number | undefined;
    if (isIOSDevice && connected && !client?.isMuted) { // Assuming client.isMuted reflects actual mute state
      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, client?.isMuted, isIOSDevice]);

  // CSS volume update for mic pulse
  useEffect(() => {
    document.documentElement.style.setProperty(
      "--volume",
      `${Math.max(5, Math.min((isIOSDevice ? simulatedVolume : inVolume) * 200, 12))}px`, // Increased max pulse for visibility
    );
  }, [inVolume, simulatedVolume, isIOSDevice]);

  // Audio recording
  useEffect(() => {
    const onData = (base64: string) => {
      if (client && connected) {
        client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
      }
    };
    if (connected && !client?.isMuted && audioRecorder) { // Use client.isMuted
      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, audioRecorder, client?.isMuted]); // Dependency on client.isMuted

  // Stop video on disconnect
  useEffect(() => {
    if (!connected && activeVideoStream) {
      console.log('🔌 Disconnected, stopping video stream.');
      activeVideoStream.getTracks().forEach(track => track.stop());
      setActiveVideoStream(null);
      onVideoStreamChange(null);
      setCurrentFacingModeInternal(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); // Target 0.5 FPS for video
      }
      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) {
          // Flip image if user-facing camera and it's not already flipped by CSS
          // The new HTML uses scale-x-[-1] so browser handles mirroring.
          // If browser doesn't mirror stream itself, and you need to send mirrored frames:
          // if (currentFacingModeInternal === 'user') {
          //   ctx.scale(-1, 1);
          //   ctx.drawImage(video, -canvas.width, 0, canvas.width, canvas.height);
          // } else {
          //   ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          // }
          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, currentFacingModeInternal]); // Added currentFacingModeInternal

  // 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]);
  
  // If UI is hidden, render minimal or nothing
  if (isUiHidden) {
    return (
      <>
        <canvas style={{ display: "none" }} ref={renderCanvasRef} />
        {/* AudioPulse might still be useful for the global --volume CSS var */}
        <div style={{display: 'none'}}> 
          <AudioPulse volume={volume} active={connected && !client?.isMuted} hover={false} />
        </div>
      </>
    );
  }

  // --- Original UI (fallback if isUiHidden is false) ---
  // This part will be shown if you don't pass `isUiHidden={true}` from App.tsx
  // For your new design, this will likely not be rendered.
  return (
    <section className="control-tray">
      <canvas style={{ display: "none" }} ref={renderCanvasRef} />
      <nav className={cn("actions-nav", { disabled: !connected })}>
        <button
          className={cn("action-button mic-button")}
          onClick={() => contextSetMuted(client?.isMuted ? false : true)} // Toggle mute state
          disabled={!connected || isSwitchingCamera}
          title={client?.isMuted ? "Unmute Microphone" : "Mute Microphone"}
        >
          <span className="material-symbols-outlined filled">
            {client?.isMuted ? "mic_off" : "mic"}
          </span>
        </button>
        <div className="action-button no-action outlined">
          <AudioPulse volume={volume} active={connected && !client?.isMuted} hover={false} />
        </div>
        {/* ... other original buttons ... This part needs careful review if you want to mix UIs */}
      </nav>
      <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>
      {children}
    </section>
  );
}
export default memo(ControlTray);