Files
client/app/renderer/js/voice.js
T
omar 3d623329b3
ci / linux-x64 (push) Failing after 33s
ci / linux-arm64-cross (push) Successful in 3m8s
Transmit mode: only the latest set_transmit answer counts; forwarding terminology; 0.1.4
An older answer (same settings or a restarted core) could re-enable forwarding while a newer mode
change was pending. Requests and core restarts now start a new epoch. Renderer stats count frames
forwarded to the core. v0.1.3 was tagged but never released.
2026-10-24 09:45:49 +03:00

386 lines
14 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, call } 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';
// framesForwarded counts PCM frames handed to the core; whether voice was sent is S.audio.transmitting.
export const voiceStats = { framesForwarded: 0, forwardRuns: 0, framesPlayed: 0, level: 0 };
let engine = null;
let forwarding = false;
let forwardRun = 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';
}
// Transmit mode confirmed by the core (`set_transmit`): null until acknowledged. Frames are forwarded only
// when it matches what the preferences ask for, so audio never reaches the core under the wrong 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.
let coreTx = null;
// Every request and every core restart bumps the epoch; only the answer to the latest request may change
// coreTx, 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.
let coreTxEpoch = 0;
let coreTxPendingKey = null;
let coreTxFailed = false;
function wantedCoreTx() {
return S.prefs?.transmitMode === 'vad' ? { mode: 'vad', sensitivity: S.prefs.vadSensitivity } : { mode: 'direct' };
}
const txKey = (mode) => (mode ? `${mode.mode}:${mode.sensitivity ?? ''}` : '');
/** 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();
}
/**
* Asks the core to use the transmit mode the preferences select. Nothing is forwarded until the core has
* acknowledged it; a failure leaves the mode unapplied (nothing is sent) and is shown, never replaced by
* another mode.
*/
export async function applyTransmitMode() {
if (!S.prefs) return;
const want = wantedCoreTx();
const key = txKey(want);
if (coreTxPendingKey === key) return; // the latest request already asks for exactly this
if (coreTxPendingKey === null && txKey(coreTx) === key && !coreTxFailed) return;
const epoch = ++coreTxEpoch;
coreTx = null;
coreTxFailed = false;
stopForwarding();
coreTxPendingKey = key;
try {
const result = await call('set_transmit', want);
if (epoch !== coreTxEpoch) return; // superseded, or the core restarted
coreTx = { mode: result.mode, sensitivity: result.sensitivity };
log('info', `voice: transmit mode ${result.mode}${result.sensitivity ? ` (${result.sensitivity})` : ''}`);
} catch (err) {
if (epoch !== coreTxEpoch) return;
coreTxFailed = true;
log('error', `voice: set_transmit failed: ${err.code} ${err.message}`);
toast(() => t('error.transmit_mode', { detail: errorText(err) }), 'error');
} finally {
if (epoch === coreTxEpoch) {
coreTxPendingKey = null;
hooks.onTransmitChanged();
}
}
}
/** The core stopped or restarted: its transmit mode is unknown, and answers from before are void. */
export function forgetCoreTransmitMode() {
coreTxEpoch += 1;
coreTx = null;
coreTxPendingKey = null;
coreTxFailed = false;
forwarding = false;
forwardRun = null;
}
/** Whether captured frames go to the core right now (not whether voice is sent: see S.audio.transmitting). */
export function shouldForward() {
if (!isConnected() || S.audio.input_muted || S.audio.output_muted || !channelCanTransmit()) return false;
const mode = S.prefs.transmitMode;
if (mode === 'vad') return coreTx?.mode === 'vad' && coreTx.sensitivity === S.prefs.vadSensitivity;
if (coreTx?.mode !== 'direct') return false;
return mode === 'open' || S.ptt;
}
function onFrame(pcm, rms, peak) {
voiceStats.level = peak;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
if (shouldForward()) {
tp.sendAudioFrame(new Uint8Array(pcm));
voiceStats.framesForwarded += 1;
if (!forwarding) {
forwarding = true;
voiceStats.forwardRuns += 1;
forwardRun = { frames: 0, peakMax: 0, mode: S.prefs.transmitMode };
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 = isConnected() || micTest;
if (!want) {
engine.stopCapture();
stopForwarding();
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();
stopForwarding();
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');
if (S.prefs.transmitMode === 'vad') return t('transmit.header.vad');
// 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);
}
/** The transmit mode the core confirmed, or null (diagnostics). */
export function confirmedTransmitMode() {
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()) return null;
return ch.codec;
}