Files
client/app/renderer/js/voice.js
T

311 lines
11 KiB
JavaScript

// Voice: microphone capture → core (gated by mute/deafen/PTT/open mic), core mix → speakers,
// device selection and push-to-talk keys.
import { $, setText } from './dom.js';
import { S, isConnected, ownChannel } from './state.js';
import { tp, log } from './core.js';
import { AudioEngine } from './audio/engine.js';
import { buildDeviceOptions } from './audio/devices.js';
import { toast } from './toast.js';
import { errorText, keyLabel } from './text.js';
import { t } from './i18n.js';
export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0 };
let engine = null;
let sending = false;
let burst = null;
let micTest = false;
let meterRaf = 0;
let assigningPtt = null;
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {}, savePrefs: async () => S.prefs, onOutputChanged: () => {} };
export function initVoice(h0) {
hooks = { ...hooks, ...h0 };
engine = new AudioEngine({
onFrame,
onError: (e) => toast(() => errorText(e), 'error'),
log,
});
tp.onAudio(({ pcm }) => {
voiceStats.framesPlayed += 1;
engine.pushPlayback(pcm);
});
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
window.addEventListener('blur', () => {
setPtt(false, 'window-blur');
hooks.onPtt(false);
});
window.addEventListener('focus', () => hooks.onPtt(S.ptt));
navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices());
const btn = $('#btn-ptt');
btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return;
btn.setPointerCapture(e.pointerId);
setPtt(true, 'button');
});
const release = () => setPtt(false, 'button');
btn.addEventListener('pointerup', release);
btn.addEventListener('pointercancel', release);
btn.addEventListener('lostpointercapture', release);
btn.addEventListener('keydown', (e) => {
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
e.preventDefault();
setPtt(true, 'button');
}
});
btn.addEventListener('keyup', (e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
setPtt(false);
}
});
}
/** Creates the AudioContext and applies output prefs; safe to call repeatedly. */
export async function startAudio() {
try {
await engine.init();
engine.setVoiceVolume(S.prefs.voiceVolume);
if (S.prefs.outputDeviceId) await engine.setOutputDevice(S.prefs.outputDeviceId).catch((err) => toast(() => t('message.output.device.unavailable.p0', { p0: err.message }), 'error'));
} catch (err) {
toast(() => t('message.audio.unavailable.p0', { p0: err.message }), 'error');
log('error', `audio init failed: ${err.message}`);
}
}
function channelCanTransmit() {
const ch = ownChannel();
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
}
export function shouldTransmit() {
return isConnected()
&& !S.audio.input_muted
&& !S.audio.output_muted
&& (S.prefs.transmitMode === 'open' || S.ptt)
&& channelCanTransmit();
}
function onFrame(pcm, rms, peak) {
voiceStats.level = peak;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
if (shouldTransmit()) {
tp.sendAudioFrame(new Uint8Array(pcm));
voiceStats.framesSent += 1;
if (!sending) {
sending = true;
voiceStats.bursts += 1;
burst = { frames: 0, peakMax: 0, mode: S.prefs.transmitMode };
log('debug', `voice: burst start mode=${burst.mode} focused=${document.hasFocus()} capture=${engine.capturing}`);
hooks.onTransmitChanged();
}
burst.frames += 1;
if (peak > burst.peakMax) burst.peakMax = peak;
} else if (sending) {
tp.endAudio();
sending = false;
log('debug', `voice: burst end frames=${burst.frames} peak=${burst.peakMax > 0 ? (20 * Math.log10(burst.peakMax)).toFixed(1) : '-inf'} dBFS`);
burst = null;
hooks.onTransmitChanged();
}
}
function drawMeter() {
meterRaf = 0;
const db = voiceStats.level > 0 ? 20 * Math.log10(voiceStats.level) : -100;
const pct = Math.max(0, Math.min(100, ((db + 60) / 60) * 100));
$('#mic-meter').style.width = `${pct.toFixed(0)}%`;
}
/**
* Capture runs while connected (or during the settings mic test). Stopping also cancels a start that is
* still waiting for the microphone, and a second call while one start is pending does not open another.
*/
export async function syncCapture() {
const want = isConnected() || micTest;
if (!want) {
engine.stopCapture();
if (sending) {
tp.endAudio();
sending = false;
}
return;
}
if (engine.capturing || engine.captureStarting) return;
try {
const label = await engine.startCapture({
deviceId: S.prefs.inputDeviceId,
echoCancellation: S.prefs.echoCancellation,
noiseSuppression: S.prefs.noiseSuppression,
autoGainControl: S.prefs.autoGainControl,
});
if (label !== null) refreshDevices();
} catch (err) {
if (err.code === 'device_unavailable') toast(() => errorText(err), 'error');
else toast(() => t('message.microphone.access.unavailable.p0', { p0: err.message || err.name }), 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
}
}
/**
* Re-opens the microphone with the current preferences. Also used after a failed start, so a newly chosen
* device recovers capture whenever capture is wanted (connected or mic test); otherwise nothing opens.
*/
export async function restartCapture() {
engine.stopCapture();
await syncCapture();
}
export function setMicTest(on) {
micTest = on;
if (!on) $('#mic-meter').style.width = '0%';
return syncCapture();
}
export function onOutputMuted(muted) {
if (muted) engine.flushPlayback();
}
export function setVoiceVolume(pct) {
engine.setVoiceVolume(pct);
}
/** Saved input device for capture; used by Settings and by the microphone context menu. */
export async function chooseInputDevice(deviceId) {
const saved = await hooks.savePrefs({ inputDeviceId: deviceId });
if (saved?.inputDeviceId === deviceId) await restartCapture(); // not saved: keep capturing from the stored device
await refreshDevices();
}
/** Saved output device for voice and stream audio; used by Settings and by the headphones menu. */
export async function chooseOutputDevice(deviceId) {
const saved = await hooks.savePrefs({ outputDeviceId: deviceId });
if (saved?.outputDeviceId !== deviceId) {
await refreshDevices(); // not saved: audio stays on the stored device the UI shows
return;
}
try {
await engine.setOutputDevice(deviceId);
} catch (err) {
toast(() => t('message.could.not.select.output.device.p0', { p0: err.message }), 'error');
}
hooks.onOutputChanged();
await refreshDevices();
}
export function playbackStats() {
return engine.playbackStats();
}
// ---------- devices ----------
let lastChoices = null;
/** Last enumerated choices ({input, output} from buildDeviceOptions), shared by Settings and the menus. */
export async function deviceChoices() {
await refreshDevices();
return lastChoices;
}
export async function refreshDevices() {
const status = $('#device-status');
let devices;
try {
devices = await navigator.mediaDevices.enumerateDevices();
} catch (err) {
// The menus must show this failure, not an earlier successful list.
lastChoices = { error: { name: err.name, message: err.message } };
setText(status, () => t('message.could.not.list.devices.p0.p1', { p0: err.name, p1: err.message }));
log('warn', `enumerateDevices failed: ${err.name}`);
return;
}
const input = buildDeviceOptions(devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId);
const output = buildDeviceOptions(devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId);
fillSelect($('#input-device'), input.options, S.prefs.inputDeviceId);
fillSelect($('#output-device'), output.options, S.prefs.outputDeviceId);
let text;
if (input.redacted || output.redacted) text = t('ui.the.engine.hid.the.device.list.audio');
else if (input.physical === 0 && output.physical === 0) text = t('ui.no.audio.devices.found');
else if (input.physical === 0) text = t('message.no.microphones.found.output.devices.p0', { p0: output.physical });
else if (output.physical === 0) text = t('message.microphones.p0.no.output.devices.found', { p0: input.physical });
else text = t('message.microphones.found.p0.output.devices.p1', { p0: input.physical, p1: output.physical });
setText(status, () => text);
lastChoices = { input, output, status: text };
log('info', `devices: inputs=${input.physical} outputs=${output.physical} redacted=${input.redacted || output.redacted}`);
}
function fillSelect(select, options, selected) {
select.replaceChildren(...options.map((o) => {
const opt = document.createElement('option');
opt.value = o.value;
opt.textContent = o.label;
return opt;
}));
select.value = selected || '';
}
// ---------- push-to-talk ----------
function isTextField(el) {
return el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && !['checkbox', 'radio', 'range', 'button', 'submit'].includes(el.type)) || el?.isContentEditable;
}
function onKeyDown(e) {
if (assigningPtt) {
e.preventDefault();
e.stopPropagation();
const done = assigningPtt;
assigningPtt = null;
done(e.key === 'Escape' ? null : e.code);
return;
}
if (e.code !== S.prefs?.pttCode || e.repeat) return;
if (S.prefs.transmitMode !== 'ptt') return;
if (isTextField(e.target) && e.key.length === 1) return;
setPtt(true);
}
function onKeyUp(e) {
if (e.code === S.prefs?.pttCode) setPtt(false);
}
export function setPtt(down, source = 'key') {
if (S.ptt === down) return;
S.ptt = down;
const btn = $('#btn-ptt');
btn.setAttribute('aria-pressed', String(down));
setText(btn, () => down ? t('ui.talk.now') : t('ui.hold.to.talk'));
if (S.prefs?.transmitMode === 'ptt') log('debug', `voice: ptt ${down ? 'down' : 'up'} source=${source} focused=${document.hasFocus()}`);
hooks.onPtt(down);
}
/** Resolves with a KeyboardEvent.code, or null when cancelled with Escape. */
export function capturePttKey() {
return new Promise((resolve) => {
assigningPtt = resolve;
});
}
export function transmitHint() {
if (!S.prefs) return '';
if (S.prefs.transmitMode === 'open') return t('ui.open.microphone');
// The key is read only from this window: say so whenever another window has the focus.
if (!document.hasFocus()) return t('message.window.unfocused.p0.will.not.work', { p0: keyLabel(S.prefs.pttCode) });
return t('message.key.p0', { p0: keyLabel(S.prefs.pttCode) });
}
export function isCapturing() {
return Boolean(engine && engine.capturing);
}
export function isSending() {
return sending;
}
export function channelCodecProblem() {
const ch = ownChannel();
if (!ch || channelCanTransmit()) return null;
return ch.codec;
}