Files
client/app/renderer/js/voice.js
T
omar c75c8f3d74
release / linux-x64 (push) Failing after 59s
ci / linux-x64 (push) Failing after 1m9s
ci / linux-arm64-cross (push) Failing after 4m15s
release / linux-arm64 (push) Successful in 4m36s
release / appimage-startup (push) Skipped
release / publish (push) Skipped
release: prepare v0.1.5 verified account-free snapshot
2026-11-02 10:50:54 +03:00

581 lines
24 KiB
JavaScript

// Voice: microphone capture → the input connection's core (gated by mute/deafen/PTT/open mic), every
// connection's received voice → one mixer → speakers, device selection and push-to-talk keys.
//
// Several servers can be connected at once. Exactly one stream is captured, and it goes only to the input
// connection (state.inputConnection(), official FindAudioInputServerConnectionHandler); which server is on
// screen does not matter. Each connection's core has its own transmit mode, acknowledged separately.
import { $, setText } from './dom.js';
import { S, on, emit, ownChannel, inputConnection, connectionById, connectionList, isAlive } from './state.js';
import { tp, log, callOn } from './core.js';
import { AudioEngine } from './audio/engine.js';
import { buildDeviceOptions } from './audio/devices.js';
import { toast } from './toast.js';
import { errorText } from './text.js';
import { t } from './i18n.js';
import { deviceProfile, captureDenoiseLevel, transmitConfig, transmitKey, PushToTalkGate } from './audio/profiles.js';
import { whisperHold } from './whisper.js';
import { configureNotifications } from './audio/notify-output.js';
import { notify } from './notifications.js';
import { DeviceTest } from './audio/device-test.js';
const pttGate = new PushToTalkGate();
// Push-to-talk holders: 'key' (Audio PTT key), 'button' (footer button) and keybind holders
// `keybind:<bindingId>:<local|global>`. PTT is down while any holder is down. Window focus loss
// releases only window-scoped holders; a global keybind keeps PTT until its own release.
const pttHolders = new Set();
const windowScopedHolder = (holder) => holder === 'key' || holder === 'button' || holder.endsWith(':local');
// Push-to-mute holders (official PushToMute = inputDeactivated): while any is held nothing is forwarded.
// The user's mute flags are never touched, so releasing restores exactly what the user chose meanwhile.
const inputDeactivatedHolders = new Set();
// framesForwarded counts PCM frames handed to a core; whether voice was sent is the connection's audio.transmitting.
export const voiceStats = { framesForwarded: 0, forwardRuns: 0, framesPlayed: 0, level: 0 };
let engine = null;
let mutedSpeech = false;
let forwarding = false;
let forwardRun = null;
let micTest = false;
let deviceTestActive = false;
const deviceTest = new DeviceTest({
play: (samples, ended, isCurrent) => engine.playDeviceTest(samples, ended, isCurrent, S.prefs.outputDeviceId),
changed: (state) => { engine?.discardCapturedFrames(); emit('device-test', { ...state, active: deviceTestActive }); },
});
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,
});
on('voice-boundary', captureBoundary);
on('input', () => clearDeviceTest());
on('audio_state', (_event, conn) => { if (conn?.audio.input_muted || conn?.audio.output_muted) clearDeviceTest(); });
for (const event of ['audio_state', 'input', 'connection-closed']) on(event, () => {
const conn = inputConnection();
if (!conn || conn.audio.input_muted || conn.audio.output_muted) { pttGate.reset(); S.ptt = false; captureBoundary(); }
engine.setPlaybackEnabled(connectionList().some((c) => c.conn.state === 'connected' && !c.audio.output_muted));
engine.setTransmitting(Boolean(conn?.audio.transmitting));
});
window.addEventListener('keydown', (e) => { if (!e.repeat && e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) engine.typingHit(); });
tp.onAudio(({ connectionId, pcm }) => {
const conn = connectionById(connectionId);
// Late frames of a closed connection, or of a server muted for output, are not played.
if (!conn || conn.audio.output_muted) return;
voiceStats.framesPlayed += 1;
engine.pushPlayback(pcm, connectionId);
});
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
window.addEventListener('blur', () => {
setPtt(false, 'window-blur');
hooks.onPtt(S.ptt);
});
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, 'button');
}
});
}
/** Creates the AudioContext and applies output prefs; safe to call repeatedly. */
export async function startAudio() {
try {
await engine.init();
engine.setOutputLevelDb(S.prefs.outputLevelDb);
if (S.prefs.outputDeviceId) await engine.setOutputDevice(S.prefs.outputDeviceId).catch((err) => toast(() => t('message.output.device.unavailable.p0', { p0: err.message }), 'error'));
await applyVoicePreferences();
} catch (err) {
toast(() => t('message.audio.unavailable.p0', { p0: err.message }), 'error');
log('error', `audio init failed: ${err.message}`);
}
}
function channelCanTransmit(conn) {
const ch = ownChannel(conn);
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
}
// Transmit mode confirmed by each connection's core (`set_transmit`): null until acknowledged. Frames are
// forwarded only when it matches what the preferences ask for, so audio never reaches a core under the wrong
// mode — a new or restarted core gets nothing until it has acknowledged the mode.
// "direct": the core sends every forwarded frame (push to talk, open microphone). "vad": the core's voice
// detector decides, so frames are forwarded continuously and only speech is sent.
// Every request and every core restart bumps the connection's epoch; only the answer to the latest request may
// change its mode, so an older answer (even for the same settings, or from a previous core) never re-enables
// forwarding while a newer change is still on its way.
const txStates = new WeakMap();
function txState(conn) {
let state = txStates.get(conn);
if (!state) txStates.set(conn, (state = { mode: null, epoch: 0, pendingKey: null, failed: false }));
return state;
}
function wantedCoreTx() { return transmitConfig(S.prefs); }
const txKey = transmitKey;
// Connection main currently routes captured frames to (acknowledged by connections:set-input).
let routedInputId = null;
let routeRequest = 0;
/** Stops forwarding at once (audio_end: the core ends any talk spurt and, in voice activation, forgets the audio). */
function stopForwarding() {
if (!forwarding) return;
tp.endAudio();
forwarding = false;
log('debug', `voice: forwarding end frames=${forwardRun.frames} peak=${forwardRun.peakMax > 0 ? (20 * Math.log10(forwardRun.peakMax)).toFixed(1) : '-inf'} dBFS`);
forwardRun = null;
hooks.onTransmitChanged();
}
function captureBoundary() {
stopForwarding();
// Also end native preroll when no frame had reached the renderer forwarding counter yet.
tp.endAudio();
engine?.discardCapturedFrames();
}
/**
* Makes main route captured audio to the current input connection. Forwarding stops first and stays off until
* main has switched, so no frame of a talk spurt reaches the previous server after the change.
*/
export async function syncInputRoute() {
const want = inputConnection()?.id ?? null;
if (want === routedInputId) return;
whisperHold.release();
pttGate.reset();
captureBoundary();
routedInputId = null;
const request = ++routeRequest;
const result = await tp.setInputConnection(want);
if (request !== routeRequest) return; // superseded by a newer change
routedInputId = result?.ok ? result.input : null;
if (routedInputId !== (inputConnection()?.id ?? null)) void syncInputRoute();
hooks.onTransmitChanged();
}
/**
* Asks a connection's core (default: every connection) to use the transmit mode the preferences select.
* Nothing is forwarded to it until the core has acknowledged; a failure leaves the mode unapplied (nothing is
* sent) and is shown, never replaced by another mode.
*/
export async function applyTransmitMode(conn) {
if (!S.prefs) return;
if (conn === undefined) {
await Promise.all(connectionList().filter((c) => c.core.status === 'ready').map((c) => applyTransmitMode(c)));
return;
}
if (!isAlive(conn)) return;
const tx = txState(conn);
const want = wantedCoreTx();
const key = txKey(want);
if (tx.pendingKey === key) return; // the latest request already asks for exactly this
if (tx.pendingKey === null && txKey(tx.mode) === key && !tx.failed) return;
const epoch = ++tx.epoch;
tx.mode = null;
tx.failed = false;
if (inputConnection() === conn) stopForwarding();
tx.pendingKey = key;
try {
const result = await callOn(conn.id, 'set_transmit', want);
if (epoch !== tx.epoch) return; // superseded, or the core restarted
tx.mode = result;
log('info', `voice: ${conn.id} transmit mode ${result.mode}${result.sensitivity ? ` (${result.sensitivity})` : ''}`);
} catch (err) {
if (epoch !== tx.epoch || !isAlive(conn)) return;
tx.failed = true;
log('error', `voice: ${conn.id} set_transmit failed: ${err.code} ${err.message}`);
toast(() => t('error.transmit_mode', { detail: errorText(err) }), 'error');
} finally {
if (epoch === tx.epoch) {
tx.pendingKey = null;
hooks.onTransmitChanged();
}
}
}
/** A connection's core stopped or restarted: its transmit mode is unknown, and answers from before are void. */
export function forgetCoreTransmitMode(conn) {
const tx = txState(conn);
tx.epoch += 1;
tx.mode = null;
tx.pendingKey = null;
tx.failed = false;
if (routedInputId === conn.id) {
forwarding = false;
forwardRun = null;
}
}
/** The connection was closed: drop its playback ring; its transmit state goes with the record. */
export function removeConnection(conn) {
engine?.removePlaybackStream(conn.id);
}
/** Whether captured frames go to a core right now (not whether voice is sent: see audio.transmitting). */
export function shouldForward() {
if (deviceTestActive || deviceTest.playing) return false;
if (inputDeactivatedHolders.size > 0) return false;
const conn = inputConnection();
if (!conn || conn.id !== routedInputId) return false;
if (conn.audio.input_muted || conn.audio.output_muted || !channelCanTransmit(conn)) return false;
if (whisperHold.held) return whisperHold.epoch(conn) !== null;
if (txKey(txState(conn).mode) !== txKey(wantedCoreTx())) return false;
return !S.prefs.pttEnabled || pttGate.open;
}
function onFrame(pcm, rms, peak) {
voiceStats.level = peak;
const conn = inputConnection();
const talkingMuted = Boolean(conn?.audio.input_muted && peak >= 0.03);
if (talkingMuted && !mutedSpeech) notify('talking_while_muted', conn);
mutedSpeech = talkingMuted;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
if (micTest) {
deviceTest.push(pcm);
if (!deviceTest.recording) void setMicTest(false);
stopForwarding();
return;
}
if (shouldForward()) {
tp.sendAudioFrame(new Uint8Array(pcm), whisperHold.epoch(inputConnection()) ?? undefined);
voiceStats.framesForwarded += 1;
if (!forwarding) {
forwarding = true;
voiceStats.forwardRuns += 1;
forwardRun = { frames: 0, peakMax: 0, mode: whisperHold.held ? 'whisper' : wantedCoreTx().mode };
log('debug', `voice: forwarding start mode=${forwardRun.mode} focused=${document.hasFocus()} capture=${engine.capturing}`);
hooks.onTransmitChanged();
}
forwardRun.frames += 1;
if (peak > forwardRun.peakMax) forwardRun.peakMax = peak;
} else {
stopForwarding();
}
}
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 = inputConnection() !== null || micTest;
if (!want) {
engine.stopCapture();
stopForwarding();
return;
}
if (engine.capturing || engine.captureStarting) return;
try {
const label = await engine.startCapture({
deviceId: S.prefs.inputDeviceId,
echoCancellation: deviceProfile(S.prefs, 'output').aec,
autoGainControl: deviceProfile(S.prefs, 'input').agc,
denoiseLevel: captureDenoiseLevel(S.prefs),
});
if (label !== null) refreshDevices();
} catch (err) {
if (micTest) { micTest = false; deviceTestActive = false; deviceTest.clear(); }
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();
stopForwarding();
await syncCapture();
}
export async function setMicTest(on) {
whisperHold.release();
pttGate.reset();
captureBoundary();
micTest = on;
if (on) { deviceTestActive = true; deviceTest.start(); }
else { deviceTest.finish(); $('#mic-meter').style.width = '0%'; }
await syncCapture();
}
export const deviceTestState = () => ({ ...deviceTest.state(), active: deviceTestActive });
export async function playDeviceTest() {
await setMicTest(false);
captureBoundary();
try { return await deviceTest.playback(); }
catch (e) { toast(() => errorText(e), 'error'); return false; }
}
export function clearDeviceTest() {
const wasCapturingTest = micTest;
micTest = false;
deviceTestActive = false;
deviceTest.clear();
$('#mic-meter').style.width = '0%';
captureBoundary();
return wasCapturingTest ? syncCapture() : Promise.resolve();
}
/** Output muted: drop buffered voice of that connection (or of every connection without `conn`). */
export function onOutputMuted(muted, conn) {
if (muted) engine.flushPlayback(conn?.id);
}
export function setOutputLevelDb(db) { engine.setOutputLevelDb(db); }
export async function applyVoicePreferences({ restart = false } = {}) {
if (!engine || !S.prefs?.inputDsp) return;
await clearDeviceTest();
captureBoundary();
pttGate.reset();
const output = deviceProfile(S.prefs, 'output');
engine.setOutputLevelDb(S.prefs.outputLevelDb);
engine.setPlaybackDsp(output);
engine.setTypingEnabled(deviceProfile(S.prefs, 'input').typing);
// A level change applies live (suppressor reset); switching noise reduction on or off rebuilds capture.
const denoiseLevel = captureDenoiseLevel(S.prefs);
const denoiseSwitched = engine.capturing && engine.captureDenoising !== (denoiseLevel !== null);
engine.setDenoiseLevel(denoiseLevel);
engine.setPlaybackEnabled(connectionList().some((c) => c.conn.state === 'connected' && !c.audio.output_muted));
configureNotifications({ deviceId: S.prefs.notificationDeviceId, levelDb: S.prefs.notificationLevelDb, voiceDeviceId: S.prefs.outputDeviceId,
logger: (level, message) => { log(level, message); if (level === 'warn') toast(message, 'error'); } });
await Promise.all(connectionList().filter((c) => c.core.status === 'ready').map(async (conn) => {
await applyTransmitMode(conn);
try { await callOn(conn.id, 'set_playback_dsp', { agc: output.agc }); } catch (e) { toast(() => errorText(e), 'error'); }
}));
if (restart || denoiseSwitched) await restartCapture();
}
/** 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 applyVoicePreferences({ restart: true });
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 applyVoicePreferences({ restart: true });
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');
status.hidden = false;
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);
status.hidden = !input.redacted && !output.redacted && input.physical > 0 && output.physical > 0;
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.name ?? o.label;
if (o.caption) opt.dataset.caption = o.caption;
return opt;
}));
select.value = selected || '';
showDeviceCaption(select);
}
const captionedSelects = new WeakSet();
/** audio-device-selector's small right-hand text: the device the "default" alias resolves to, shown only
* while Default Device is the selected choice (official actualDeviceName('')). */
function showDeviceCaption(select) {
if (!captionedSelects.has(select)) {
captionedSelects.add(select);
select.addEventListener('change', () => showDeviceCaption(select));
}
let caption = select.nextElementSibling?.classList.contains('ts-device-caption') ? select.nextElementSibling : null;
if (!caption) {
caption = document.createElement('span');
caption.className = 'ts-device-caption';
caption.setAttribute('aria-hidden', 'true');
select.after(caption);
}
const text = select.selectedOptions[0]?.dataset.caption ?? '';
caption.textContent = text;
caption.hidden = !text;
if (text) select.setAttribute('aria-description', text);
else select.removeAttribute('aria-description');
}
// ---------- 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 || S.keybindCapture) return; // keybinds.js records this key
if (!S.prefs.pttEnabled) return;
if (isTextField(e.target) && e.key.length === 1) return;
setPtt(true, 'key');
}
function onKeyUp(e) {
if (e.code === S.prefs?.pttCode) setPtt(false, 'key');
}
/**
* `source` names the holder: 'key', 'button', 'keybind:<id>:<scope>'. 'window-blur' releases every
* window-scoped holder (privacy reset) and leaves global keybind holders down; 'reset'
* (microphone connection lost) releases every holder.
*/
export function setPtt(down, source = 'key') {
if (source === 'window-blur') {
for (const holder of [...pttHolders]) if (windowScopedHolder(holder)) pttHolders.delete(holder);
if (pttHolders.size === 0) applyPtt(false, source, true);
return;
}
if (source === 'reset') pttHolders.clear();
else if (down) pttHolders.add(source);
else pttHolders.delete(source);
applyPtt(pttHolders.size > 0, source, false);
}
function applyPtt(down, source, privacy) {
if (S.ptt === down && !privacy) return;
if (down || privacy) captureBoundary();
if (privacy) pttGate.reset();
else pttGate.set(down, S.prefs?.pttReleaseDelay?.active ? S.prefs.pttReleaseDelay.ms : 0);
if (!down && !pttGate.open) captureBoundary();
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?.pttEnabled) log('debug', `voice: ptt ${down ? 'down' : 'up'} source=${source} focused=${document.hasFocus()}`);
hooks.onPtt(down);
}
/**
* Official PushToMute (inputDeactivated): `holder` is a keybind id. Fail-closed: frames stop at once and the
* pending capture is cut; forwarding resumes only when the last holder releases. Holders are not tied to a
* route: if the input connection changes while the key is held, the new route stays deactivated too.
*/
export function setInputDeactivated(holder, on) {
const had = inputDeactivatedHolders.size > 0;
if (on) inputDeactivatedHolders.add(holder);
else inputDeactivatedHolders.delete(holder);
if (had !== inputDeactivatedHolders.size > 0) captureBoundary();
}
/** Resolves with a KeyboardEvent.code, or null when cancelled with Escape. */
export function capturePttKey() {
return new Promise((resolve) => {
assigningPtt = resolve;
});
}
export function isCapturing() {
return Boolean(engine && engine.capturing);
}
/** The transmit mode the core confirmed, or null (diagnostics). */
export function confirmedTransmitMode() {
const conn = inputConnection();
const coreTx = conn ? txState(conn).mode : null;
return coreTx ? { ...coreTx } : null;
}
/** Whether captured PCM is currently being handed to the core (not whether voice is sent). */
export function isForwarding() {
return forwarding;
}
export function channelCodecProblem() {
const ch = ownChannel();
if (!ch || channelCanTransmit(inputConnection())) return null;
return ch.codec;
}