727 lines
24 KiB
JavaScript
727 lines
24 KiB
JavaScript
window.Kronick = window.Kronick || {};
|
|
|
|
/*
|
|
* Helper to ensure a shared spatial AudioContext exists and is running
|
|
*/
|
|
Kronick.getSpatialAudioContext = function getSpatialAudioContext() {
|
|
if (!Kronick.state.audioCtx) {
|
|
Kronick.state.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
|
}
|
|
if (Kronick.state.audioCtx.state === 'suspended') {
|
|
Kronick.state.audioCtx.resume();
|
|
}
|
|
return Kronick.state.audioCtx;
|
|
};
|
|
|
|
/*
|
|
* Tear down only the local microphone processing graph.
|
|
*/
|
|
Kronick.cleanupLocalMicProcessing = function cleanupLocalMicProcessing() {
|
|
if (Kronick.state.rawMicStream) {
|
|
Kronick.state.rawMicStream.getTracks().forEach(track => track.stop());
|
|
Kronick.state.rawMicStream = null;
|
|
}
|
|
|
|
if (Kronick.state.processedAudioContext) {
|
|
Kronick.state.processedAudioContext.close().catch(() => {});
|
|
Kronick.state.processedAudioContext = null;
|
|
}
|
|
|
|
Kronick.state.rnnoiseNode = null;
|
|
Kronick.state.rnnoiseWetGain = null;
|
|
Kronick.state.rnnoiseDryGain = null;
|
|
Kronick.state.voiceGateNode = null;
|
|
Kronick.state.currentMicDb = -80;
|
|
|
|
if (typeof Kronick.updateVoiceMeter === 'function') {
|
|
Kronick.updateVoiceMeter(-80);
|
|
}
|
|
};
|
|
|
|
/*
|
|
* Rebuild the published microphone so suppression-system changes can be
|
|
* applied without leaving and rejoining the room.
|
|
*/
|
|
Kronick.applyAudioProcessingSettings = async function applyAudioProcessingSettings() {
|
|
const room = Kronick.state.room;
|
|
if (!room?.localParticipant) return false;
|
|
|
|
const oldTrack = Kronick.state.localMicTrack;
|
|
const wasEnabled = room.localParticipant.isMicrophoneEnabled !== false;
|
|
|
|
if (oldTrack) {
|
|
try {
|
|
await room.localParticipant.unpublishTrack(oldTrack, true);
|
|
} catch (error) {
|
|
console.debug('Old microphone track was already unpublished:', error);
|
|
}
|
|
}
|
|
|
|
Kronick.cleanupLocalMicProcessing();
|
|
|
|
const newTrack = await Kronick.createProcessedMicrophoneTrack();
|
|
const publishOptions = LivekitClient.Track?.Source?.Microphone
|
|
? { source: LivekitClient.Track.Source.Microphone }
|
|
: undefined;
|
|
|
|
await room.localParticipant.publishTrack(newTrack, publishOptions);
|
|
Kronick.state.localMicTrack = newTrack;
|
|
|
|
if (!wasEnabled && typeof newTrack.mute === 'function') {
|
|
await newTrack.mute();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
/*
|
|
* Initialize dynamic RNNoise AudioWorklet & Mumble-style VAD pipeline
|
|
*/
|
|
Kronick.createProcessedMicrophoneTrack = async function createProcessedMicrophoneTrack(options = {}) {
|
|
const mode = options.noiseSuppressionMode
|
|
?? Kronick.state.noiseSuppressionMode
|
|
?? 'hybrid';
|
|
const suppressionEnabled = options.noiseSuppressionEnabled
|
|
?? Kronick.state.noiseSuppressionEnabled
|
|
?? true;
|
|
const effectiveMode = suppressionEnabled ? mode : 'off';
|
|
const useBrowserSuppression = ['browser', 'hybrid'].includes(effectiveMode);
|
|
const useRnnoise = ['rnnoise', 'hybrid'].includes(effectiveMode);
|
|
|
|
const constraints = {
|
|
echoCancellation: options.echoCancellation
|
|
?? Kronick.state.echoCancellation
|
|
?? true,
|
|
noiseSuppression: useBrowserSuppression,
|
|
autoGainControl: options.autoGainControl
|
|
?? Kronick.state.autoGainControl
|
|
?? true,
|
|
channelCount: 1,
|
|
sampleRate: 48000
|
|
};
|
|
|
|
const rawStream = await navigator.mediaDevices.getUserMedia({ audio: constraints });
|
|
const audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 48000 });
|
|
|
|
if (audioContext.state === 'suspended') {
|
|
await audioContext.resume();
|
|
}
|
|
|
|
const sourceNode = audioContext.createMediaStreamSource(rawStream);
|
|
const destinationNode = audioContext.createMediaStreamDestination();
|
|
const gateNode = audioContext.createGain();
|
|
gateNode.gain.value = Kronick.state.voiceActivationEnabled === false ? 1 : 0;
|
|
gateNode.connect(destinationNode);
|
|
|
|
Kronick.state.rnnoiseNode = null;
|
|
Kronick.state.rnnoiseWetGain = null;
|
|
Kronick.state.rnnoiseDryGain = null;
|
|
Kronick.state.voiceGateNode = gateNode;
|
|
|
|
if (useRnnoise) {
|
|
try {
|
|
await audioContext.audioWorklet.addModule('/js/rnnoise-worklet.js');
|
|
const rnnoiseNode = new AudioWorkletNode(audioContext, 'rnnoise-worklet');
|
|
const wasmResponse = await fetch('/rnnoise-wasm/rnnoise.wasm');
|
|
|
|
if (!wasmResponse.ok) {
|
|
throw new Error(`RNNoise WASM returned HTTP ${wasmResponse.status}`);
|
|
}
|
|
|
|
const wasmBytes = await wasmResponse.arrayBuffer();
|
|
rnnoiseNode.port.postMessage({ type: 'INIT_WASM', wasmBytes });
|
|
|
|
const wetGain = audioContext.createGain();
|
|
const dryGain = audioContext.createGain();
|
|
const mix = Math.max(0, Math.min(1, (Kronick.state.rnnoiseStrength ?? 100) / 100));
|
|
wetGain.gain.value = mix;
|
|
dryGain.gain.value = 1 - mix;
|
|
|
|
sourceNode.connect(rnnoiseNode);
|
|
rnnoiseNode.connect(wetGain);
|
|
sourceNode.connect(dryGain);
|
|
wetGain.connect(gateNode);
|
|
dryGain.connect(gateNode);
|
|
|
|
Kronick.state.rnnoiseNode = rnnoiseNode;
|
|
Kronick.state.rnnoiseWetGain = wetGain;
|
|
Kronick.state.rnnoiseDryGain = dryGain;
|
|
} catch (workletError) {
|
|
console.warn('RNNoise unavailable; falling back to the microphone stream:', workletError);
|
|
sourceNode.connect(gateNode);
|
|
}
|
|
} else {
|
|
sourceNode.connect(gateNode);
|
|
}
|
|
|
|
// Local VAD drives the actual outgoing gate and the sidebar activity meter.
|
|
const analyser = audioContext.createAnalyser();
|
|
analyser.fftSize = 512;
|
|
sourceNode.connect(analyser);
|
|
|
|
const audioData = new Float32Array(analyser.fftSize);
|
|
let lastSpokenTime = 0;
|
|
let lastMeterUpdate = 0;
|
|
|
|
const checkVadLevel = () => {
|
|
if (!Kronick.state.processedAudioContext || audioContext.state === 'closed') return;
|
|
|
|
analyser.getFloatTimeDomainData(audioData);
|
|
let sum = 0;
|
|
for (let i = 0; i < audioData.length; i++) {
|
|
sum += audioData[i] * audioData[i];
|
|
}
|
|
|
|
const rms = Math.sqrt(sum / audioData.length);
|
|
const db = 20 * Math.log10(rms || 1e-8);
|
|
const now = Date.now();
|
|
const threshold = Kronick.state.vadThreshold ?? -66;
|
|
const holdMs = Kronick.state.vadHoldMs ?? 200;
|
|
const voiceActivationEnabled = Kronick.state.voiceActivationEnabled !== false;
|
|
const isSpeaking = db > threshold;
|
|
|
|
if (isSpeaking) lastSpokenTime = now;
|
|
|
|
const activeVoice = !voiceActivationEnabled
|
|
|| isSpeaking
|
|
|| (now - lastSpokenTime < holdMs);
|
|
|
|
Kronick.state.isLocalVoiceActive = activeVoice;
|
|
Kronick.state.currentMicDb = db;
|
|
|
|
const targetGain = activeVoice ? 1 : 0;
|
|
gateNode.gain.setTargetAtTime(targetGain, audioContext.currentTime, activeVoice ? 0.008 : 0.025);
|
|
|
|
if (now - lastMeterUpdate >= 80 && typeof Kronick.updateVoiceMeter === 'function') {
|
|
Kronick.updateVoiceMeter(db);
|
|
lastMeterUpdate = now;
|
|
}
|
|
|
|
requestAnimationFrame(checkVadLevel);
|
|
};
|
|
|
|
Kronick.state.processedAudioContext = audioContext;
|
|
Kronick.state.rawMicStream = rawStream;
|
|
checkVadLevel();
|
|
|
|
const processedTrack = destinationNode.stream.getAudioTracks()[0];
|
|
return new LivekitClient.LocalAudioTrack(processedTrack);
|
|
};
|
|
|
|
/*
|
|
* Connect to the selected LiveKit room.
|
|
*/
|
|
Kronick.connect = async function connect() {
|
|
const roomName = document.getElementById('roomName')?.value.trim();
|
|
const userName = document.getElementById('userName')?.value.trim();
|
|
const avatarUrl = document.getElementById('avatarUrl')?.value.trim() || '';
|
|
|
|
if (window.parent !== window) {
|
|
let selected = new URLSearchParams(location.search).get('room');
|
|
try { selected = new URLSearchParams(window.parent.location.search).get('room') || selected; } catch (_) {}
|
|
if (selected && (roomName !== selected || !Kronick.account?.rooms?.some(r => r.room_name === selected))) {
|
|
alert('Wait for your assigned room to load or switch rooms from the main menu.');
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (!roomName || !userName) {
|
|
alert('Choose an assigned room.');
|
|
return;
|
|
}
|
|
|
|
if (Kronick.state.room) {
|
|
console.warn('A LiveKit room is already active.');
|
|
return;
|
|
}
|
|
|
|
|
|
Kronick.state.currentRoomName = roomName;
|
|
Kronick.saveJoinInfo(roomName, userName, avatarUrl);
|
|
|
|
const { Room, RoomEvent } = LivekitClient;
|
|
|
|
Kronick.setStatus('Connecting...', 'connecting');
|
|
Kronick.setConnectionControls('connecting');
|
|
|
|
const room = new Room();
|
|
Kronick.state.room = room;
|
|
|
|
// Ensure state maps exist
|
|
Kronick.state.participantPanners = Kronick.state.participantPanners || new Map();
|
|
Kronick.state.participantAudioSources = Kronick.state.participantAudioSources || new Map();
|
|
Kronick.state.participantGainNodes = Kronick.state.participantGainNodes || new Map();
|
|
|
|
if (typeof Kronick.initScreenShare === 'function') {
|
|
Kronick.initScreenShare(room);
|
|
}
|
|
|
|
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
|
|
if (track.kind !== 'audio') return;
|
|
|
|
if (
|
|
typeof Kronick.isScreenShareAudioPublication === 'function' &&
|
|
Kronick.isScreenShareAudioPublication(publication)
|
|
) {
|
|
return;
|
|
}
|
|
|
|
const audio = track.attach();
|
|
audio.id = `audio-${participant.sid}`;
|
|
audio.autoplay = true;
|
|
audio.playsInline = true;
|
|
// Do NOT mute this element. createMediaElementSource() reroutes its audio
|
|
// into the Web Audio graph; muting it can result in silence reaching the
|
|
// spatial panner on some browsers.
|
|
audio.muted = false;
|
|
audio.style.display = 'none';
|
|
audio.volume = 1;
|
|
|
|
document.body.appendChild(audio);
|
|
|
|
Kronick.state.participantAudioElements.set(participant.sid, audio);
|
|
const savedVolume = Kronick.getSavedVolume(participant.identity || participant.sid);
|
|
Kronick.updateVolumeSlider(participant.sid, savedVolume);
|
|
|
|
// Web Audio HRTF Spatial Panner Setup
|
|
try {
|
|
const ctx = Kronick.getSpatialAudioContext();
|
|
const sourceNode = ctx.createMediaElementSource(audio);
|
|
const gainNode = ctx.createGain();
|
|
const pannerNode = ctx.createPanner();
|
|
gainNode.gain.value = savedVolume;
|
|
|
|
pannerNode.panningModel = 'HRTF';
|
|
pannerNode.distanceModel = 'inverse';
|
|
pannerNode.refDistance = 1;
|
|
pannerNode.maxDistance = 1000;
|
|
pannerNode.rolloffFactor = Kronick.state.spatialAudioEnabled === false
|
|
? 0
|
|
: Math.max(0, (Kronick.state.spatialFalloff ?? 100) / 100);
|
|
|
|
sourceNode.connect(gainNode);
|
|
gainNode.connect(pannerNode);
|
|
pannerNode.connect(ctx.destination);
|
|
|
|
Kronick.state.participantAudioSources.set(participant.sid, sourceNode);
|
|
Kronick.state.participantGainNodes.set(participant.sid, gainNode);
|
|
Kronick.state.participantPanners.set(participant.sid, pannerNode);
|
|
|
|
if (typeof Kronick.updateSpatialAudioPosition === 'function') {
|
|
Kronick.updateSpatialAudioPosition(participant.sid);
|
|
}
|
|
} catch (spatialErr) {
|
|
console.warn('Failed to attach spatial audio panner for participant:', participant.identity, spatialErr);
|
|
}
|
|
});
|
|
|
|
room.on(RoomEvent.TrackUnsubscribed, (track, publication, participant) => {
|
|
if (
|
|
typeof Kronick.isScreenShareVideoPublication === 'function' &&
|
|
Kronick.isScreenShareVideoPublication(publication)
|
|
) {
|
|
return;
|
|
}
|
|
|
|
if (
|
|
typeof Kronick.isScreenShareAudioPublication === 'function' &&
|
|
Kronick.isScreenShareAudioPublication(publication)
|
|
) {
|
|
return;
|
|
}
|
|
|
|
track.detach().forEach(element => element.remove());
|
|
|
|
if (participant?.sid) {
|
|
Kronick.state.participantAudioElements.delete(participant.sid);
|
|
|
|
const panner = Kronick.state.participantPanners.get(participant.sid);
|
|
if (panner) {
|
|
panner.disconnect();
|
|
Kronick.state.participantPanners.delete(participant.sid);
|
|
}
|
|
|
|
const gain = Kronick.state.participantGainNodes?.get(participant.sid);
|
|
if (gain) {
|
|
gain.disconnect();
|
|
Kronick.state.participantGainNodes.delete(participant.sid);
|
|
}
|
|
|
|
const source = Kronick.state.participantAudioSources.get(participant.sid);
|
|
if (source) {
|
|
source.disconnect();
|
|
Kronick.state.participantAudioSources.delete(participant.sid);
|
|
}
|
|
}
|
|
});
|
|
|
|
room.on(RoomEvent.ParticipantConnected, participant => {
|
|
Kronick.renderParticipant(participant);
|
|
});
|
|
|
|
room.on(RoomEvent.ParticipantDisconnected, participant => {
|
|
Kronick.removeParticipant(participant);
|
|
});
|
|
|
|
room.on(RoomEvent.ActiveSpeakersChanged, speakers => {
|
|
Kronick.updateActiveSpeakers(speakers);
|
|
});
|
|
|
|
room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
|
|
let decodedData = '';
|
|
|
|
try {
|
|
decodedData = new TextDecoder().decode(payload);
|
|
} catch (error) {
|
|
console.warn('Could not decode LiveKit data:', error);
|
|
return;
|
|
}
|
|
|
|
// Native Kronic Media room playback uses a separate, versioned LiveKit topic.
|
|
if (topic === Kronick.roomPlaybackTopic) {
|
|
try {
|
|
Kronick.handleNativeRoomPlayback(JSON.parse(decodedData), participant);
|
|
} catch (error) {
|
|
console.warn('Bad native room playback message:', error);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (topic === Kronick.config.DATA_TOPIC_MEDIA) {
|
|
try {
|
|
const message = JSON.parse(decodedData);
|
|
Kronick.handleRoomMedia(message);
|
|
} catch (error) {
|
|
console.warn('Bad media message:', {
|
|
participant: participant?.identity,
|
|
data: decodedData,
|
|
error
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (topic === Kronick.config.DATA_TOPIC_CHAT) {
|
|
try {
|
|
const message = JSON.parse(decodedData);
|
|
Kronick.receiveChatMessage(message);
|
|
} catch (error) {
|
|
console.warn('Bad chat message:', {
|
|
participant: participant?.identity,
|
|
data: decodedData,
|
|
error
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
room.on(RoomEvent.ParticipantMetadataChanged, (metadata, participant) => {
|
|
Kronick.updateParticipantAvatar(participant);
|
|
});
|
|
|
|
room.on(RoomEvent.Disconnected, () => {
|
|
Kronick.cleanupRoom();
|
|
Kronick.setStatus('Disconnected');
|
|
});
|
|
|
|
try {
|
|
const tokenResponse = await fetch('/api/account-token', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'same-origin',
|
|
body: JSON.stringify({
|
|
room: roomName,
|
|
avatar: avatarUrl
|
|
})
|
|
});
|
|
|
|
let tokenData = {};
|
|
|
|
try {
|
|
tokenData = await tokenResponse.json();
|
|
} catch {
|
|
throw new Error('Token server returned an invalid response.');
|
|
}
|
|
|
|
if (!tokenResponse.ok) {
|
|
const detail =
|
|
typeof tokenData.detail === 'string'
|
|
? tokenData.detail
|
|
: tokenData.detail?.message || 'Room authentication failed.';
|
|
|
|
throw new Error(detail);
|
|
}
|
|
|
|
if (!tokenData?.token) {
|
|
throw new Error('Token server returned no token.');
|
|
}
|
|
|
|
await room.connect(Kronick.config.LIVEKIT_URL, tokenData.token);
|
|
|
|
if (typeof Kronick.updateDeleteRoomButton === 'function') {
|
|
Kronick.updateDeleteRoomButton(roomName, Boolean(tokenData.isOwner));
|
|
}
|
|
|
|
room.remoteParticipants.forEach(participant => {
|
|
Kronick.renderParticipant(participant);
|
|
});
|
|
|
|
/* Setup local processed audio with RNNoise filtering */
|
|
let microphoneEnabled = false;
|
|
|
|
try {
|
|
const localAudioTrack = await Kronick.createProcessedMicrophoneTrack();
|
|
const publishOptions = LivekitClient.Track?.Source?.Microphone
|
|
? { source: LivekitClient.Track.Source.Microphone }
|
|
: undefined;
|
|
await room.localParticipant.publishTrack(localAudioTrack, publishOptions);
|
|
Kronick.state.localMicTrack = localAudioTrack;
|
|
microphoneEnabled = true;
|
|
} catch (microphoneError) {
|
|
console.warn('Connected, but noise-suppressed microphone could not be enabled:', microphoneError);
|
|
}
|
|
|
|
Kronick.renderParticipant(room.localParticipant);
|
|
Kronick.setConnectionControls('connected');
|
|
|
|
if (typeof Kronick.updateScreenShareControls === 'function') {
|
|
Kronick.updateScreenShareControls();
|
|
}
|
|
|
|
const muteButton = document.getElementById('muteBtn');
|
|
if (muteButton) {
|
|
muteButton.innerText = microphoneEnabled ? 'Mute' : 'Enable Mic';
|
|
muteButton.classList.toggle('muted', !microphoneEnabled);
|
|
}
|
|
|
|
Kronick.setStatus(
|
|
microphoneEnabled
|
|
? `Connected to room: ${roomName}`
|
|
: `Connected to room: ${roomName} — microphone unavailable`,
|
|
microphoneEnabled ? 'connected' : 'connecting'
|
|
);
|
|
|
|
await Kronick.loadRoomChatHistory(roomName);
|
|
} catch (error) {
|
|
console.error('LiveKit connection failed:', error);
|
|
|
|
try {
|
|
room.disconnect();
|
|
} catch {
|
|
// Ignore disconnect failure.
|
|
}
|
|
|
|
if (Kronick.state.room === room) {
|
|
Kronick.cleanupRoom();
|
|
}
|
|
|
|
Kronick.setStatus(
|
|
error?.message ? `Connection failed: ${error.message}` : 'Connection failed. Check console.',
|
|
'error'
|
|
);
|
|
|
|
alert(error?.message || 'Unable to join the room.');
|
|
}
|
|
};
|
|
|
|
/*
|
|
* Update connection-related buttons.
|
|
*/
|
|
Kronick.setConnectionControls = function setConnectionControls(state) {
|
|
const joinButton = document.getElementById('joinBtn');
|
|
const muteButton = document.getElementById('muteBtn');
|
|
const leaveButton = document.getElementById('leaveBtn');
|
|
const screenShareButton = document.getElementById('screenShareBtn');
|
|
|
|
if (!joinButton || !muteButton || !leaveButton) return;
|
|
|
|
if (state === 'connecting') {
|
|
joinButton.disabled = true;
|
|
joinButton.innerText = 'Connecting...';
|
|
muteButton.disabled = true;
|
|
leaveButton.disabled = true;
|
|
|
|
if (screenShareButton) screenShareButton.disabled = true;
|
|
return;
|
|
}
|
|
|
|
if (state === 'connected') {
|
|
joinButton.disabled = true;
|
|
joinButton.innerText = 'Connected';
|
|
muteButton.disabled = false;
|
|
muteButton.innerText = 'Mute';
|
|
muteButton.classList.remove('muted');
|
|
leaveButton.disabled = false;
|
|
|
|
if (screenShareButton) screenShareButton.disabled = false;
|
|
return;
|
|
}
|
|
|
|
joinButton.disabled = false;
|
|
joinButton.innerText = 'Join Voice';
|
|
muteButton.disabled = true;
|
|
muteButton.innerText = 'Mute';
|
|
muteButton.classList.remove('muted');
|
|
leaveButton.disabled = true;
|
|
|
|
if (screenShareButton) {
|
|
screenShareButton.disabled = true;
|
|
screenShareButton.classList.remove('active');
|
|
|
|
const label = screenShareButton.querySelector('.button-label');
|
|
if (label) {
|
|
label.textContent = 'Share Screen';
|
|
} else {
|
|
screenShareButton.textContent = 'Share Screen';
|
|
}
|
|
}
|
|
};
|
|
|
|
/*
|
|
* Toggle the local microphone.
|
|
*/
|
|
Kronick.toggleMute = async function toggleMute() {
|
|
const room = Kronick.state.room;
|
|
if (!room?.localParticipant) return;
|
|
|
|
const muteButton = document.getElementById('muteBtn');
|
|
const currentlyEnabled = room.localParticipant.isMicrophoneEnabled;
|
|
|
|
if (muteButton) muteButton.disabled = true;
|
|
|
|
try {
|
|
await room.localParticipant.setMicrophoneEnabled(!currentlyEnabled);
|
|
const nowEnabled = room.localParticipant.isMicrophoneEnabled;
|
|
|
|
if (muteButton) {
|
|
muteButton.innerText = nowEnabled ? 'Mute' : 'Enable Mic';
|
|
muteButton.classList.toggle('muted', !nowEnabled);
|
|
}
|
|
|
|
Kronick.setStatus(
|
|
nowEnabled
|
|
? `Connected to room: ${Kronick.state.currentRoomName}`
|
|
: `Connected to room: ${Kronick.state.currentRoomName} — microphone muted`,
|
|
'connected'
|
|
);
|
|
} catch (error) {
|
|
console.error('Could not change microphone state:', error);
|
|
|
|
Kronick.setStatus(
|
|
`Connected to room: ${Kronick.state.currentRoomName} — microphone failed`,
|
|
'error'
|
|
);
|
|
} finally {
|
|
if (muteButton && Kronick.state.room) {
|
|
muteButton.disabled = false;
|
|
}
|
|
}
|
|
};
|
|
|
|
/*
|
|
* Disconnect from the room.
|
|
*/
|
|
Kronick.disconnect = function disconnect() {
|
|
const room = Kronick.state.room;
|
|
|
|
if (room) {
|
|
try {
|
|
room.disconnect();
|
|
} catch (error) {
|
|
console.error('Room disconnect failed:', error);
|
|
Kronick.cleanupRoom();
|
|
Kronick.setStatus('Disconnected');
|
|
}
|
|
return;
|
|
}
|
|
|
|
Kronick.cleanupRoom();
|
|
Kronick.setStatus('Disconnected');
|
|
};
|
|
|
|
/*
|
|
* Clean up every part of the active room.
|
|
*/
|
|
Kronick.cleanupRoom = function cleanupRoom() {
|
|
const activeRoom = Kronick.state.room;
|
|
|
|
if (activeRoom?.localParticipant?.isScreenShareEnabled) {
|
|
activeRoom.localParticipant
|
|
.setScreenShareEnabled(false)
|
|
.catch(error => console.debug('Screen share was already stopped:', error));
|
|
}
|
|
|
|
if (typeof Kronick.resetScreenShare === 'function') {
|
|
Kronick.resetScreenShare();
|
|
}
|
|
|
|
if (typeof Kronick.cleanupScreenShareListeners === 'function') {
|
|
Kronick.cleanupScreenShareListeners();
|
|
}
|
|
|
|
// Clean up local audio context and media streams
|
|
if (typeof Kronick.cleanupLocalMicProcessing === 'function') {
|
|
Kronick.cleanupLocalMicProcessing();
|
|
}
|
|
Kronick.state.localMicTrack = null;
|
|
|
|
// Clean up Web Audio Panners and Sources
|
|
if (Kronick.state.participantPanners) {
|
|
Kronick.state.participantPanners.forEach(panner => panner.disconnect());
|
|
Kronick.state.participantPanners.clear();
|
|
}
|
|
|
|
if (Kronick.state.participantGainNodes) {
|
|
Kronick.state.participantGainNodes.forEach(gain => gain.disconnect());
|
|
Kronick.state.participantGainNodes.clear();
|
|
}
|
|
|
|
if (Kronick.state.participantAudioSources) {
|
|
Kronick.state.participantAudioSources.forEach(source => source.disconnect());
|
|
Kronick.state.participantAudioSources.clear();
|
|
}
|
|
|
|
Kronick.state.participantStatsIntervals.forEach(interval => clearInterval(interval));
|
|
Kronick.state.participantStatsIntervals.clear();
|
|
Kronick.state.participantLevels.clear();
|
|
Kronick.state.participantRtts.clear();
|
|
|
|
Kronick.state.participantAudioElements.forEach(audio => {
|
|
try {
|
|
audio.pause();
|
|
} catch {
|
|
// Ignore audio cleanup failure.
|
|
}
|
|
audio.remove();
|
|
});
|
|
|
|
Kronick.state.participantAudioElements.clear();
|
|
|
|
document.querySelectorAll('audio[id^="audio-"]').forEach(audio => {
|
|
try {
|
|
audio.pause();
|
|
} catch {
|
|
// Ignore audio cleanup failure.
|
|
}
|
|
audio.remove();
|
|
});
|
|
|
|
const participantContainer = Kronick.getParticipantContainer();
|
|
if (participantContainer) {
|
|
participantContainer.innerHTML = '';
|
|
}
|
|
|
|
Kronick.state.nextTileX = 0;
|
|
Kronick.state.nextTileY = 0;
|
|
|
|
Kronick.showEmptyRoomMessage();
|
|
Kronick.setConnectionControls('disconnected');
|
|
|
|
if (typeof Kronick.updateDeleteRoomButton === 'function') {
|
|
Kronick.updateDeleteRoomButton('', false);
|
|
}
|
|
|
|
Kronick.state.room = null;
|
|
Kronick.state.currentRoomName = '';
|
|
};
|