Files

816 lines
23 KiB
JavaScript

window.Kronick = window.Kronick || {};
Kronick.getParticipantContainer =
function getParticipantContainer() {
return document.getElementById('participant-container');
};
Kronick.removeEmptyRoomMessage =
function removeEmptyRoomMessage() {
document.querySelector(
'#participant-container .empty-room-message'
)?.remove();
};
Kronick.showEmptyRoomMessage =
function showEmptyRoomMessage() {
const container = Kronick.getParticipantContainer();
if (!container) return;
if (
container.querySelector('.octagon')
|| container.querySelector('.empty-room-message')
) {
return;
}
const emptyMessage = document.createElement('div');
emptyMessage.className = 'empty-room-message';
emptyMessage.innerHTML = `
<div class="empty-room-icon">🎙️</div>
<h3>No participants connected</h3>
<p>Enter a room and display name, then join the voice channel.</p>
`;
container.appendChild(emptyMessage);
};
Kronick.getNextParticipantPosition =
function getNextParticipantPosition() {
const container = Kronick.getParticipantContainer();
const tileWidth = 340;
const tileHeight = 340;
const gap = 24;
const usableWidth = container?.clientWidth || window.innerWidth;
const position = {
x: Kronick.state.nextTileX,
y: Kronick.state.nextTileY
};
Kronick.state.nextTileX += tileWidth + gap;
if (
Kronick.state.nextTileX + tileWidth
> Math.max(tileWidth, usableWidth)
) {
Kronick.state.nextTileX = 0;
Kronick.state.nextTileY += tileHeight + gap;
}
return position;
};
Kronick.getAvatarFromMetadata =
function getAvatarFromMetadata(metadata) {
if (!metadata) return '';
try {
const parsed = JSON.parse(metadata);
return parsed.avatar || '';
} catch {
return '';
}
};
Kronick.updateSpatialAudioPosition =
function updateSpatialAudioPosition(sid) {
if (!Kronick.state?.participantPanners) return;
const panner = Kronick.state.participantPanners.get(sid);
if (!panner) return;
const container = Kronick.getParticipantContainer();
const tile = document.getElementById(`p-${sid}`);
if (!container || !tile) return;
const containerRect = container.getBoundingClientRect();
const tileRect = tile.getBoundingClientRect();
const containerCenterX = containerRect.left + containerRect.width / 2;
const containerCenterY = containerRect.top + containerRect.height / 2;
const tileCenterX = tileRect.left + tileRect.width / 2;
const tileCenterY = tileRect.top + tileRect.height / 2;
const normalizedX =
(tileCenterX - containerCenterX)
/ (containerRect.width / 2 || 1);
const normalizedY =
(tileCenterY - containerCenterY)
/ (containerRect.height / 2 || 1);
const spatialEnabled = Kronick.state.spatialAudioEnabled !== false;
const width = spatialEnabled
? (Kronick.state.spatialWidth ?? 100) / 100
: 0;
const depth = spatialEnabled
? (Kronick.state.spatialDepth ?? 100) / 100
: 0;
const x = normalizedX * 5 * width;
const y = -normalizedY * 2 * depth;
const z = spatialEnabled ? -2 * depth : 0;
panner.rolloffFactor = spatialEnabled
? Math.max(0, (Kronick.state.spatialFalloff ?? 100) / 100)
: 0;
const ctx = Kronick.state.audioCtx;
const currentTime = ctx ? ctx.currentTime : 0;
if (panner.positionX) {
panner.positionX.setValueAtTime(x, currentTime);
panner.positionY.setValueAtTime(y, currentTime);
panner.positionZ.setValueAtTime(z, currentTime);
} else if (panner.setPosition) {
panner.setPosition(x, y, z);
}
};
Kronick.renderParticipant =
function renderParticipant(participant) {
if (document.getElementById(`p-${participant.sid}`)) return;
Kronick.removeEmptyRoomMessage();
const div = document.createElement('div');
div.className = 'octagon participant-card';
div.id = `p-${participant.sid}`;
const identity = participant.identity || 'Unknown';
const participantKey = identity || participant.sid;
const isLocal = participant === Kronick.state.room?.localParticipant;
const avatar = Kronick.getAvatarFromMetadata(participant.metadata);
const savedPosition = Kronick.getSavedPosition(participantKey);
const position = savedPosition || Kronick.getNextParticipantPosition();
div.style.left = `${position.x}px`;
div.style.top = `${position.y}px`;
const avatarHtml = avatar
? `
<img
class="avatar"
src="${Kronick.escapeAttribute(avatar)}"
alt="${Kronick.escapeAttribute(identity)}"
onerror="this.style.display='none';"
>
`
: `
<div class="avatar-fallback">
${Kronick.escapeHtml(identity)}
</div>
`;
const volumeHtml = isLocal
? ''
: `
<div class="volume-overlay">
<span>Volume</span>
<input
id="volume-${participant.sid}"
type="range"
min="0"
max="100"
value="100"
aria-label="Volume for ${Kronick.escapeAttribute(identity)}"
>
</div>
`;
div.innerHTML = `
${avatarHtml}
<div class="name-overlay">
${Kronick.escapeHtml(identity)}
</div>
<div
class="stats-overlay"
id="stats-${participant.sid}"
>
RTT: -- ms | Level: 0%
</div>
${volumeHtml}
<div
class="meter-fill"
id="meter-${participant.sid}"
></div>
`;
Kronick.getParticipantContainer()?.appendChild(div);
if (!isLocal) {
const volumeSlider = document.getElementById(`volume-${participant.sid}`);
if (volumeSlider) {
const stopPropagation = event => event.stopPropagation();
volumeSlider.addEventListener('pointerdown', stopPropagation);
volumeSlider.addEventListener('mousedown', stopPropagation);
volumeSlider.addEventListener('click', stopPropagation);
volumeSlider.addEventListener('input', event => {
Kronick.setParticipantVolume(
participant.sid,
participantKey,
event.currentTarget.value
);
});
}
}
Kronick.makeDraggable(div, participantKey, participant.sid);
Kronick.makeParticipantResizable(div, participantKey, participant.sid);
Kronick.state.participantLevels.set(participant.sid, 0);
Kronick.state.participantRtts.set(participant.sid, '--');
if (!isLocal) {
const savedVolume = Kronick.getSavedVolume(participantKey);
Kronick.updateVolumeSlider(
participant.sid,
savedVolume
);
Kronick.setParticipantVolume(
participant.sid,
participantKey,
savedVolume * 100
);
}
Kronick.updateSpatialAudioPosition(participant.sid);
Kronick.updateParticipantStats(
participant
);
const interval = setInterval(async () => {
await Kronick.updateParticipantStats(participant);
}, 2000);
Kronick.state.participantStatsIntervals.set(participant.sid, interval);
};
Kronick.makeDraggable =
function makeDraggable(element, positionKey, sid) {
let isDragging = false;
let startMouseX = 0;
let startMouseY = 0;
let startLeft = 0;
let startTop = 0;
element.addEventListener('mousedown', event => {
if (event.button !== 0 || event.target.closest('input')) return;
isDragging = true;
startMouseX = event.clientX;
startMouseY = event.clientY;
startLeft = parseInt(element.style.left || '0', 10);
startTop = parseInt(element.style.top || '0', 10);
element.style.zIndex = '999';
document.body.classList.add('participant-dragging');
event.preventDefault();
});
document.addEventListener('mousemove', event => {
if (!isDragging) return;
const container = Kronick.getParticipantContainer();
const dx = event.clientX - startMouseX;
const dy = event.clientY - startMouseY;
// No boundary: the tile may go anywhere in the window. Only a small
// strip is kept on screen so it can always be grabbed back.
const rect = container
? container.getBoundingClientRect()
: {left: 0, top: 0};
const keep = 40;
const minLeft = keep - element.offsetWidth - rect.left;
const maxLeft = window.innerWidth - keep - rect.left;
const minTop = keep - element.offsetHeight - rect.top;
const maxTop = window.innerHeight - keep - rect.top;
const newLeft = Math.max(minLeft, Math.min(maxLeft, startLeft + dx));
const newTop = Math.max(minTop, Math.min(maxTop, startTop + dy));
element.style.left = `${newLeft}px`;
element.style.top = `${newTop}px`;
if (sid) Kronick.updateSpatialAudioPosition(sid);
});
document.addEventListener('mouseup', () => {
if (!isDragging) return;
isDragging = false;
element.style.zIndex = '';
document.body.classList.remove('participant-dragging');
Kronick.savePosition(positionKey, {
x: parseInt(element.style.left || '0', 10),
y: parseInt(element.style.top || '0', 10)
});
if (sid) Kronick.updateSpatialAudioPosition(sid);
});
};
Kronick.updateParticipantStats =
async function updateParticipantStats(participant) {
if (!participant) {
return;
}
/*
* LiveKit does not always expose the same stats path for
* local and remote participants. Try the public track API
* first, then the sender, then the underlying publisher PC
* as a guarded final fallback for our own participant.
*/
const publications = Array.from(
participant.getTrackPublications?.().values?.()
|| []
);
const publication =
publications.find(
pub =>
pub.track
&& (
pub.kind === 'audio'
|| pub.track.kind === 'audio'
)
)
|| publications.find(
pub => pub.track
);
const track =
publication?.track;
let stats =
null;
try {
if (
track
&& typeof track.getRTCStatsReport
=== 'function'
) {
stats =
await track.getRTCStatsReport();
}
if (
!stats
&& track?.sender
&& typeof track.sender.getStats
=== 'function'
) {
stats =
await track.sender.getStats();
}
/*
* Local participant fallback. LiveKit's internal PC
* shape can vary by version, so every access is guarded.
*/
const isLocal =
participant
=== Kronick.state.room
?.localParticipant;
if (
!stats
&& isLocal
) {
const publisher =
Kronick.state.room
?.engine
?.pcManager
?.publisher;
const pc =
publisher?._pc
|| publisher?.pc
|| publisher;
if (
pc
&& typeof pc.getStats
=== 'function'
) {
stats =
await pc.getStats();
}
}
let rtt =
null;
stats?.forEach?.(
report => {
if (
report.type
=== 'candidate-pair'
&& (
report.state
=== 'succeeded'
|| report.nominated
)
&& typeof report
.currentRoundTripTime
=== 'number'
) {
rtt =
report
.currentRoundTripTime;
}
if (
report.type
=== 'remote-inbound-rtp'
&& typeof report
.roundTripTime
=== 'number'
) {
rtt =
report.roundTripTime;
}
}
);
if (
rtt !== null
) {
Kronick.state
.participantRtts
.set(
participant.sid,
Math.round(
rtt * 1000
)
);
}
/*
* Keep our own level live even when the active-speaker
* event does not include the local participant.
*/
if (
typeof participant.audioLevel
=== 'number'
) {
Kronick.state
.participantLevels
.set(
participant.sid,
Math.round(
participant.audioLevel
* 100
)
);
}
} catch (err) {
console.debug(
'Participant RTT unavailable:',
participant.identity
|| participant.sid,
err
);
}
Kronick.updateStatsOverlay(
participant.sid
);
};
Kronick.updateActiveSpeakers =
function updateActiveSpeakers(speakers) {
document.querySelectorAll('.meter-fill').forEach(meter => {
meter.style.width = '0%';
});
document.querySelectorAll('.octagon').forEach(card => {
card.classList.remove('speaking');
});
Kronick.state.participantLevels.forEach((_, sid) => {
Kronick.state.participantLevels.set(sid, 0);
});
speakers.forEach(speaker => {
const level = Math.round((speaker.audioLevel || 0) * 100);
Kronick.state.participantLevels.set(speaker.sid, level);
const meter = document.getElementById(`meter-${speaker.sid}`);
const card = document.getElementById(`p-${speaker.sid}`);
if (meter) meter.style.width = `${level}%`;
if (card && level > 5) card.classList.add('speaking');
Kronick.updateStatsOverlay(speaker.sid);
});
};
Kronick.updateStatsOverlay =
function updateStatsOverlay(sid) {
const stats = document.getElementById(`stats-${sid}`);
if (!stats) return;
const rtt = Kronick.state.participantRtts.get(sid) || '--';
const level = Kronick.state.participantLevels.get(sid) || 0;
stats.textContent = `RTT: ${rtt} ms | Level: ${level}%`;
};
Kronick.setParticipantVolume =
function setParticipantVolume(sid, participantKey, value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) return;
const volume = Math.max(0, Math.min(1, numericValue / 100));
localStorage.setItem(
`volume-${participantKey}`,
String(volume)
);
const room = Kronick.state.room;
const participant = room?.remoteParticipants?.get(sid);
// 1) Ask LiveKit itself to apply the per-participant volume.
if (participant) {
try {
if (typeof participant.setVolume === 'function') {
participant.setVolume(volume);
}
} catch (error) {
console.warn(
'LiveKit participant volume failed:',
participantKey,
error
);
}
try {
const microphoneSource =
LivekitClient?.Track?.Source?.Microphone;
let micPublication = null;
if (
microphoneSource
&& typeof participant.getTrackPublication === 'function'
) {
micPublication = participant.getTrackPublication(
microphoneSource
);
}
if (!micPublication) {
const publications = Array.from(
participant.getTrackPublications().values()
);
micPublication = publications.find(publication =>
publication?.source === microphoneSource
|| publication?.track?.kind === 'audio'
);
}
const remoteTrack = micPublication?.track;
if (
remoteTrack
&& typeof remoteTrack.setVolume === 'function'
) {
remoteTrack.setVolume(volume);
}
} catch (error) {
console.warn(
'LiveKit track volume failed:',
participantKey,
error
);
}
}
// 2) Apply the same value to our WebAudio gain node.
const gainNode = Kronick.state.participantGainNodes?.get(sid);
if (gainNode) {
try {
const ctx = gainNode.context;
gainNode.gain.cancelScheduledValues(ctx.currentTime);
gainNode.gain.setValueAtTime(volume, ctx.currentTime);
} catch (error) {
console.warn(
'GainNode volume failed:',
participantKey,
error
);
}
}
// 3) Keep the attached HTML audio element in sync as a fallback.
const audio = Kronick.state.participantAudioElements?.get(sid);
if (audio) {
try {
audio.volume = volume;
audio.muted = volume === 0;
} catch (error) {
console.warn(
'Audio element volume failed:',
participantKey,
error
);
}
}
console.log('Participant volume applied:', {
sid,
participantKey,
volume,
livekitParticipant: Boolean(participant),
gain: gainNode ? gainNode.gain.value : null,
audioVolume: audio ? audio.volume : null,
audioMuted: audio ? audio.muted : null
});
};
Kronick.updateVolumeSlider =
function updateVolumeSlider(sid, volume) {
const slider = document.getElementById(`volume-${sid}`);
if (slider) {
slider.value = Math.round(volume * 100);
}
};
Kronick.updateParticipantAvatar =
function updateParticipantAvatar(participant) {
const card = document.getElementById(`p-${participant.sid}`);
if (!card) return;
const avatar = Kronick.getAvatarFromMetadata(participant.metadata);
const identity = participant.identity || 'Unknown';
card.querySelector('.avatar')?.remove();
card.querySelector('.avatar-fallback')?.remove();
const nameOverlay = card.querySelector('.name-overlay');
if (avatar) {
const img = document.createElement('img');
img.className = 'avatar';
img.src = avatar;
img.alt = identity;
img.onerror = () => {
img.style.display = 'none';
};
card.insertBefore(img, nameOverlay);
} else {
const fallback = document.createElement('div');
fallback.className = 'avatar-fallback';
fallback.textContent = identity;
card.insertBefore(fallback, nameOverlay);
}
};
Kronick.removeParticipant =
function removeParticipant(participant) {
document.getElementById(`p-${participant.sid}`)?.remove();
const interval = Kronick.state.participantStatsIntervals.get(participant.sid);
if (interval) {
clearInterval(interval);
Kronick.state.participantStatsIntervals.delete(participant.sid);
}
Kronick.state.participantLevels.delete(participant.sid);
Kronick.state.participantRtts.delete(participant.sid);
const audio = Kronick.state.participantAudioElements.get(participant.sid);
if (audio) {
try { audio.pause(); } catch {}
audio.remove();
}
Kronick.state.participantAudioElements.delete(participant.sid);
const panner = Kronick.state.participantPanners?.get(participant.sid);
if (panner) {
try { panner.disconnect(); } catch {}
Kronick.state.participantPanners.delete(participant.sid);
}
const gainNode = Kronick.state.participantGainNodes?.get(participant.sid);
if (gainNode) {
try { gainNode.disconnect(); } catch {}
Kronick.state.participantGainNodes.delete(participant.sid);
}
const sourceNode = Kronick.state.participantAudioSources?.get(participant.sid);
if (sourceNode) {
try { sourceNode.disconnect(); } catch {}
Kronick.state.participantAudioSources.delete(participant.sid);
}
Kronick.showEmptyRoomMessage();
};
window.addEventListener('resize', () => {
if (Kronick.state?.participantPanners) {
Kronick.state.participantPanners.forEach((_, sid) => {
Kronick.updateSpatialAudioPosition(sid);
});
}
});
Kronick.makeParticipantResizable =
function makeParticipantResizable(element, participantKey, sid) {
if (!element) return;
const storageKey = `participantSize-${participantKey}`;
try {
const saved = JSON.parse(localStorage.getItem(storageKey) || 'null');
if (saved?.width) element.style.width = `${saved.width}px`;
if (saved?.height) element.style.height = `${saved.height}px`;
} catch {}
const handle = document.createElement('div');
handle.className = 'participant-resize-handle';
handle.title = 'Resize avatar';
handle.setAttribute('aria-label', 'Resize participant avatar');
element.appendChild(handle);
let active = false;
let sx = 0;
let sy = 0;
let sw = 0;
let sh = 0;
handle.addEventListener('pointerdown', event => {
active = true;
sx = event.clientX;
sy = event.clientY;
const rect = element.getBoundingClientRect();
sw = rect.width;
sh = rect.height;
handle.setPointerCapture?.(event.pointerId);
event.stopPropagation();
event.preventDefault();
});
handle.addEventListener('pointermove', event => {
if (!active) return;
const maxW = Math.max(
180,
(Kronick.getParticipantContainer()?.clientWidth || window.innerWidth) - 20
);
const width = Math.min(
maxW,
Math.max(180, sw + event.clientX - sx)
);
const height = Math.min(
700,
Math.max(140, sh + event.clientY - sy)
);
element.style.width = `${width}px`;
element.style.height = `${height}px`;
if (sid) Kronick.updateSpatialAudioPosition(sid);
});
const stop = () => {
if (!active) return;
active = false;
localStorage.setItem(storageKey, JSON.stringify({
width: Math.round(element.getBoundingClientRect().width),
height: Math.round(element.getBoundingClientRect().height)
}));
if (sid) Kronick.updateSpatialAudioPosition(sid);
};
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
};