File size: 12,030 Bytes
7f2a14a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f40f415
 
7f2a14a
 
 
 
 
 
 
 
 
 
 
 
 
616f053
7f2a14a
 
 
 
 
 
 
616f053
7f2a14a
 
 
 
 
 
616f053
 
 
 
7f2a14a
 
 
 
 
 
 
 
 
 
 
 
616f053
7f2a14a
 
 
 
 
 
 
 
 
616f053
7f2a14a
 
616f053
7f2a14a
 
 
 
616f053
7f2a14a
 
 
 
 
 
616f053
7f2a14a
 
 
 
 
 
 
 
 
 
616f053
7f2a14a
 
 
 
 
 
 
 
 
 
616f053
7f2a14a
 
 
 
 
 
 
616f053
7f2a14a
 
 
616f053
7f2a14a
 
 
 
f40f415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f2a14a
 
 
616f053
7f2a14a
616f053
 
7f2a14a
616f053
7f2a14a
 
 
 
616f053
 
 
 
7f2a14a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f40f415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f2a14a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aa81db
7f2a14a
 
1aa81db
7f2a14a
1aa81db
7f2a14a
1aa81db
 
7f2a14a
1aa81db
7f2a14a
1aa81db
7f2a14a
 
1aa81db
7f2a14a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
345
346
347
348
349
350
351
/**
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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 { audioContext } from "../../lib/utils";
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;
};

/**
 * button used for triggering webcam or screen-capture
 */
const MediaStreamButton = memo(
  ({ isStreaming, onIcon, offIcon, start, stop }: MediaStreamButtonProps) =>
    isStreaming ? (
      <button className="action-button" onClick={stop}>
        <span className="material-symbols-outlined">{onIcon}</span>
      </button>
    ) : (
      <button className="action-button" onClick={start}>
        <span className="material-symbols-outlined">{offIcon}</span>
      </button>
    ),
);

function ControlTray({
  videoRef,
  children,
  onVideoStreamChange = () => {},
  supportsVideo,
}: ControlTrayProps) {
  const videoStreams = [useWebcam(), useScreenCapture()];
  const [activeVideoStream, setActiveVideoStream] =
    useState<MediaStream | null>(null);
  const [webcam, screenCapture] = videoStreams;
  const [inVolume, setInVolume] = useState(0);
  const [audioRecorder] = useState(() => new AudioRecorder());
  const [muted, setMuted] = useState(false);
  const [videoDevices, setVideoDevices] = useState<MediaDeviceInfo[]>([]);
  const [currentDeviceIndex, setCurrentDeviceIndex] = useState(0);
  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();

  // Add iOS detection
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

  useEffect(() => {
    if (!connected && connectButtonRef.current) {
      console.log('๐ŸŽฏ Setting focus on connect button - connection status:', connected);
      connectButtonRef.current.focus();
    }
  }, [connected]);

  // Add iOS volume simulation effect
  useEffect(() => {
    if (isIOSDevice && connected && !muted) {
      console.log('๐Ÿ“ฑ Starting iOS volume simulation');
      const interval = setInterval(() => {
        // Create a smooth pulsing effect
        const pulse = (Math.sin(Date.now() / 500) + 1) / 2; // Values between 0 and 1
        setSimulatedVolume(0.02 + pulse * 0.03); // Small range for subtle effect
      }, 50);
      
      return () => {
        console.log('๐Ÿ›‘ Stopping iOS volume simulation');
        clearInterval(interval);
      };
    }
  }, [connected, muted, isIOSDevice]);

  useEffect(() => {
    document.documentElement.style.setProperty(
      "--volume",
      `${Math.max(5, Math.min((isIOSDevice ? simulatedVolume : inVolume) * 200, 8))}px`,
    );
  }, [inVolume, simulatedVolume, isIOSDevice]);

  useEffect(() => {
    const onData = (base64: string) => {
      console.log('๐ŸŽค Sending audio data chunk');
      client.sendRealtimeInput([
        {
          mimeType: "audio/pcm;rate=16000",
          data: base64,
        },
      ]);
    };

    if (connected && !muted && audioRecorder) {
      console.log('๐ŸŽ™๏ธ Starting audio recorder');
      audioRecorder.on("data", onData).on("volume", setInVolume).start();
    } else {
      console.log('โน๏ธ Stopping audio recorder');
      audioRecorder.stop();
    }

    return () => {
      console.log('๐Ÿงน Cleaning up audio recorder listeners');
      audioRecorder.off("data", onData).off("volume", setInVolume);
    };
  }, [connected, client, muted, audioRecorder]);

  useEffect(() => {
    if (videoRef.current) {
      console.log('๐ŸŽฅ Setting video stream:', activeVideoStream ? 'active' : 'null');
      videoRef.current.srcObject = activeVideoStream;
    }

    let timeoutId = -1;

    function sendVideoFrame() {
      const video = videoRef.current;
      const canvas = renderCanvasRef.current;

      if (!video || !canvas) {
        console.log('โš ๏ธ Missing video or canvas reference');
        return;
      }

      const ctx = canvas.getContext("2d")!;
      canvas.width = video.videoWidth * 0.25;
      canvas.height = video.videoHeight * 0.25;
      if (canvas.width + canvas.height > 0) {
        ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
        const base64 = canvas.toDataURL("image/jpeg", 1.0);
        const data = base64.slice(base64.indexOf(",") + 1, Infinity);
        console.log('๐Ÿ“ธ Sending video frame');
        client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
      }
      if (connected) {
        timeoutId = window.setTimeout(sendVideoFrame, 1000 / 0.5);
      }
    }
    if (connected && activeVideoStream !== null) {
      console.log('๐ŸŽฌ Starting video frame capture');
      requestAnimationFrame(sendVideoFrame);
    }
    return () => {
      console.log('โน๏ธ Stopping video frame capture');
      clearTimeout(timeoutId);
    };
  }, [connected, activeVideoStream, client, videoRef]);

  // Add effect to track available video devices
  useEffect(() => {
    async function getVideoDevices() {
      console.log('๐Ÿ“น Enumerating video devices...');
      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const videoInputs = devices.filter(device => device.kind === 'videoinput');
        console.log('๐Ÿ“น Available video devices:', videoInputs.length);
        videoInputs.forEach((device, index) => {
          console.log(`๐Ÿ“น Device ${index}:`, {
            deviceId: device.deviceId,
            label: device.label
          });
        });
        setVideoDevices(videoInputs);
      } catch (error) {
        console.error('โŒ Error enumerating devices:', error);
      }
    }

    // Get initial device list
    getVideoDevices();

    // Listen for device changes
    navigator.mediaDevices.addEventListener('devicechange', getVideoDevices);
    return () => {
      navigator.mediaDevices.removeEventListener('devicechange', getVideoDevices);
    };
  }, []);

  const rotateWebcam = async () => {
    console.log('๐Ÿ”„ Rotating webcam...');
    if (videoDevices.length <= 1) {
      console.log('โš ๏ธ Not enough video devices to rotate');
      return;
    }

    const nextIndex = (currentDeviceIndex + 1) % videoDevices.length;
    console.log(`๐ŸŽฏ Switching to device index ${nextIndex}`);
    
    try {
      const newStream = await navigator.mediaDevices.getUserMedia({
        video: { deviceId: { exact: videoDevices[nextIndex].deviceId } },
        audio: false
      });
      
      console.log('โœ… Got new video stream');
      setActiveVideoStream(newStream);
      onVideoStreamChange(newStream);
      setCurrentDeviceIndex(nextIndex);
      
      // Clean up old stream
      if (activeVideoStream) {
        activeVideoStream.getTracks().forEach(track => track.stop());
      }
    } catch (error) {
      console.error('โŒ Error rotating webcam:', error);
    }
  };

  //handler for swapping from one video-stream to the next
  const changeStreams = (next?: UseMediaStreamResult) => async () => {
    if (next) {
      console.log('๐Ÿ”„ Starting new video stream');
      const mediaStream = await next.start();
      setActiveVideoStream(mediaStream);
      onVideoStreamChange(mediaStream);
    } else {
      console.log('โน๏ธ Stopping video stream');
      setActiveVideoStream(null);
      onVideoStreamChange(null);
    }

    videoStreams.filter((msr) => msr !== next).forEach((msr) => {
      console.log('๐Ÿ›‘ Stopping other video streams');
      msr.stop();
    });
  };

  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={() => setMuted(!muted)}
        >
          {!muted ? (
            <span className="material-symbols-outlined filled">mic</span>
          ) : (
            <span className="material-symbols-outlined filled">mic_off</span>
          )}
        </button>

        <div className="action-button no-action outlined">
          <AudioPulse volume={volume} active={connected} hover={false} />
        </div>

        {supportsVideo && (
          <>
            {!isIOSDevice && (
              <MediaStreamButton
                isStreaming={screenCapture.isStreaming}
                start={changeStreams(screenCapture)}
                stop={changeStreams()}
                onIcon="cancel_presentation"
                offIcon="present_to_all"
              />
            )}
            {webcam.isStreaming && videoDevices.length > 1 && (
              <button 
                className="action-button" 
                onClick={rotateWebcam}
                title="Switch camera"
              >
                <span className="material-symbols-outlined">switch_camera</span>
              </button>
            )}
            <MediaStreamButton
              isStreaming={webcam.isStreaming}
              start={changeStreams(webcam)}
              stop={changeStreams()}
              onIcon="videocam_off"
              offIcon="videocam"
            />
          </>
        )}
        {children}
      </nav>

      <div className={cn("connection-container", { connected })}>
        <div className="connection-button-container">
          <button
            ref={connectButtonRef}
            className={cn("action-button connect-toggle", { connected })}
            onClick={async () => {
              console.log('๐ŸŽฎ ControlTray: Connection button clicked');
              try {
                if (connected) {
                  console.log('๐Ÿ“ด ControlTray: Initiating disconnect...');
                  await disconnect();
                  console.log('โœ… ControlTray: Disconnected successfully');
                } else {
                  console.log('๐Ÿ”Œ ControlTray: Starting connection process...');
                  console.log('๐Ÿ“ฑ ControlTray: Device info:', { isIOSDevice, isSafari });
                  
                  console.log('๐Ÿ“ž ControlTray: Calling LiveAPIContext.connect()...');
                  await connect();
                  console.log('โœ… ControlTray: Connected successfully via LiveAPIContext');
                }
              } catch (err) {
                console.error('โŒ ControlTray: Connection error:', err);
              }
            }}
          >
            <span className="material-symbols-outlined filled">
              {connected ? "pause" : "play_arrow"}
            </span>
          </button>
        </div>
        <span className="text-indicator">Streaming</span>
      </div>
    </section>
  );
}

export default memo(ControlTray);