/* Huddle Video Call App - WebRTC Client */ // ── State ──────────────────────────────────────────────────────────────── let ws = null; let localStream = null; let screenStream = null; let myPeerId = null; let myName = "Guest"; let roomId = null; let micEnabled = true; let camEnabled = false; let screenSharing = false; let chatOpen = false; let recording = false; let mediaRecorder = null; let recordedChunks = []; let recordingStartTime = null; let recordingTimerInterval = null; let myRole = "participant"; let handRaised = false; let meetingStartTime = null; let meetingTimerInterval = null; let bgBlurEnabled = false; let bgBlurCanvas = null; let bgBlurCtx = null; let bgBlurStream = null; let selfieSegmenter = null; let segMask = null; let vbgTempVideo = null; let vbgSceneBg = null; let vbgMode = null; // 'blur' | 'scene' let vbgPersonCanvas = null; let vbgPersonCtx = null; let vbgMaskCanvas = null; let vbgMaskCtx = null; let vbgTempMaskCanvas = null; let vbgTempMaskCtx = null; let vbgPrevMask = null; // Uint8Array for temporal smoothing let vbgUseFallback = false; let vbgFallbackMask = null; let viewMode = "gallery"; // "gallery" | "speaker" let pinnedPeerId = null; let currentVbg = "none"; let audioAnalysers = {}; // peer_id -> { analyser, dataArray } // Map of peer_id -> { pc: RTCPeerConnection, videoEl, tile, name } const peerConnections = {}; const ICE_SERVERS = [ { urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }, { urls: "stun:stun2.l.google.com:19302" }, ]; // ── Elements ───────────────────────────────────────────────────────────── const joinScreen = document.getElementById("joinScreen"); const callScreen = document.getElementById("callScreen"); const nameInput = document.getElementById("nameInput"); const roomInput = document.getElementById("roomInput"); const newMeetingBtn = document.getElementById("newMeetingBtn"); const joinBtn = document.getElementById("joinBtn"); const previewVideo = document.getElementById("previewVideo"); const previewPlaceholder = document.getElementById("previewPlaceholder"); const previewMic = document.getElementById("previewMic"); const previewCam = document.getElementById("previewCam"); const videoGrid = document.getElementById("videoGrid"); const localVideo = document.getElementById("localVideo"); const localVideoOff = document.getElementById("localVideoOff"); const localName = document.getElementById("localName"); const localMicIndicator = document.getElementById("localMicIndicator"); const micBtn = document.getElementById("micBtn"); const camBtn = document.getElementById("camBtn"); const screenBtn = document.getElementById("screenBtn"); const chatBtn = document.getElementById("chatBtn"); const leaveBtn = document.getElementById("leaveBtn"); const copyLinkBtn = document.getElementById("copyLinkBtn"); const roomInfo = document.getElementById("roomInfo"); const peerCount = document.getElementById("peerCount"); const chatPanel = document.getElementById("chatPanel"); const chatMessages = document.getElementById("chatMessages"); const chatInput = document.getElementById("chatInput"); const sendChatBtn = document.getElementById("sendChatBtn"); const closeChatBtn = document.getElementById("closeChatBtn"); const toast = document.getElementById("toast"); const recordBtn = document.getElementById("recordBtn"); // ── Init ───────────────────────────────────────────────────────────────── document.addEventListener("DOMContentLoaded", () => { // Check if URL has a room code const pathMatch = window.location.pathname.match(/^\/room\/([a-zA-Z0-9]+)/); if (pathMatch) { roomInput.value = pathMatch[1]; } // Restore name from localStorage const savedName = localStorage.getItem("huddle_name"); if (savedName) nameInput.value = savedName; startPreview(); setupJoinListeners(); }); // ── Camera Preview ─────────────────────────────────────────────────────── async function startPreview() { try { localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }); previewVideo.srcObject = localStream; previewVideo.muted = true; // Always mute local preview // Default camera off localStream.getVideoTracks().forEach(t => t.enabled = false); previewPlaceholder.style.display = "flex"; previewCam.classList.remove("active"); } catch (e) { console.warn("Could not access camera/mic:", e); previewPlaceholder.querySelector("p").textContent = "Camera not available"; } } // ── Join Screen Listeners ──────────────────────────────────────────────── function setupJoinListeners() { previewMic.addEventListener("click", () => { micEnabled = !micEnabled; previewMic.classList.toggle("active", micEnabled); if (localStream) { localStream.getAudioTracks().forEach(t => t.enabled = micEnabled); } }); previewCam.addEventListener("click", () => { camEnabled = !camEnabled; previewCam.classList.toggle("active", camEnabled); if (localStream) { localStream.getVideoTracks().forEach(t => t.enabled = camEnabled); } previewPlaceholder.style.display = camEnabled ? "none" : "flex"; }); newMeetingBtn.addEventListener("click", async () => { try { const resp = await fetch("/api/create-room", { method: "POST" }); const data = await resp.json(); joinRoom(data.room_id); } catch (e) { showToast("Failed to create room"); } }); joinBtn.addEventListener("click", () => { const code = roomInput.value.trim(); if (!code) { showToast("Please enter a room code"); return; } joinRoom(code); }); roomInput.addEventListener("keydown", (e) => { if (e.key === "Enter") joinBtn.click(); }); nameInput.addEventListener("keydown", (e) => { if (e.key === "Enter") newMeetingBtn.click(); }); } // ── Join Room ──────────────────────────────────────────────────────────── function joinRoom(id) { roomId = id; myName = nameInput.value.trim() || "Guest"; localStorage.setItem("huddle_name", myName); // Ensure we have a stream if (!localStream) { navigator.mediaDevices.getUserMedia({ video: true, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }) .then(stream => { localStream = stream; connectWebSocket(); }) .catch(() => { // Join without media connectWebSocket(); }); } else { connectWebSocket(); } } // ── WebSocket Connection ───────────────────────────────────────────────── function connectWebSocket() { const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; ws = new WebSocket(`${proto}//${window.location.host}/ws`); ws.onopen = () => { ws.send(JSON.stringify({ action: "join", room_id: roomId, name: myName, })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); handleSignal(msg); }; ws.onclose = () => { showToast("Disconnected from server"); }; ws.onerror = (err) => { console.error("WebSocket error:", err); }; } // ── Signal Handler ─────────────────────────────────────────────────────── async function handleSignal(msg) { console.log("[signal]", msg.action, msg); switch (msg.action) { case "joined": myPeerId = msg.peer_id; myRole = msg.role || "participant"; console.log("[me] My peer ID:", myPeerId, "role:", myRole); enterCallScreen(); for (const peer of msg.peers) { console.log("[init] Creating offer to existing peer:", peer.id, peer.name); await getOrCreatePeer(peer.id, peer.name); await sendOffer(peer.id); } break; case "peer-joined": showToast(`${msg.name} joined`); console.log("[peer-joined]", msg.peer_id, msg.name); getOrCreatePeer(msg.peer_id, msg.name); updatePeerCount(); updateParticipantList(); break; case "peer-left": removePeer(msg.peer_id); updatePeerCount(); updateParticipantList(); break; case "offer": await handleOffer(msg.from, msg.data); break; case "answer": await handleAnswer(msg.from, msg.data); break; case "ice-candidate": await handleIceCandidate(msg.from, msg.data); break; case "chat": addChatMessage(msg.name, msg.text, msg.time); logTranscript('chat', msg.name, msg.text); if (!chatOpen) showToast(`${msg.name}: ${msg.text}`); break; case "error": showToast(msg.message); break; // ── Waiting room ──────────────────────────────────── case "waiting-room": showWaitingRoom(msg.message); break; case "waiting-room-update": updateWaitingList(msg.waiting); break; case "denied": showToast(msg.message); leaveCall(); break; // ── Hand raise ────────────────────────────────────── case "hand-raise": handleHandRaise(msg.peer_id, msg.name, msg.raised); break; case "all-hands-lowered": handleAllHandsLowered(); break; // ── Reactions ─────────────────────────────────────── case "reaction": showReaction(msg.emoji, msg.name); break; // ── Host controls ─────────────────────────────────── case "host-changed": if (msg.new_host === myPeerId) { myRole = "host"; showToast("You are now the host"); showHostControls(); } else { showToast(`${msg.name} is now the host`); } updateParticipantList(); break; case "muted-by-host": micEnabled = false; micBtn.classList.remove("active"); if (localStream) localStream.getAudioTracks().forEach(t => t.enabled = false); localMicIndicator.textContent = "🔇"; localMicIndicator.classList.add("muted"); showToast(msg.message); break; case "kicked": showToast(msg.message); leaveCall(); break; case "setting-changed": showToast(`${msg.setting.replace('_', ' ')} ${msg.value ? 'enabled' : 'disabled'}`); if (msg.setting === "waiting_room") { const toggle = document.getElementById("waitingRoomToggle"); if (toggle) toggle.checked = msg.value; } break; // ── Polls ─────────────────────────────────────────── case "poll-started": renderPoll(msg.poll); showToast("New poll started!"); break; case "poll-update": updatePollResults(msg.poll_id, msg.results, msg.total_votes); break; case "poll-ended": endPollDisplay(msg.poll_id, msg.results, msg.total_votes); break; // ── Whiteboard ────────────────────────────────────── case "whiteboard-sync": replayWhiteboardStrokes(msg.strokes); break; case "whiteboard-stroke": drawRemoteStroke(msg.stroke); break; case "whiteboard-clear": clearWhiteboardLocal(); break; // ── Breakout rooms ────────────────────────────────── case "breakout-started": showToast("Breakout rooms started!"); renderBreakoutActive(msg.rooms); break; case "breakout-ended": showToast("Breakout rooms ended"); hideBreakoutActive(); break; // ── Captions ──────────────────────────────────────── case "caption": showCaption(msg.name, msg.text); logTranscript('speech', msg.name, msg.text); break; } } // ── Enter Call Screen ──────────────────────────────────────────────────── function enterCallScreen() { joinScreen.classList.remove("active"); callScreen.classList.add("active"); if (localStream) { localVideo.srcObject = localStream; localVideo.muted = true; } localVideoOff.style.display = camEnabled ? "none" : ""; localName.textContent = `${myName} (You)`; localMicIndicator.textContent = micEnabled ? "🎤" : "🔇"; localMicIndicator.classList.toggle("muted", !micEnabled); history.replaceState(null, "", `/room/${roomId}`); document.title = `Huddle - ${roomId}`; roomInfo.textContent = `Room: ${roomId}`; micBtn.classList.toggle("active", micEnabled); camBtn.classList.toggle("active", camEnabled); setupCallControls(); updateGridLayout(); updatePeerCount(); updateParticipantList(); // Start meeting timer meetingStartTime = Date.now(); meetingTimerInterval = setInterval(updateMeetingTimer, 1000); updateMeetingTimer(); // Show host controls if host if (myRole === "host") { showHostControls(); } // Start speaker detection startSpeakerDetectionLoop(); applyViewMode(); } // ── Call Control Listeners ─────────────────────────────────────────────── function setupCallControls() { micBtn.addEventListener("click", toggleMic); camBtn.addEventListener("click", toggleCam); screenBtn.addEventListener("click", toggleScreenShare); recordBtn.addEventListener("click", toggleRecording); leaveBtn.addEventListener("click", leaveCall); // Chat chatBtn.addEventListener("click", () => { chatOpen = !chatOpen; chatPanel.classList.toggle("open", chatOpen); chatBtn.classList.toggle("active", chatOpen); closeSidePanels("chatPanel"); if (chatOpen) chatInput.focus(); }); closeChatBtn.addEventListener("click", () => { chatOpen = false; chatPanel.classList.remove("open"); chatBtn.classList.remove("active"); }); copyLinkBtn.addEventListener("click", () => { const url = `${window.location.origin}/room/${roomId}`; navigator.clipboard.writeText(url).then(() => { showToast("Invite link copied!"); }).catch(() => { showToast(url); }); }); sendChatBtn.addEventListener("click", sendChat); chatInput.addEventListener("keydown", (e) => { if (e.key === "Enter") sendChat(); }); // Hand raise document.getElementById("handBtn").addEventListener("click", toggleHandRaise); // Reactions document.querySelectorAll(".reaction-btn").forEach(btn => { btn.addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "reaction", emoji: btn.dataset.emoji })); }); }); // Participants panel document.getElementById("participantsBtn").addEventListener("click", () => { const panel = document.getElementById("participantsPanel"); const open = !panel.classList.contains("open"); closeSidePanels("participantsPanel"); panel.classList.toggle("open", open); document.getElementById("participantsBtn").classList.toggle("active", open); if (open) updateParticipantList(); }); document.getElementById("closeParticipantsBtn").addEventListener("click", () => { document.getElementById("participantsPanel").classList.remove("open"); document.getElementById("participantsBtn").classList.remove("active"); }); // Host controls document.getElementById("muteAllBtn").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "mute-all" })); }); document.getElementById("lowerAllHandsBtn").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "lower-all-hands" })); }); document.getElementById("waitingRoomToggle").addEventListener("change", (e) => { if (ws) ws.send(JSON.stringify({ action: "toggle-waiting-room", enabled: e.target.checked })); }); document.getElementById("lockMeetingToggle").addEventListener("change", (e) => { if (ws) ws.send(JSON.stringify({ action: "lock-meeting", locked: e.target.checked })); }); // Waiting room leave document.getElementById("waitingLeaveBtn").addEventListener("click", leaveCall); // Whiteboard document.getElementById("whiteboardBtn").addEventListener("click", () => { const panel = document.getElementById("whiteboardPanel"); const open = !panel.classList.contains("open"); closeSidePanels("whiteboardPanel"); panel.classList.toggle("open", open); if (open) initWhiteboard(); }); document.getElementById("closeWhiteboardBtn").addEventListener("click", () => { document.getElementById("whiteboardPanel").classList.remove("open"); }); // Polls document.getElementById("pollsBtn").addEventListener("click", () => { const panel = document.getElementById("pollsPanel"); const open = !panel.classList.contains("open"); closeSidePanels("pollsPanel"); panel.classList.toggle("open", open); if (open && myRole === "host") { document.getElementById("createPollSection").style.display = "block"; } }); document.getElementById("closePollsBtn").addEventListener("click", () => { document.getElementById("pollsPanel").classList.remove("open"); }); document.getElementById("addPollOption").addEventListener("click", () => { const container = document.getElementById("pollOptionsContainer"); const count = container.children.length + 1; const input = document.createElement("input"); input.type = "text"; input.className = "poll-option-input"; input.placeholder = `Option ${count}`; input.maxLength = 100; container.appendChild(input); }); document.getElementById("launchPollBtn").addEventListener("click", () => { const question = document.getElementById("pollQuestion").value.trim(); const options = [...document.querySelectorAll(".poll-option-input")] .map(i => i.value.trim()).filter(Boolean); if (!question || options.length < 2) { showToast("Need a question and at least 2 options"); return; } if (ws) ws.send(JSON.stringify({ action: "create-poll", question, options })); document.getElementById("pollQuestion").value = ""; document.querySelectorAll(".poll-option-input").forEach((i, idx) => { i.value = ""; if (idx >= 2) i.remove(); }); }); // Breakout rooms document.getElementById("breakoutBtn").addEventListener("click", () => { const panel = document.getElementById("breakoutPanel"); const open = !panel.classList.contains("open"); closeSidePanels("breakoutPanel"); panel.classList.toggle("open", open); if (open && myRole === "host") { document.getElementById("breakoutSetup").style.display = "block"; initBreakoutSetup(); } }); document.getElementById("closeBreakoutBtn").addEventListener("click", () => { document.getElementById("breakoutPanel").classList.remove("open"); }); document.getElementById("addBreakoutRoom").addEventListener("click", addBreakoutRoomRow); document.getElementById("startBreakoutBtn").addEventListener("click", startBreakout); document.getElementById("endBreakoutBtn").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "end-breakout" })); }); // Background blur document.getElementById("bgBlurBtn").addEventListener("click", toggleBgBlur); // Meeting Notes document.getElementById("notesBtn").addEventListener("click", () => { const panel = document.getElementById("notesPanel"); const open = !panel.classList.contains("open"); closeSidePanels("notesPanel"); panel.classList.toggle("open", open); if (open) refreshNotesSummaries(); }); document.getElementById("closeNotesBtn").addEventListener("click", () => { document.getElementById("notesPanel").classList.remove("open"); }); document.getElementById("saveNotesBtn").addEventListener("click", saveNotes); document.getElementById("generateSummaryBtn").addEventListener("click", generateAndInsertSummary); // View toggle document.getElementById("viewToggleBtn").addEventListener("click", toggleViewMode); // Captions toggle document.getElementById("captionBtn").addEventListener("click", toggleCaptions); // More menu click toggle (for mobile/touch) document.getElementById("moreBtn").addEventListener("click", (e) => { e.stopPropagation(); const menu = document.getElementById("moreMenu"); menu.classList.toggle("open"); }); document.addEventListener("click", () => { document.getElementById("moreMenu").classList.remove("open"); }); // Device selector document.getElementById("deviceSelectBtn").addEventListener("click", openDeviceSelector); document.getElementById("closeDeviceModal").addEventListener("click", () => { document.getElementById("deviceModal").style.display = "none"; }); document.getElementById("camSelect").addEventListener("change", (e) => switchCamera(e.target.value)); document.getElementById("micSelect").addEventListener("change", (e) => switchMicrophone(e.target.value)); document.getElementById("speakerSelect").addEventListener("change", (e) => switchSpeaker(e.target.value)); // Virtual background document.getElementById("virtualBgBtn").addEventListener("click", openVirtualBgModal); document.getElementById("closeVbgModal").addEventListener("click", () => { document.getElementById("vbgModal").style.display = "none"; }); document.querySelectorAll(".vbg-option").forEach(opt => { opt.addEventListener("click", () => { document.querySelectorAll(".vbg-option").forEach(o => o.classList.remove("active")); opt.classList.add("active"); applyVirtualBg(opt.dataset.bg); document.getElementById("vbgModal").style.display = "none"; }); }); // Keyboard shortcuts modal document.getElementById("shortcutsBtn").addEventListener("click", () => { document.getElementById("shortcutsModal").style.display = "flex"; }); document.getElementById("closeShortcutsModal").addEventListener("click", () => { document.getElementById("shortcutsModal").style.display = "none"; }); // Close modals on overlay click document.querySelectorAll(".modal-overlay").forEach(overlay => { overlay.addEventListener("click", (e) => { if (e.target === overlay) overlay.style.display = "none"; }); }); // Pin local video document.getElementById("localTile")?.addEventListener("dblclick", () => togglePin("local")); // Keyboard shortcuts setupKeyboardShortcuts(); } function toggleMic() { micEnabled = !micEnabled; micBtn.classList.toggle("active", micEnabled); if (localStream) { localStream.getAudioTracks().forEach(t => t.enabled = micEnabled); } localMicIndicator.textContent = micEnabled ? "🎤" : "🔇"; localMicIndicator.classList.toggle("muted", !micEnabled); } function toggleCam() { camEnabled = !camEnabled; camBtn.classList.toggle("active", camEnabled); if (localStream) { localStream.getVideoTracks().forEach(t => t.enabled = camEnabled); } localVideoOff.style.display = camEnabled ? "none" : ""; } async function toggleScreenShare() { if (screenSharing) { stopScreenShare(); return; } try { screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }); screenSharing = true; screenBtn.classList.add("active"); const screenTrack = screenStream.getVideoTracks()[0]; screenTrack.onended = () => stopScreenShare(); // Replace video track in all peer connections for (const pid in peerConnections) { const pc = peerConnections[pid].pc; const sender = pc.getSenders().find(s => s.track && s.track.kind === "video"); if (sender) { sender.replaceTrack(screenTrack); } } // Show screen share locally localVideo.srcObject = screenStream; localVideoOff.style.display = "none"; showToast("Screen sharing started"); } catch (e) { console.warn("Screen share cancelled:", e); } } function stopScreenShare() { if (screenStream) { screenStream.getTracks().forEach(t => t.stop()); screenStream = null; } screenSharing = false; screenBtn.classList.remove("active"); // Restore camera track const camTrack = localStream ? localStream.getVideoTracks()[0] : null; for (const pid in peerConnections) { const pc = peerConnections[pid].pc; const sender = pc.getSenders().find(s => s.track && s.track.kind === "video"); if (sender && camTrack) { sender.replaceTrack(camTrack); } } localVideo.srcObject = localStream; localVideoOff.style.display = camEnabled ? "none" : ""; showToast("Screen sharing stopped"); } function leaveCall() { if (recording) stopRecording(); for (const pid in peerConnections) { peerConnections[pid].pc.close(); peerConnections[pid].tile.remove(); delete peerConnections[pid]; } if (ws) { ws.close(); ws = null; } if (screenStream) { screenStream.getTracks().forEach(t => t.stop()); screenStream = null; } if (bgBlurStream) { bgBlurStream.getTracks().forEach(t => t.stop()); bgBlurStream = null; } bgBlurEnabled = false; screenSharing = false; chatOpen = false; handRaised = false; myRole = "participant"; pinnedPeerId = null; viewMode = "gallery"; currentVbg = "none"; chatPanel.classList.remove("open"); document.querySelectorAll(".side-panel").forEach(p => p.classList.remove("open")); document.querySelectorAll(".modal-overlay").forEach(m => m.style.display = "none"); clearInterval(meetingTimerInterval); meetingTimerInterval = null; stopSpeakerDetectionLoop(); for (const pid in audioAnalysers) cleanupSpeakerDetection(pid); // Hide waiting room overlay document.getElementById("waitingRoomOverlay").style.display = "none"; callScreen.classList.remove("active"); joinScreen.classList.add("active"); history.replaceState(null, "", "/"); document.title = "Huddle - Video Calls"; if (localStream) { previewVideo.srcObject = localStream; } } // ── Recording ─────────────────────────────────────────────────────────── function toggleRecording() { if (recording) { stopRecording(); } else { startRecording(); } } function startRecording() { const audioCtx = new AudioContext(); const dest = audioCtx.createMediaStreamDestination(); // Mix local audio if (localStream) { const localAudioTracks = localStream.getAudioTracks(); if (localAudioTracks.length > 0) { const localSource = audioCtx.createMediaStreamSource( new MediaStream(localAudioTracks) ); localSource.connect(dest); } } // Mix remote audio from all peers for (const pid in peerConnections) { const remoteStream = peerConnections[pid].videoEl.srcObject; if (remoteStream) { const remoteTracks = remoteStream.getAudioTracks(); if (remoteTracks.length > 0) { const remoteSource = audioCtx.createMediaStreamSource( new MediaStream(remoteTracks) ); remoteSource.connect(dest); } } } // Capture the video grid as a canvas stream const gridEl = document.getElementById("videoGrid"); const canvas = document.createElement("canvas"); canvas.width = 1280; canvas.height = 720; const ctx = canvas.getContext("2d"); // Draw all video elements onto canvas at 30fps const drawInterval = setInterval(() => { ctx.fillStyle = "#f5f7fb"; ctx.fillRect(0, 0, canvas.width, canvas.height); const videos = gridEl.querySelectorAll("video"); const count = videos.length; if (count === 0) return; const cols = count <= 1 ? 1 : count <= 4 ? 2 : 3; const rows = Math.ceil(count / cols); const tileW = canvas.width / cols; const tileH = canvas.height / rows; videos.forEach((video, i) => { if (!video.srcObject || video.videoWidth === 0) return; const col = i % cols; const row = Math.floor(i / cols); const x = col * tileW; const y = row * tileH; const vw = video.videoWidth; const vh = video.videoHeight; const vAspect = vw / vh; const tAspect = tileW / tileH; let sx, sy, sw, sh; if (vAspect > tAspect) { sh = vh; sw = vh * tAspect; sx = (vw - sw) / 2; sy = 0; } else { sw = vw; sh = vw / tAspect; sx = 0; sy = (vh - sh) / 2; } ctx.drawImage(video, sx, sy, sw, sh, x + 2, y + 2, tileW - 4, tileH - 4); }); }, 1000 / 30); const canvasStream = canvas.captureStream(30); // Combine canvas video + mixed audio const combined = new MediaStream([ ...canvasStream.getVideoTracks(), ...dest.stream.getAudioTracks(), ]); const mimeType = MediaRecorder.isTypeSupported("video/webm;codecs=vp9,opus") ? "video/webm;codecs=vp9,opus" : "video/webm"; recordedChunks = []; mediaRecorder = new MediaRecorder(combined, { mimeType }); mediaRecorder.ondataavailable = (e) => { if (e.data.size > 0) recordedChunks.push(e.data); }; mediaRecorder.onstop = () => { clearInterval(drawInterval); audioCtx.close(); const blob = new Blob(recordedChunks, { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19); a.href = url; a.download = `Huddle-${roomId}-${timestamp}.webm`; a.click(); URL.revokeObjectURL(url); showToast("Recording saved!"); }; mediaRecorder._drawInterval = drawInterval; mediaRecorder._audioCtx = audioCtx; mediaRecorder.start(1000); recording = true; recordBtn.classList.add("active"); recordBtn.classList.add("recording"); recordingStartTime = Date.now(); updateRecordingTimer(); recordingTimerInterval = setInterval(updateRecordingTimer, 1000); showToast("Recording started"); } function stopRecording() { if (mediaRecorder && mediaRecorder.state !== "inactive") { mediaRecorder.stop(); } recording = false; recordBtn.classList.remove("active"); recordBtn.classList.remove("recording"); clearInterval(recordingTimerInterval); const timerEl = document.getElementById("recordTimer"); if (timerEl) timerEl.remove(); showToast("Recording stopped — downloading..."); } function updateRecordingTimer() { const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000); const mins = String(Math.floor(elapsed / 60)).padStart(2, "0"); const secs = String(elapsed % 60).padStart(2, "0"); let timerEl = document.getElementById("recordTimer"); if (!timerEl) { timerEl = document.createElement("span"); timerEl.id = "recordTimer"; timerEl.className = "record-timer"; recordBtn.parentElement.insertBefore(timerEl, recordBtn.nextSibling); } timerEl.textContent = `${mins}:${secs}`; } function sendChat() { const text = chatInput.value.trim(); if (!text || !ws) return; ws.send(JSON.stringify({ action: "chat", text })); chatInput.value = ""; } // ── WebRTC Peer Connection ─────────────────────────────────────────────── function getOrCreatePeer(peerId, peerName) { // If we already have a connection for this peer, just update name if (peerConnections[peerId]) { if (peerName && peerName !== "Peer") { peerConnections[peerId].name = peerName; const nameEl = peerConnections[peerId].tile.querySelector(".tile-name"); if (nameEl) nameEl.textContent = peerName; } return peerConnections[peerId]; } console.log("[peer] Creating new peer connection for:", peerId, peerName); const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS }); // Create video tile for remote peer const tile = document.createElement("div"); tile.className = "video-tile"; tile.dataset.peer = peerId; tile.innerHTML = `
👤
${escapeHtml(peerName || "Peer")} 🎤
`; videoGrid.appendChild(tile); const videoEl = tile.querySelector("video"); videoEl.muted = false; videoEl.volume = 1.0; const offOverlay = tile.querySelector(".video-off-overlay"); // Pin button tile.querySelector(".pin-btn").addEventListener("click", () => togglePin(peerId)); const conn = { pc, videoEl, tile, name: peerName, offOverlay }; peerConnections[peerId] = conn; // Add local tracks to peer connection if (localStream) { localStream.getTracks().forEach(track => { pc.addTrack(track, localStream); }); console.log("[peer] Added", localStream.getTracks().length, "local tracks for", peerId); } else { console.warn("[peer] No local stream to add tracks from"); } // Handle incoming tracks from remote peer pc.ontrack = (event) => { console.log("[track] Received", event.track.kind, "track from", peerId, "streams:", event.streams.length); // Use the first stream from the event if (event.streams && event.streams[0]) { videoEl.srcObject = event.streams[0]; } else { // Fallback: create a new MediaStream if (!videoEl.srcObject) { videoEl.srcObject = new MediaStream(); } videoEl.srcObject.addTrack(event.track); } offOverlay.style.display = "none"; // Setup speaker detection for audio tracks if (event.track.kind === "audio") { setupSpeakerDetection(peerId, event.streams[0]); } // Force play to handle autoplay policy videoEl.play().catch(err => { console.warn("[track] Autoplay blocked for", peerId, err); }); }; // ICE candidates pc.onicecandidate = (event) => { if (event.candidate && ws) { ws.send(JSON.stringify({ action: "ice-candidate", target: peerId, data: event.candidate.toJSON(), })); } }; pc.onconnectionstatechange = () => { console.log("[peer]", peerId, "connection state:", pc.connectionState); if (pc.connectionState === "connected") { offOverlay.style.display = "none"; } if (pc.connectionState === "failed") { console.error("[peer]", peerId, "connection failed"); removePeer(peerId); } }; pc.oniceconnectionstatechange = () => { console.log("[peer]", peerId, "ICE state:", pc.iceConnectionState); if (pc.iceConnectionState === "disconnected" || pc.iceConnectionState === "failed") { removePeer(peerId); } }; updateGridLayout(); updatePeerCount(); return conn; } async function sendOffer(peerId) { const conn = peerConnections[peerId]; if (!conn) return; try { const offer = await conn.pc.createOffer({ offerToReceiveAudio: true, offerToReceiveVideo: true, }); await conn.pc.setLocalDescription(offer); console.log("[offer] Sending offer to", peerId, "state:", conn.pc.signalingState); ws.send(JSON.stringify({ action: "offer", target: peerId, data: conn.pc.localDescription.toJSON(), })); } catch (err) { console.error("[offer] Failed to create offer for", peerId, err); } } async function handleOffer(fromId, offerData) { const conn = getOrCreatePeer(fromId, null); const pc = conn.pc; try { console.log("[offer] Handling offer from", fromId, "signalingState:", pc.signalingState); await pc.setRemoteDescription(new RTCSessionDescription(offerData)); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); console.log("[answer] Sending answer to", fromId); ws.send(JSON.stringify({ action: "answer", target: fromId, data: pc.localDescription.toJSON(), })); } catch (err) { console.error("[offer] Failed to handle offer from", fromId, err); } } async function handleAnswer(fromId, answerData) { const conn = peerConnections[fromId]; if (!conn) { console.warn("[answer] No connection for", fromId); return; } try { console.log("[answer] Setting remote description from", fromId, "signalingState:", conn.pc.signalingState); await conn.pc.setRemoteDescription(new RTCSessionDescription(answerData)); } catch (err) { console.error("[answer] Failed to set answer from", fromId, err); } } async function handleIceCandidate(fromId, candidateData) { const conn = peerConnections[fromId]; if (!conn) return; try { await conn.pc.addIceCandidate(new RTCIceCandidate(candidateData)); } catch (e) { console.warn("[ice] Failed to add ICE candidate from", fromId, e); } } function removePeer(peerId) { const conn = peerConnections[peerId]; if (!conn) return; conn.pc.close(); conn.tile.remove(); delete peerConnections[peerId]; cleanupSpeakerDetection(peerId); if (pinnedPeerId === peerId) pinnedPeerId = null; const name = conn.name || "Someone"; showToast(`${name} left`); updateGridLayout(); updatePeerCount(); } // ── Grid Layout ────────────────────────────────────────────────────────── function updateGridLayout() { const count = videoGrid.children.length; videoGrid.dataset.count = Math.min(count, 9); } function updatePeerCount() { const count = Object.keys(peerConnections).length + 1; // +1 for self peerCount.textContent = `${count} participant${count !== 1 ? "s" : ""}`; } // ── Chat ───────────────────────────────────────────────────────────────── function addChatMessage(name, text, time) { const div = document.createElement("div"); div.className = "chat-msg"; div.innerHTML = `${escapeHtml(name)}${time || ""}
${escapeHtml(text)}`; chatMessages.appendChild(div); chatMessages.scrollTop = chatMessages.scrollHeight; } // ── Helpers ────────────────────────────────────────────────────────────── function escapeHtml(str) { const div = document.createElement("div"); div.textContent = str || ""; return div.innerHTML; } function showToast(message) { toast.textContent = message; toast.classList.add("visible"); setTimeout(() => toast.classList.remove("visible"), 3000); } // ═══════════════════════════════════════════════════════════════════════════ // NEW ZOOM-LIKE FEATURES // ═══════════════════════════════════════════════════════════════════════════ // ── Side Panel Helper ─────────────────────────────────────────────────── function closeSidePanels(except) { const panels = ["chatPanel", "participantsPanel", "whiteboardPanel", "pollsPanel", "breakoutPanel", "notesPanel"]; panels.forEach(id => { if (id !== except) document.getElementById(id).classList.remove("open"); }); if (except !== "chatPanel") { chatOpen = false; chatBtn.classList.remove("active"); } } // ── Meeting Timer ─────────────────────────────────────────────────────── function updateMeetingTimer() { if (!meetingStartTime) return; const elapsed = Math.floor((Date.now() - meetingStartTime) / 1000); const h = Math.floor(elapsed / 3600); const m = String(Math.floor((elapsed % 3600) / 60)).padStart(2, "0"); const s = String(elapsed % 60).padStart(2, "0"); const el = document.getElementById("meetingTimer"); if (el) el.textContent = h > 0 ? `${h}:${m}:${s}` : `${m}:${s}`; } // ── Host Controls ─────────────────────────────────────────────────────── function showHostControls() { const el = document.getElementById("hostControls"); if (el) el.style.display = "flex"; const createPoll = document.getElementById("createPollSection"); if (createPoll) createPoll.style.display = "block"; const breakout = document.getElementById("breakoutSetup"); if (breakout) breakout.style.display = "block"; } // ── Hand Raise ────────────────────────────────────────────────────────── function toggleHandRaise() { handRaised = !handRaised; const btn = document.getElementById("handBtn"); btn.classList.toggle("raised", handRaised); document.getElementById("localHand").style.display = handRaised ? "" : "none"; if (ws) ws.send(JSON.stringify({ action: "hand-raise", raised: handRaised })); showToast(handRaised ? "Hand raised" : "Hand lowered"); } function handleHandRaise(peerId, name, raised) { const conn = peerConnections[peerId]; if (conn) { let indicator = conn.tile.querySelector(".hand-indicator"); if (!indicator) { indicator = document.createElement("div"); indicator.className = "hand-indicator"; indicator.textContent = "✋"; conn.tile.appendChild(indicator); } indicator.style.display = raised ? "" : "none"; conn.hand = raised; } if (raised) showToast(`${name} raised hand ✋`); updateParticipantList(); } function handleAllHandsLowered() { handRaised = false; document.getElementById("handBtn").classList.remove("raised"); document.getElementById("localHand").style.display = "none"; for (const pid in peerConnections) { peerConnections[pid].hand = false; const indicator = peerConnections[pid].tile.querySelector(".hand-indicator"); if (indicator) indicator.style.display = "none"; } showToast("All hands lowered"); updateParticipantList(); } // ── Reactions ─────────────────────────────────────────────────────────── function showReaction(emoji, name) { const overlay = document.getElementById("reactionsOverlay"); const el = document.createElement("div"); el.className = "reaction-float"; el.textContent = emoji; el.style.left = Math.random() * 250 + "px"; overlay.appendChild(el); setTimeout(() => el.remove(), 2600); } // ── Waiting Room ──────────────────────────────────────────────────────── function showWaitingRoom(message) { joinScreen.classList.remove("active"); callScreen.classList.add("active"); document.getElementById("waitingRoomOverlay").style.display = "flex"; document.getElementById("waitingRoomMsg").textContent = message; } function updateWaitingList(waiting) { const container = document.getElementById("waitingListContent"); const wrapper = document.getElementById("waitingList"); if (!waiting || !waiting.length) { wrapper.style.display = "none"; return; } wrapper.style.display = "block"; container.innerHTML = waiting.map(w => `
${escapeHtml(w.name)}
`).join(""); } function admitPeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "admit-peer", target: targetId })); } function denyPeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "deny-peer", target: targetId })); } // ── Participant List ──────────────────────────────────────────────────── function updateParticipantList() { const list = document.getElementById("participantList"); if (!list) return; const count = Object.keys(peerConnections).length + 1; document.getElementById("participantCountTitle").textContent = `In Meeting (${count})`; let html = `
${escapeHtml(myName)} (You) ${myRole === "host" ? 'Host' : ""} ${handRaised ? '✋' : ""}
`; for (const pid in peerConnections) { const c = peerConnections[pid]; const isHost = false; // Server tracks this, simplified here html += `
${escapeHtml(c.name || "Peer")} ${c.hand ? '✋' : ""} ${myRole === "host" ? ` ` : ""}
`; } list.innerHTML = html; } function mutePeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "mute-peer", target: targetId })); } function kickPeer(targetId) { if (ws) ws.send(JSON.stringify({ action: "kick-peer", target: targetId })); } // ── Polls ─────────────────────────────────────────────────────────────── const activePolls = {}; function renderPoll(poll) { activePolls[poll.id] = poll; const container = document.getElementById("activePollsList"); let card = document.getElementById(`poll-${poll.id}`); if (!card) { card = document.createElement("div"); card.id = `poll-${poll.id}`; card.className = "poll-card"; container.prepend(card); } const total = poll.total_votes || 0; const results = poll.results || poll.options.map(() => 0); card.innerHTML = `

${escapeHtml(poll.question)}

${poll.options.map((opt, i) => { const count = results[i] || 0; const pct = total > 0 ? Math.round(count / total * 100) : 0; const voted = poll.my_vote === i; return `
${escapeHtml(opt)}
${pct}%
`; }).join("")}
${total} vote${total !== 1 ? 's' : ''}
${myRole === "host" && poll.active ? `` : ""} ${!poll.active ? '
Poll ended
' : ""} `; } function votePoll(pollId, choice) { if (ws) ws.send(JSON.stringify({ action: "vote-poll", poll_id: pollId, choice })); if (activePolls[pollId]) activePolls[pollId].my_vote = choice; } function endPoll(pollId) { if (ws) ws.send(JSON.stringify({ action: "end-poll", poll_id: pollId })); } function updatePollResults(pollId, results, totalVotes) { if (activePolls[pollId]) { activePolls[pollId].results = results; activePolls[pollId].total_votes = totalVotes; renderPoll(activePolls[pollId]); } } function endPollDisplay(pollId, results, totalVotes) { if (activePolls[pollId]) { activePolls[pollId].active = false; activePolls[pollId].results = results; activePolls[pollId].total_votes = totalVotes; renderPoll(activePolls[pollId]); } } // ── Whiteboard ────────────────────────────────────────────────────────── let wbDrawing = false; let wbCurrentStroke = null; let wbEraser = false; function initWhiteboard() { const canvas = document.getElementById("whiteboardCanvas"); if (canvas._initialized) return; canvas._initialized = true; const ctx = canvas.getContext("2d"); ctx.lineCap = "round"; ctx.lineJoin = "round"; canvas.addEventListener("pointerdown", (e) => { wbDrawing = true; const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left) / rect.width * canvas.width; const y = (e.clientY - rect.top) / rect.height * canvas.height; const color = wbEraser ? "#ffffff" : document.getElementById("wbColor").value; const width = wbEraser ? 20 : parseInt(document.getElementById("wbSize").value); wbCurrentStroke = { points: [[x, y]], color, width }; ctx.strokeStyle = color; ctx.lineWidth = width; ctx.beginPath(); ctx.moveTo(x, y); }); canvas.addEventListener("pointermove", (e) => { if (!wbDrawing || !wbCurrentStroke) return; const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left) / rect.width * canvas.width; const y = (e.clientY - rect.top) / rect.height * canvas.height; wbCurrentStroke.points.push([x, y]); const ctx2 = canvas.getContext("2d"); ctx2.strokeStyle = wbCurrentStroke.color; ctx2.lineWidth = wbCurrentStroke.width; ctx2.lineTo(x, y); ctx2.stroke(); }); const endDraw = () => { if (wbDrawing && wbCurrentStroke && wbCurrentStroke.points.length > 1) { if (ws) ws.send(JSON.stringify({ action: "whiteboard-stroke", stroke: wbCurrentStroke })); } wbDrawing = false; wbCurrentStroke = null; }; canvas.addEventListener("pointerup", endDraw); canvas.addEventListener("pointerleave", endDraw); document.getElementById("wbEraser").addEventListener("click", () => { wbEraser = !wbEraser; document.getElementById("wbEraser").classList.toggle("active", wbEraser); canvas.style.cursor = wbEraser ? "cell" : "crosshair"; }); document.getElementById("wbClear").addEventListener("click", () => { if (ws) ws.send(JSON.stringify({ action: "whiteboard-clear" })); clearWhiteboardLocal(); }); } function drawRemoteStroke(stroke) { const canvas = document.getElementById("whiteboardCanvas"); const ctx = canvas.getContext("2d"); if (!stroke.points || stroke.points.length < 2) return; ctx.strokeStyle = stroke.color || "#000"; ctx.lineWidth = stroke.width || 3; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.beginPath(); ctx.moveTo(stroke.points[0][0], stroke.points[0][1]); for (let i = 1; i < stroke.points.length; i++) { ctx.lineTo(stroke.points[i][0], stroke.points[i][1]); } ctx.stroke(); } function replayWhiteboardStrokes(strokes) { const canvas = document.getElementById("whiteboardCanvas"); const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); for (const stroke of strokes) drawRemoteStroke(stroke); } function clearWhiteboardLocal() { const canvas = document.getElementById("whiteboardCanvas"); const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); } // ── Breakout Rooms ────────────────────────────────────────────────────── function initBreakoutSetup() { const container = document.getElementById("breakoutRoomsList"); if (container.children.length === 0) { addBreakoutRoomRow(); addBreakoutRoomRow(); } } function addBreakoutRoomRow() { const container = document.getElementById("breakoutRoomsList"); const idx = container.children.length + 1; const row = document.createElement("div"); row.className = "breakout-room-row"; row.innerHTML = `
`; container.appendChild(row); updateBreakoutAssignments(); } function updateBreakoutAssignments() { const peersInCall = Object.entries(peerConnections).map(([id, c]) => ({ id, name: c.name || "Peer" })); const rows = document.querySelectorAll("#breakoutRoomsList .breakout-room-row"); rows.forEach(row => { const peersDiv = row.querySelector(".br-peers"); peersDiv.innerHTML = peersInCall.map(p => `${escapeHtml(p.name)}` ).join(""); }); } function startBreakout() { const rows = document.querySelectorAll("#breakoutRoomsList .breakout-room-row"); const breakoutRooms = []; rows.forEach(row => { const name = row.querySelector("input").value.trim() || "Room"; const assignedPeers = [...row.querySelectorAll(".br-peer-chip.assigned")].map(el => el.dataset.pid); breakoutRooms.push({ name, peers: assignedPeers }); }); if (ws) ws.send(JSON.stringify({ action: "create-breakout", rooms: breakoutRooms })); } function renderBreakoutActive(rooms) { const setup = document.getElementById("breakoutSetup"); const active = document.getElementById("breakoutActive"); const list = document.getElementById("breakoutActiveList"); setup.style.display = "none"; active.style.display = "block"; list.innerHTML = Object.entries(rooms).map(([rid, r]) => `
${escapeHtml(r.name)}
${r.peers.map(pid => { const name = peerConnections[pid]?.name || (pid === myPeerId ? myName : "Peer"); return `${escapeHtml(name)}`; }).join("")}
`).join(""); } function hideBreakoutActive() { document.getElementById("breakoutSetup").style.display = myRole === "host" ? "block" : "none"; document.getElementById("breakoutActive").style.display = "none"; } // ── Background Blur ───────────────────────────────────────────────────── async function toggleBgBlur() { if (bgBlurEnabled && vbgMode === 'blur') { // Turn off blur applyVirtualBg('none'); } else { // Turn on blur await applyVirtualBg('blur'); } } // ── Meeting Notes ─────────────────────────────────────────────────────── function refreshNotesSummaries() { // Polls summary const pollsContent = document.getElementById("notesPollsContent"); const pollKeys = Object.keys(activePolls); if (pollKeys.length) { pollsContent.innerHTML = pollKeys.map(pid => { const p = activePolls[pid]; const total = p.total_votes || 0; const results = p.results || p.options.map(() => 0); let html = `
${escapeHtml(p.question)}${p.active ? '' : ' (ended)'}`; html += '
'; return html; }).join(''); } else { pollsContent.textContent = 'No polls yet.'; } // Whiteboard snapshot const wbContent = document.getElementById("notesWhiteboardContent"); const canvas = document.getElementById("whiteboardCanvas"); if (canvas && canvas._initialized) { const ctx = canvas.getContext("2d"); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const hasContent = imageData.data.some((v, i) => i % 4 !== 3 && v !== 0); if (hasContent) { const dataUrl = canvas.toDataURL("image/png"); wbContent.innerHTML = `Whiteboard snapshot`; } else { wbContent.innerHTML = 'Whiteboard is empty.'; } } else { wbContent.innerHTML = 'Open whiteboard to capture.'; } // Breakout rooms summary const brContent = document.getElementById("notesBreakoutContent"); const brList = document.getElementById("breakoutActiveList"); if (brList && brList.children.length > 0) { brContent.innerHTML = brList.innerHTML; } else { brContent.textContent = 'No breakout rooms yet.'; } // Transcript summary const txContent = document.getElementById("notesTranscriptContent"); if (txContent) { if (meetingTranscript.length > 0) { txContent.innerHTML = formatTranscriptSummary(); } else { txContent.innerHTML = 'Enable captions (CC) to auto-capture discussion.'; } } } function formatTranscriptSummary() { const speechEntries = meetingTranscript.filter(e => e.type === 'speech'); const chatEntries = meetingTranscript.filter(e => e.type === 'chat'); let html = ''; // Key discussion points grouped by speaker if (speechEntries.length > 0) { html += '
Discussion Transcript'; // Group consecutive entries by same speaker const grouped = []; let current = null; for (const entry of speechEntries) { if (current && current.name === entry.name) { current.texts.push(entry.text); current.endTime = entry.time; } else { current = { name: entry.name, texts: [entry.text], startTime: entry.time, endTime: entry.time }; grouped.push(current); } } for (const g of grouped) { html += `
`; html += `${escapeHtml(g.name)}`; html += `${g.startTime}`; html += `

${escapeHtml(g.texts.join(' '))}

`; } html += '
'; // Speaker summary const speakers = {}; for (const e of speechEntries) { if (!speakers[e.name]) speakers[e.name] = { count: 0, words: 0 }; speakers[e.name].count++; speakers[e.name].words += e.text.split(/\s+/).length; } html += '
Speaker Summary
'; } // Chat messages if (chatEntries.length > 0) { html += '
Chat Messages'; for (const e of chatEntries) { html += `
${escapeHtml(e.name)}`; html += `${e.time}`; html += `

${escapeHtml(e.text)}

`; } html += '
'; } if (!html) html = 'No discussion captured yet.'; return html; } function generateAndInsertSummary() { const textarea = document.getElementById('notesTextarea'); const speechEntries = meetingTranscript.filter(e => e.type === 'speech'); const chatEntries = meetingTranscript.filter(e => e.type === 'chat'); let summary = ''; if (speechEntries.length === 0 && chatEntries.length === 0) { showToast('No discussion to summarize. Enable captions first.'); return; } summary += '=== MEETING SUMMARY ===\n'; summary += `Generated: ${new Date().toLocaleString()}\n`; summary += `Total contributions: ${meetingTranscript.length}\n\n`; if (speechEntries.length > 0) { summary += '--- Discussion ---\n'; const grouped = []; let current = null; for (const entry of speechEntries) { if (current && current.name === entry.name) { current.texts.push(entry.text); } else { current = { name: entry.name, texts: [entry.text], time: entry.time }; grouped.push(current); } } for (const g of grouped) { summary += `[${g.time}] ${g.name}: ${g.texts.join(' ')}\n`; } summary += '\n'; // Speaker stats const speakers = {}; for (const e of speechEntries) { if (!speakers[e.name]) speakers[e.name] = { count: 0, words: 0 }; speakers[e.name].count++; speakers[e.name].words += e.text.split(/\s+/).length; } summary += '--- Speakers ---\n'; for (const [name, stats] of Object.entries(speakers)) { summary += `${name}: ${stats.count} contributions, ~${stats.words} words\n`; } summary += '\n'; } if (chatEntries.length > 0) { summary += '--- Chat ---\n'; for (const e of chatEntries) { summary += `[${e.time}] ${e.name}: ${e.text}\n`; } } // Append to existing notes if (textarea.value.trim()) { textarea.value += '\n\n' + summary; } else { textarea.value = summary; } showToast('Summary added to notes'); } function saveNotes() { refreshNotesSummaries(); const userNotes = document.getElementById("notesTextarea").value; const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19); const meetingDuration = document.getElementById("meetingTimer").textContent; const participantCount = Object.keys(peerConnections).length + 1; // Build participants list const participants = [myName + " (You)"]; for (const pid in peerConnections) { participants.push(peerConnections[pid].name || "Peer"); } // Build polls text let pollsText = ""; const pollKeys = Object.keys(activePolls); if (pollKeys.length) { pollsText = pollKeys.map(pid => { const p = activePolls[pid]; const total = p.total_votes || 0; const results = p.results || p.options.map(() => 0); let t = ` Q: ${p.question}${p.active ? '' : ' (ended)'}`; p.options.forEach((opt, i) => { const count = results[i] || 0; const pct = total > 0 ? Math.round(count / total * 100) : 0; t += `\n - ${opt}: ${count} vote${count !== 1 ? 's' : ''} (${pct}%)`; }); t += `\n Total votes: ${total}`; return t; }).join("\n\n"); } // Build text content let content = `Huddle - Meeting Notes\n`; content += `========================\n\n`; content += `Room: ${roomId}\n`; content += `Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}\n`; content += `Duration: ${meetingDuration}\n`; content += `Participants (${participantCount}): ${participants.join(", ")}\n\n`; if (userNotes.trim()) { content += `--- Notes ---\n${userNotes}\n\n`; } if (pollsText) { content += `--- Polls ---\n${pollsText}\n\n`; } // Breakout rooms text const brList = document.getElementById("breakoutActiveList"); if (brList && brList.children.length > 0) { content += `--- Breakout Rooms ---\n`; brList.querySelectorAll(".breakout-room-row").forEach(row => { const name = row.querySelector("strong")?.textContent || "Room"; const peers = [...row.querySelectorAll(".br-peer-chip")].map(el => el.textContent).join(", "); content += ` ${name}: ${peers || "empty"}\n`; }); content += "\n"; } // Chat log const chatMsgs = document.querySelectorAll("#chatMessages .chat-msg"); if (chatMsgs.length) { content += `--- Chat Log ---\n`; chatMsgs.forEach(msg => { const nameEl = msg.querySelector(".chat-name"); const timeEl = msg.querySelector(".chat-time"); const textEl = msg.querySelector(".chat-text"); content += ` [${timeEl?.textContent || ''}] ${nameEl?.textContent || ''}: ${textEl?.textContent || ''}\n`; }); content += "\n"; } // Save as text file const blob = new Blob([content], { type: "text/plain" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `Huddle-Notes-${roomId}-${timestamp}.txt`; a.click(); URL.revokeObjectURL(url); // Also save whiteboard image separately if it has content const canvas = document.getElementById("whiteboardCanvas"); if (canvas && canvas._initialized) { const ctx = canvas.getContext("2d"); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const hasContent = imageData.data.some((v, i) => i % 4 !== 3 && v !== 0); if (hasContent) { canvas.toBlob(function(imgBlob) { const imgUrl = URL.createObjectURL(imgBlob); const imgA = document.createElement("a"); imgA.href = imgUrl; imgA.download = `Huddle-Whiteboard-${roomId}-${timestamp}.png`; imgA.click(); URL.revokeObjectURL(imgUrl); }, "image/png"); } } showToast("Meeting notes saved!"); } // ── View Toggle (Gallery / Speaker) ───────────────────────────────────── function toggleViewMode() { viewMode = viewMode === "gallery" ? "speaker" : "gallery"; const label = document.getElementById("viewToggleLabel"); const icon = document.getElementById("viewToggleBtn").querySelector(".material-icons-round"); if (viewMode === "speaker") { label.textContent = "Speaker"; icon.textContent = "view_sidebar"; } else { label.textContent = "Gallery"; icon.textContent = "grid_view"; } applyViewMode(); } function applyViewMode() { const grid = document.getElementById("videoGrid"); grid.classList.remove("view-gallery", "view-speaker"); grid.classList.add(viewMode === "speaker" ? "view-speaker" : "view-gallery"); // In speaker mode, spotlight the pinned peer or the active speaker if (viewMode === "speaker") { const spotlightId = pinnedPeerId || findActiveSpeaker() || "local"; grid.querySelectorAll(".video-tile").forEach(tile => { tile.classList.toggle("spotlight", tile.dataset.peer === spotlightId); }); } else { grid.querySelectorAll(".video-tile").forEach(tile => { tile.classList.remove("spotlight"); }); } } function findActiveSpeaker() { let loudest = null; let loudestLevel = 0; for (const pid in audioAnalysers) { const { analyser, dataArray } = audioAnalysers[pid]; analyser.getByteFrequencyData(dataArray); const avg = dataArray.reduce((a, b) => a + b, 0) / dataArray.length; if (avg > loudestLevel && avg > 15) { loudestLevel = avg; loudest = pid; } } return loudest; } // ── Pin / Spotlight Video ─────────────────────────────────────────────── function togglePin(peerId) { if (pinnedPeerId === peerId) { pinnedPeerId = null; showToast("Unpinned video"); } else { pinnedPeerId = peerId; const name = peerConnections[peerId]?.name || "Peer"; showToast(`Pinned ${name}`); } // Update pin button styling videoGrid.querySelectorAll(".pin-btn").forEach(btn => { const tile = btn.closest(".video-tile"); btn.classList.toggle("active", tile.dataset.peer === pinnedPeerId); }); applyViewMode(); } // ── Speaker Active Indicator ──────────────────────────────────────────── function setupSpeakerDetection(peerId, stream) { try { const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); const source = audioCtx.createMediaStreamSource(stream); const analyser = audioCtx.createAnalyser(); analyser.fftSize = 256; analyser.smoothingTimeConstant = 0.5; source.connect(analyser); const dataArray = new Uint8Array(analyser.frequencyBinCount); audioAnalysers[peerId] = { analyser, dataArray, audioCtx }; } catch (e) { console.warn("[speaker] Failed to setup detection for", peerId, e); } } function cleanupSpeakerDetection(peerId) { if (audioAnalysers[peerId]) { audioAnalysers[peerId].audioCtx.close().catch(() => {}); delete audioAnalysers[peerId]; } } let speakerDetectionInterval = null; function startSpeakerDetectionLoop() { if (speakerDetectionInterval) return; speakerDetectionInterval = setInterval(() => { for (const pid in audioAnalysers) { const { analyser, dataArray } = audioAnalysers[pid]; analyser.getByteFrequencyData(dataArray); const avg = dataArray.reduce((a, b) => a + b, 0) / dataArray.length; const tile = peerConnections[pid]?.tile; if (tile) { tile.classList.toggle("speaking", avg > 15); } } // Auto-switch speaker view spotlight if (viewMode === "speaker" && !pinnedPeerId) { applyViewMode(); } }, 300); } function stopSpeakerDetectionLoop() { clearInterval(speakerDetectionInterval); speakerDetectionInterval = null; } // ── Device Selector ───────────────────────────────────────────────────── async function openDeviceSelector() { const modal = document.getElementById("deviceModal"); modal.style.display = "flex"; const devices = await navigator.mediaDevices.enumerateDevices(); const camSelect = document.getElementById("camSelect"); const micSelect = document.getElementById("micSelect"); const speakerSelect = document.getElementById("speakerSelect"); const currentVideoId = localStream?.getVideoTracks()[0]?.getSettings()?.deviceId; const currentAudioId = localStream?.getAudioTracks()[0]?.getSettings()?.deviceId; camSelect.innerHTML = devices.filter(d => d.kind === "videoinput").map(d => `` ).join(''); micSelect.innerHTML = devices.filter(d => d.kind === "audioinput").map(d => `` ).join(''); speakerSelect.innerHTML = devices.filter(d => d.kind === "audiooutput").map(d => `` ).join(''); } async function switchCamera(deviceId) { try { const newStream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: { exact: deviceId } }, audio: false, }); const newTrack = newStream.getVideoTracks()[0]; const oldTrack = localStream.getVideoTracks()[0]; if (oldTrack) { localStream.removeTrack(oldTrack); oldTrack.stop(); } localStream.addTrack(newTrack); for (const pid in peerConnections) { const sender = peerConnections[pid].pc.getSenders().find(s => s.track?.kind === "video"); if (sender) sender.replaceTrack(newTrack); } localVideo.srcObject = localStream; showToast("Camera switched"); } catch (e) { showToast("Failed to switch camera"); } } async function switchMicrophone(deviceId) { try { const newStream = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: deviceId }, echoCancellation: true, noiseSuppression: true, autoGainControl: true }, video: false, }); const newTrack = newStream.getAudioTracks()[0]; const oldTrack = localStream.getAudioTracks()[0]; if (oldTrack) { localStream.removeTrack(oldTrack); oldTrack.stop(); } localStream.addTrack(newTrack); newTrack.enabled = micEnabled; for (const pid in peerConnections) { const sender = peerConnections[pid].pc.getSenders().find(s => s.track?.kind === "audio"); if (sender) sender.replaceTrack(newTrack); } showToast("Microphone switched"); } catch (e) { showToast("Failed to switch microphone"); } } async function switchSpeaker(deviceId) { try { for (const pid in peerConnections) { const el = peerConnections[pid].videoEl; if (el.setSinkId) await el.setSinkId(deviceId); } showToast("Speaker switched"); } catch (e) { showToast("Failed to switch speaker"); } } // ── Virtual Background ────────────────────────────────────────────────── const VBG_SCENES = { office: (ctx, w, h) => { // Warm beige office with bookshelf and window ctx.fillStyle = '#f5ebe0'; ctx.fillRect(0, 0, w, h); // Floor ctx.fillStyle = '#c8a882'; ctx.fillRect(0, h*0.65, w, h*0.35); ctx.fillStyle = '#b89b78'; ctx.fillRect(0, h*0.65, w, 3); // Wall molding ctx.fillStyle = '#e8d5c0'; ctx.fillRect(0, h*0.6, w, h*0.05); // Window with light const grad = ctx.createLinearGradient(w*0.55, h*0.08, w*0.55, h*0.5); grad.addColorStop(0, '#b8d4e8'); grad.addColorStop(1, '#dceaf5'); ctx.fillStyle = '#8b7355'; ctx.fillRect(w*0.5, h*0.08, w*0.3, h*0.48); ctx.fillStyle = grad; ctx.fillRect(w*0.52, h*0.1, w*0.26, h*0.44); ctx.fillStyle = '#8b7355'; ctx.fillRect(w*0.64, h*0.08, w*0.02, h*0.48); ctx.fillStyle = '#8b7355'; ctx.fillRect(w*0.5, h*0.3, w*0.3, h*0.02); // Bookshelf ctx.fillStyle = '#6b4e37'; ctx.fillRect(w*0.05, h*0.1, w*0.25, h*0.5); for (let i = 0; i < 4; i++) { ctx.fillStyle = '#8b6b4a'; ctx.fillRect(w*0.05, h*(0.1+i*0.125), w*0.25, h*0.02); for (let j = 0; j < 5; j++) { const colors = ['#c0392b','#2980b9','#27ae60','#8e44ad','#e67e22']; ctx.fillStyle = colors[(i*5+j)%5]; ctx.fillRect(w*(0.07+j*0.045), h*(0.13+i*0.125), w*0.035, h*0.09); } } // Plant ctx.fillStyle = '#654321'; ctx.fillRect(w*0.86, h*0.45, w*0.06, h*0.2); ctx.fillStyle = '#2d7a3a'; ctx.beginPath(); ctx.arc(w*0.89, h*0.38, w*0.07, 0, Math.PI*2); ctx.fill(); ctx.fillStyle = '#35914a'; ctx.beginPath(); ctx.arc(w*0.87, h*0.34, w*0.05, 0, Math.PI*2); ctx.fill(); }, livingroom: (ctx, w, h) => { // Cozy living room with couch and lamp ctx.fillStyle = '#e8ddd0'; ctx.fillRect(0, 0, w, h); ctx.fillStyle = '#b8a089'; ctx.fillRect(0, h*0.7, w, h*0.3); // Rug ctx.fillStyle = '#8b5e3c'; ctx.fillRect(w*0.15, h*0.75, w*0.7, h*0.2); ctx.fillStyle = '#a0714f'; ctx.fillRect(w*0.18, h*0.78, w*0.64, h*0.14); // Couch ctx.fillStyle = '#4a6741'; ctx.beginPath(); ctx.roundRect(w*0.1, h*0.4, w*0.6, h*0.25, 12); ctx.fill(); ctx.fillStyle = '#3d5636'; ctx.beginPath(); ctx.roundRect(w*0.08, h*0.35, w*0.07, h*0.3, 8); ctx.fill(); ctx.beginPath(); ctx.roundRect(w*0.65, h*0.35, w*0.07, h*0.3, 8); ctx.fill(); // Cushions ctx.fillStyle = '#5a7d50'; ctx.beginPath(); ctx.roundRect(w*0.15, h*0.42, w*0.18, h*0.15, 8); ctx.fill(); ctx.beginPath(); ctx.roundRect(w*0.38, h*0.42, w*0.18, h*0.15, 8); ctx.fill(); // Lamp ctx.fillStyle = '#333'; ctx.fillRect(w*0.82, h*0.45, w*0.015, h*0.25); ctx.fillStyle = '#f0d58c'; ctx.beginPath(); ctx.moveTo(w*0.78, h*0.45); ctx.lineTo(w*0.87, h*0.45); ctx.lineTo(w*0.85, h*0.32); ctx.lineTo(w*0.80, h*0.32); ctx.closePath(); ctx.fill(); // Picture frame ctx.fillStyle = '#654321'; ctx.fillRect(w*0.3, h*0.08, w*0.2, h*0.2); ctx.fillStyle = '#87ceeb'; ctx.fillRect(w*0.32, h*0.1, w*0.16, h*0.16); ctx.fillStyle = '#2d8a4e'; ctx.fillRect(w*0.32, h*0.2, w*0.16, h*0.06); }, nature: (ctx, w, h) => { // Forest/park scene const sky = ctx.createLinearGradient(0, 0, 0, h*0.5); sky.addColorStop(0, '#87ceeb'); sky.addColorStop(1, '#b5e6f5'); ctx.fillStyle = sky; ctx.fillRect(0, 0, w, h*0.55); // Mountains ctx.fillStyle = '#6b8e7b'; ctx.beginPath(); ctx.moveTo(0,h*0.5); ctx.lineTo(w*0.2,h*0.2); ctx.lineTo(w*0.4,h*0.45); ctx.lineTo(w*0.6,h*0.15); ctx.lineTo(w*0.8,h*0.4); ctx.lineTo(w,h*0.3); ctx.lineTo(w,h*0.55); ctx.closePath(); ctx.fill(); // Ground const grass = ctx.createLinearGradient(0, h*0.5, 0, h); grass.addColorStop(0, '#4a8c5c'); grass.addColorStop(1, '#3a7048'); ctx.fillStyle = grass; ctx.fillRect(0, h*0.5, w, h*0.5); // Trees for (let i = 0; i < 6; i++) { const x = w*(0.08 + i*0.16), ty = h*0.25 + Math.sin(i*2)*h*0.1; ctx.fillStyle = '#5c3a1e'; ctx.fillRect(x-w*0.01, ty+h*0.1, w*0.02, h*0.3); ctx.fillStyle = '#2d6b3f'; ctx.beginPath(); ctx.arc(x, ty, w*0.06, 0, Math.PI*2); ctx.fill(); ctx.fillStyle = '#38854d'; ctx.beginPath(); ctx.arc(x+w*0.02, ty-h*0.02, w*0.04, 0, Math.PI*2); ctx.fill(); } // Path ctx.fillStyle = '#c4a56e'; ctx.beginPath(); ctx.moveTo(w*0.4, h); ctx.quadraticCurveTo(w*0.45, h*0.7, w*0.5, h*0.55); ctx.lineTo(w*0.53, h*0.55); ctx.quadraticCurveTo(w*0.55, h*0.7, w*0.6, h); ctx.closePath(); ctx.fill(); }, beach: (ctx, w, h) => { // Tropical beach const sky = ctx.createLinearGradient(0, 0, 0, h*0.45); sky.addColorStop(0, '#4db8e8'); sky.addColorStop(1, '#87d4f0'); ctx.fillStyle = sky; ctx.fillRect(0, 0, w, h*0.45); // Sun ctx.fillStyle = '#ffe066'; ctx.beginPath(); ctx.arc(w*0.8, h*0.12, w*0.06, 0, Math.PI*2); ctx.fill(); // Clouds ctx.fillStyle = 'rgba(255,255,255,0.7)'; ctx.beginPath(); ctx.arc(w*0.2, h*0.1, w*0.05, 0, Math.PI*2); ctx.fill(); ctx.beginPath(); ctx.arc(w*0.25, h*0.08, w*0.04, 0, Math.PI*2); ctx.fill(); // Ocean const ocean = ctx.createLinearGradient(0, h*0.4, 0, h*0.6); ocean.addColorStop(0, '#1a8fba'); ocean.addColorStop(1, '#2ba5d0'); ctx.fillStyle = ocean; ctx.fillRect(0, h*0.4, w, h*0.2); // Sand const sand = ctx.createLinearGradient(0, h*0.55, 0, h); sand.addColorStop(0, '#f0d68c'); sand.addColorStop(1, '#e8c872'); ctx.fillStyle = sand; ctx.fillRect(0, h*0.55, w, h*0.45); // Palm tree ctx.fillStyle = '#6b4226'; ctx.fillRect(w*0.12, h*0.15, w*0.025, h*0.5); ctx.fillStyle = '#228b22'; for (let a = -0.5; a < 2.7; a += 0.5) { ctx.save(); ctx.translate(w*0.133, h*0.15); ctx.rotate(a); ctx.beginPath(); ctx.ellipse(0, -h*0.08, w*0.06, h*0.02, 0, 0, Math.PI*2); ctx.fill(); ctx.restore(); } // Wave lines ctx.strokeStyle = 'rgba(255,255,255,0.3)'; ctx.lineWidth = 2; for (let i = 0; i < 3; i++) { ctx.beginPath(); for (let x = 0; x < w; x += 4) ctx.lineTo(x, h*(0.42+i*0.05)+Math.sin(x/30+i)*5); ctx.stroke(); } }, mountain: (ctx, w, h) => { // Snow-capped mountains const sky = ctx.createLinearGradient(0, 0, 0, h*0.5); sky.addColorStop(0, '#1a1a3e'); sky.addColorStop(1, '#4a3f6b'); ctx.fillStyle = sky; ctx.fillRect(0, 0, w, h*0.6); // Stars ctx.fillStyle = '#fff'; for (let i = 0; i < 30; i++) { ctx.beginPath(); ctx.arc(Math.random()*w, Math.random()*h*0.4, 1, 0, Math.PI*2); ctx.fill(); } // Mountains back ctx.fillStyle = '#3a3562'; ctx.beginPath(); ctx.moveTo(0,h*0.55); ctx.lineTo(w*0.15,h*0.2); ctx.lineTo(w*0.35,h*0.5); ctx.lineTo(w*0.5,h*0.15); ctx.lineTo(w*0.7,h*0.45); ctx.lineTo(w*0.85,h*0.25); ctx.lineTo(w,h*0.4); ctx.lineTo(w,h*0.6); ctx.closePath(); ctx.fill(); // Snow caps ctx.fillStyle = '#e8e8f0'; ctx.beginPath(); ctx.moveTo(w*0.46,h*0.15); ctx.lineTo(w*0.5,h*0.15); ctx.lineTo(w*0.54,h*0.15); ctx.lineTo(w*0.52,h*0.22); ctx.lineTo(w*0.48,h*0.22); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(w*0.13,h*0.2); ctx.lineTo(w*0.15,h*0.2); ctx.lineTo(w*0.17,h*0.2); ctx.lineTo(w*0.16,h*0.26); ctx.lineTo(w*0.14,h*0.26); ctx.closePath(); ctx.fill(); // Forest ctx.fillStyle = '#1a3a25'; ctx.fillRect(0, h*0.52, w, h*0.12); // Lake const lake = ctx.createLinearGradient(0, h*0.6, 0, h); lake.addColorStop(0, '#2a4060'); lake.addColorStop(1, '#1a2a40'); ctx.fillStyle = lake; ctx.fillRect(0, h*0.6, w, h*0.4); // Reflection ctx.fillStyle = 'rgba(90,70,120,.15)'; ctx.beginPath(); ctx.moveTo(0,h*0.65); ctx.lineTo(w*0.5,h*0.85); ctx.lineTo(w,h*0.7); ctx.lineTo(w,h*0.62); ctx.lineTo(0,h*0.62); ctx.closePath(); ctx.fill(); }, city: (ctx, w, h) => { // City skyline at dusk const sky = ctx.createLinearGradient(0, 0, 0, h*0.6); sky.addColorStop(0, '#0f1626'); sky.addColorStop(1, '#2d1b4e'); ctx.fillStyle = sky; ctx.fillRect(0, 0, w, h); // Stars ctx.fillStyle = '#fff'; for (let i = 0; i < 20; i++) { ctx.beginPath(); ctx.arc(Math.random()*w, Math.random()*h*0.3, 0.8, 0, Math.PI*2); ctx.fill(); } // Buildings const bColors = ['#1a1f35','#202540','#181d30','#252a45','#1e2338']; const bx = [0, 0.1, 0.2, 0.3, 0.42, 0.55, 0.62, 0.72, 0.82, 0.92]; const bh = [0.4, 0.55, 0.35, 0.65, 0.5, 0.7, 0.3, 0.6, 0.45, 0.38]; const bw2 = [0.1, 0.1, 0.1, 0.12, 0.13, 0.07, 0.1, 0.1, 0.1, 0.08]; bx.forEach((x, i) => { ctx.fillStyle = bColors[i%5]; ctx.fillRect(w*x, h*(1-bh[i]), w*bw2[i], h*bh[i]); // Windows ctx.fillStyle = '#ffd54f'; for (let wy = 0.05; wy < bh[i]-0.05; wy += 0.06) { for (let wx = 0.02; wx < bw2[i]-0.02; wx += 0.03) { if (Math.random() > 0.35) ctx.fillRect(w*(x+wx), h*(1-bh[i]+wy), w*0.015, h*0.03); } } }); // Road ctx.fillStyle = '#1a1a2e'; ctx.fillRect(0, h*0.88, w, h*0.12); ctx.strokeStyle = '#ffd54f'; ctx.lineWidth = 2; ctx.setLineDash([15,10]); ctx.beginPath(); ctx.moveTo(0, h*0.94); ctx.lineTo(w, h*0.94); ctx.stroke(); ctx.setLineDash([]); }, abstract: (ctx, w, h) => { // Modern abstract gradient (Teams-like) const bg = ctx.createLinearGradient(0, 0, w, h); bg.addColorStop(0, '#667eea'); bg.addColorStop(0.5, '#764ba2'); bg.addColorStop(1, '#f093fb'); ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h); // Circles ctx.globalAlpha = 0.15; ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(w*0.2, h*0.3, w*0.2, 0, Math.PI*2); ctx.fill(); ctx.beginPath(); ctx.arc(w*0.8, h*0.7, w*0.25, 0, Math.PI*2); ctx.fill(); ctx.beginPath(); ctx.arc(w*0.5, h*0.1, w*0.15, 0, Math.PI*2); ctx.fill(); ctx.globalAlpha = 0.08; ctx.beginPath(); ctx.arc(w*0.6, h*0.5, w*0.3, 0, Math.PI*2); ctx.fill(); ctx.globalAlpha = 1; }, classroom: (ctx, w, h) => { // Classroom with blackboard ctx.fillStyle = '#f0ebe0'; ctx.fillRect(0, 0, w, h); // Floor ctx.fillStyle = '#c4a87a'; ctx.fillRect(0, h*0.68, w, h*0.32); // Blackboard ctx.fillStyle = '#5a3e22'; ctx.fillRect(w*0.1, h*0.08, w*0.8, h*0.45); ctx.fillStyle = '#2a5a3a'; ctx.fillRect(w*0.12, h*0.1, w*0.76, h*0.41); // Chalk text lines ctx.strokeStyle = 'rgba(255,255,255,0.5)'; ctx.lineWidth = 1.5; for (let i = 0; i < 5; i++) { const y = h*(0.16+i*0.07); ctx.beginPath(); ctx.moveTo(w*0.16, y); ctx.lineTo(w*(0.4+Math.random()*0.3), y); ctx.stroke(); } // Chalk tray ctx.fillStyle = '#5a3e22'; ctx.fillRect(w*0.12, h*0.5, w*0.76, h*0.03); // Desk ctx.fillStyle = '#8b6b4a'; ctx.fillRect(w*0.2, h*0.62, w*0.6, h*0.04); ctx.fillRect(w*0.25, h*0.66, w*0.02, h*0.12); ctx.fillRect(w*0.73, h*0.66, w*0.02, h*0.12); // Clock ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(w*0.92, h*0.15, w*0.03, 0, Math.PI*2); ctx.fill(); ctx.strokeStyle = '#333'; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(w*0.92, h*0.15, w*0.03, 0, Math.PI*2); ctx.stroke(); }, }; async function initSegmenter() { if (selfieSegmenter) return true; try { if (typeof SelfieSegmentation === 'undefined') { console.warn('SelfieSegmentation not available, using fallback mask'); vbgUseFallback = true; return false; } showToast("Loading background model..."); selfieSegmenter = new SelfieSegmentation({ locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation/${file}` }); selfieSegmenter.setOptions({ modelSelection: 1, selfieMode: true }); selfieSegmenter.onResults((results) => { segMask = results.segmentationMask; }); // Warm up with timeout const warmup = document.createElement('canvas'); warmup.width = 4; warmup.height = 4; warmup.getContext('2d').fillRect(0, 0, 4, 4); const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 15000)); await Promise.race([selfieSegmenter.send({ image: warmup }), timeout]); showToast("Background model ready"); return true; } catch (e) { console.warn('Segmenter init failed, using fallback:', e); selfieSegmenter = null; vbgUseFallback = true; showToast("Using portrait mask (model unavailable)"); return false; } } function createFallbackMask(w, h) { const c = document.createElement('canvas'); c.width = w; c.height = h; const ctx = c.getContext('2d'); ctx.clearRect(0, 0, w, h); // Soft body-shaped silhouette with feathered edges ctx.fillStyle = 'white'; ctx.shadowColor = 'white'; ctx.shadowBlur = 35; // Head ctx.beginPath(); ctx.ellipse(w * 0.5, h * 0.18, w * 0.11, h * 0.13, 0, 0, Math.PI * 2); ctx.fill(); // Neck + shoulders + torso (extends below frame) ctx.beginPath(); ctx.moveTo(w * 0.43, h * 0.31); ctx.quadraticCurveTo(w * 0.36, h * 0.36, w * 0.12, h * 0.44); ctx.lineTo(w * 0.03, h * 0.56); ctx.lineTo(w * 0.03, h * 1.1); ctx.lineTo(w * 0.97, h * 1.1); ctx.lineTo(w * 0.97, h * 0.56); ctx.lineTo(w * 0.88, h * 0.44); ctx.quadraticCurveTo(w * 0.64, h * 0.36, w * 0.57, h * 0.31); ctx.closePath(); ctx.fill(); ctx.shadowBlur = 0; return c; } // ── Meeting Transcript Log ────────────────────────────────────────────── const meetingTranscript = []; function logTranscript(type, name, text) { meetingTranscript.push({ type, name, text, time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }), }); } // ── Speech-to-Text Captions ───────────────────────────────────────────── let captionsEnabled = false; let recognition = null; function toggleCaptions() { captionsEnabled = !captionsEnabled; const btn = document.getElementById("captionBtn"); const overlay = document.getElementById("captionsOverlay"); btn.classList.toggle("active", captionsEnabled); btn.querySelector(".material-icons-round").textContent = captionsEnabled ? "closed_caption" : "closed_caption_off"; overlay.style.display = captionsEnabled ? "" : "none"; if (captionsEnabled) { startSpeechRecognition(); } else { stopSpeechRecognition(); document.getElementById("captionsContent").innerHTML = ""; } } function startSpeechRecognition() { const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SpeechRecognition) { showToast("Speech recognition not supported in this browser"); toggleCaptions(); return; } recognition = new SpeechRecognition(); recognition.continuous = true; recognition.interimResults = true; recognition.lang = "en-US"; recognition.maxAlternatives = 1; recognition.onresult = (event) => { let interim = ""; let final = ""; for (let i = event.resultIndex; i < event.results.length; i++) { const transcript = event.results[i][0].transcript; if (event.results[i].isFinal) { final += transcript; } else { interim += transcript; } } if (final) { showCaption(myName, final); logTranscript('speech', myName, final); if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ action: "caption", text: final })); } } if (interim) { showCaption(myName, interim, true); } }; recognition.onerror = (event) => { if (event.error === "not-allowed") { showToast("Microphone permission denied for captions"); toggleCaptions(); } else if (event.error !== "no-speech" && event.error !== "aborted") { console.warn("Speech recognition error:", event.error); } }; recognition.onend = () => { if (captionsEnabled) { try { recognition.start(); } catch (e) { /* already started */ } } }; try { recognition.start(); } catch (e) { /* already started */ } showToast("Captions enabled"); } function stopSpeechRecognition() { if (recognition) { captionsEnabled = false; try { recognition.stop(); } catch (e) {} recognition = null; } } function showCaption(name, text, isInterim) { if (!captionsEnabled) return; const container = document.getElementById("captionsContent"); const existingInterim = container.querySelector(".caption-interim"); if (isInterim) { if (existingInterim) { existingInterim.innerHTML = `${escapeHtml(name)}: ${escapeHtml(text)}`; } else { const el = document.createElement("div"); el.className = "caption-line caption-interim"; el.style.opacity = "0.7"; el.innerHTML = `${escapeHtml(name)}: ${escapeHtml(text)}`; container.appendChild(el); } } else { if (existingInterim) existingInterim.remove(); const el = document.createElement("div"); el.className = "caption-line"; el.innerHTML = `${escapeHtml(name)}: ${escapeHtml(text)}`; container.appendChild(el); // Keep only last 3 final captions const finals = container.querySelectorAll(".caption-line:not(.caption-interim)"); while (finals.length > 3) finals[0].remove(); // Auto-remove after 8 seconds setTimeout(() => { if (el.parentNode) el.remove(); }, 8000); } } function vbgRenderLoop() { if (!bgBlurEnabled || !vbgTempVideo) return; const w = bgBlurCanvas.width, h = bgBlurCanvas.height; const processFrame = () => { if (!bgBlurEnabled) return; // Step 1: Draw video on person canvas vbgPersonCtx.clearRect(0, 0, w, h); vbgPersonCtx.drawImage(vbgTempVideo, 0, 0, w, h); // Step 2: Apply mask to cut out person with transparent background if (segMask && !vbgUseFallback) { // MediaPipe mask: R channel = person confidence (white=person, black=bg) vbgMaskCtx.clearRect(0, 0, w, h); vbgMaskCtx.drawImage(segMask, 0, 0, w, h); const maskData = vbgMaskCtx.getImageData(0, 0, w, h); const md = maskData.data; const len = w * h; // === A. Foreground-biased threshold + smoothstep === // Shift uncertain pixels toward foreground so head/face aren't cut out const curMask = new Uint8Array(len); for (let p = 0; p < len; p++) { let v = md[p * 4] / 255; // Bias: boost values above 0.3 toward foreground v = Math.min(1, v * 1.4 + 0.08); // Smoothstep contrast curve v = v * v * (3 - 2 * v); // Conservative threshold: keep uncertain pixels as person curMask[p] = v > 0.35 ? ((v * 255 + 0.5) | 0) : 0; } // === B. Morphological dilation (3x3) to fill gaps in head/shoulders === const dilated = new Uint8Array(len); for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { let maxVal = 0; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const ny = y + dy, nx = x + dx; if (ny >= 0 && ny < h && nx >= 0 && nx < w) { const nv = curMask[ny * w + nx]; if (nv > maxVal) maxVal = nv; } } } dilated[y * w + x] = maxVal; } } // === C. Temporal smoothing (EMA) to prevent frame flicker === if (!vbgPrevMask || vbgPrevMask.length !== len) { vbgPrevMask = dilated; } else { const alpha = 0.6; // current frame weight (lower = smoother but laggier) for (let p = 0; p < len; p++) { // Asymmetric blending: appearing is fast, disappearing is slow // This prevents face/head from vanishing on brief low-confidence frames const cur = dilated[p], prev = vbgPrevMask[p]; const a = cur >= prev ? 0.75 : 0.4; // appear fast, disappear slow vbgPrevMask[p] = (a * cur + (1 - a) * prev + 0.5) | 0; } } // === D. Write smoothed mask back as alpha === for (let p = 0; p < len; p++) { const i4 = p * 4; md[i4] = md[i4 + 1] = md[i4 + 2] = 255; md[i4 + 3] = vbgPrevMask[p]; } // === E. Blur pass for soft feathered edges === vbgTempMaskCtx.putImageData(maskData, 0, 0); vbgMaskCtx.clearRect(0, 0, w, h); vbgMaskCtx.filter = 'blur(5px)'; vbgMaskCtx.drawImage(vbgTempMaskCanvas, 0, 0); vbgMaskCtx.filter = 'none'; // Cut person from video using soft alpha mask vbgPersonCtx.globalCompositeOperation = 'destination-in'; vbgPersonCtx.drawImage(vbgMaskCanvas, 0, 0); vbgPersonCtx.globalCompositeOperation = 'source-over'; } else if (vbgFallbackMask) { // Fallback: pre-rendered body silhouette already has correct alpha vbgPersonCtx.globalCompositeOperation = 'destination-in'; vbgPersonCtx.drawImage(vbgFallbackMask, 0, 0); vbgPersonCtx.globalCompositeOperation = 'source-over'; } // Step 3: Compose → background first, then person on top bgBlurCtx.clearRect(0, 0, w, h); if (vbgMode === 'blur') { bgBlurCtx.filter = 'blur(12px)'; bgBlurCtx.drawImage(vbgTempVideo, 0, 0, w, h); bgBlurCtx.filter = 'none'; } else if (vbgSceneBg) { bgBlurCtx.drawImage(vbgSceneBg, 0, 0, w, h); } bgBlurCtx.drawImage(vbgPersonCanvas, 0, 0); requestAnimationFrame(vbgRenderLoop); }; // Send frame to segmenter if available, otherwise use fallback directly if (selfieSegmenter && !vbgUseFallback) { selfieSegmenter.send({ image: vbgTempVideo }).then(processFrame).catch(() => { processFrame(); // Use last known mask or fallback }); } else { processFrame(); } } function startVbgPipeline(mode, sceneBgCanvas) { if (!localStream) return; const videoTrack = localStream.getVideoTracks()[0]; if (!videoTrack) return; const w = 640, h = 480; bgBlurCanvas = document.createElement('canvas'); bgBlurCanvas.width = w; bgBlurCanvas.height = h; bgBlurCtx = bgBlurCanvas.getContext('2d'); vbgPersonCanvas = document.createElement('canvas'); vbgPersonCanvas.width = w; vbgPersonCanvas.height = h; vbgPersonCtx = vbgPersonCanvas.getContext('2d'); vbgMaskCanvas = document.createElement('canvas'); vbgMaskCanvas.width = w; vbgMaskCanvas.height = h; vbgMaskCtx = vbgMaskCanvas.getContext('2d'); vbgTempMaskCanvas = document.createElement('canvas'); vbgTempMaskCanvas.width = w; vbgTempMaskCanvas.height = h; vbgTempMaskCtx = vbgTempMaskCanvas.getContext('2d'); if (vbgUseFallback && !vbgFallbackMask) { vbgFallbackMask = createFallbackMask(w, h); } bgBlurEnabled = true; vbgMode = mode; vbgSceneBg = sceneBgCanvas || null; vbgTempVideo = document.createElement('video'); vbgTempVideo.srcObject = new MediaStream([videoTrack]); vbgTempVideo.muted = true; vbgTempVideo.addEventListener('loadeddata', () => { vbgRenderLoop(); }); vbgTempVideo.play(); bgBlurStream = bgBlurCanvas.captureStream(30); const bgTrack = bgBlurStream.getVideoTracks()[0]; for (const pid in peerConnections) { const sender = peerConnections[pid].pc.getSenders().find(s => s.track?.kind === 'video'); if (sender) sender.replaceTrack(bgTrack); } localVideo.srcObject = bgBlurStream; } function generateVbgThumbnails() { for (const [scene, drawFn] of Object.entries(VBG_SCENES)) { const el = document.getElementById('vbgPreview' + scene.charAt(0).toUpperCase() + scene.slice(1)); if (!el) continue; const c = document.createElement('canvas'); c.width = 80; c.height = 50; const ctx = c.getContext('2d'); drawFn(ctx, 80, 50); el.appendChild(c); } } function openVirtualBgModal() { const modal = document.getElementById("vbgModal"); modal.style.display = "flex"; // Generate thumbnails on first open if (!modal._thumbsGenerated) { generateVbgThumbnails(); modal._thumbsGenerated = true; } modal.querySelectorAll(".vbg-option").forEach(opt => { opt.classList.toggle("active", opt.dataset.bg === currentVbg); }); } async function applyVirtualBg(bgValue) { currentVbg = bgValue; // Clean up existing if (bgBlurStream) { bgBlurStream.getTracks().forEach(t => t.stop()); bgBlurStream = null; } bgBlurEnabled = false; vbgTempVideo = null; vbgSceneBg = null; vbgMode = null; vbgPrevMask = null; // Reset temporal buffer if (bgValue === "none") { const camTrack = localStream ? localStream.getVideoTracks()[0] : null; for (const pid in peerConnections) { const sender = peerConnections[pid].pc.getSenders().find(s => s.track?.kind === "video"); if (sender && camTrack) sender.replaceTrack(camTrack); } localVideo.srcObject = localStream; showToast("Background removed"); return; } // Init segmentation model on first use await initSegmenter(); if (bgValue === "blur") { startVbgPipeline('blur'); showToast("Background blur on"); return; } // Scene background if (bgValue.startsWith("scene:")) { const sceneKey = bgValue.split(":")[1]; const drawFn = VBG_SCENES[sceneKey]; if (!drawFn || !localStream) return; const sceneBg = document.createElement('canvas'); sceneBg.width = 640; sceneBg.height = 480; drawFn(sceneBg.getContext('2d'), 640, 480); startVbgPipeline('scene', sceneBg); showToast("Virtual background applied"); return; } } // ── Keyboard Shortcuts ────────────────────────────────────────────────── function setupKeyboardShortcuts() { document.addEventListener("keydown", (e) => { // Don't trigger if typing in input/textarea if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.tagName === "SELECT") return; if (!callScreen.classList.contains("active")) return; switch (e.key.toLowerCase()) { case "m": toggleMic(); break; case "v": toggleCam(); break; case "s": toggleScreenShare(); break; case "h": toggleHandRaise(); break; case "c": chatOpen = !chatOpen; chatPanel.classList.toggle("open", chatOpen); chatBtn.classList.toggle("active", chatOpen); if (chatOpen) { closeSidePanels("chatPanel"); chatInput.focus(); } break; case "r": toggleRecording(); break; case "g": toggleViewMode(); break; case "f": if (!document.fullscreenElement) { document.documentElement.requestFullscreen().catch(() => {}); } else { document.exitFullscreen().catch(() => {}); } break; case "?": document.getElementById("shortcutsModal").style.display = "flex"; break; case "escape": // Close any open modal document.querySelectorAll(".modal-overlay").forEach(m => m.style.display = "none"); break; } }); }