Files
client/app/renderer/js/voice.js
T
2026-10-24 06:09:48 +03:00

296 lines
10 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 { keyLabel } from './text.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(e.message, '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(`Устройство вывода недоступно: ${err.message}`, 'error'));
} catch (err) {
toast(`Звук недоступен: ${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). */
export async function syncCapture() {
const want = isConnected() || micTest;
if (want && !engine.capturing) {
try {
await engine.startCapture({
deviceId: S.prefs.inputDeviceId,
echoCancellation: S.prefs.echoCancellation,
noiseSuppression: S.prefs.noiseSuppression,
autoGainControl: S.prefs.autoGainControl,
});
refreshDevices();
} catch (err) {
toast(`Нет доступа к микрофону: ${err.message || err.name}`, 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
}
} else if (!want && engine.capturing) {
engine.stopCapture();
if (sending) {
tp.endAudio();
sending = false;
}
}
}
export async function restartCapture() {
if (!engine.capturing) return;
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) {
await hooks.savePrefs({ inputDeviceId: deviceId });
await restartCapture();
await refreshDevices();
}
/** Saved output device for voice and stream audio; used by Settings and by the headphones menu. */
export async function chooseOutputDevice(deviceId) {
await hooks.savePrefs({ outputDeviceId: deviceId });
try {
await engine.setOutputDevice(deviceId);
} catch (err) {
toast(`Не удалось выбрать устройство вывода: ${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) {
setText(status, `Не удалось получить список устройств: ${err.name}: ${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 = 'Движок скрыл список устройств (нет разрешения на доступ к звуковым устройствам). Доступно только системное устройство по умолчанию.';
else if (input.physical === 0 && output.physical === 0) text = 'Звуковые устройства не найдены.';
else if (input.physical === 0) text = `Микрофоны не найдены. Устройств вывода: ${output.physical}.`;
else if (output.physical === 0) text = `Микрофонов: ${input.physical}. Устройства вывода не найдены.`;
else text = `Найдено микрофонов: ${input.physical}, устройств вывода: ${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 ? 'Говорите…' : 'Удерживайте, чтобы говорить');
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 'Открытый микрофон';
// The key is read only from this window: say so whenever another window has the focus.
if (!document.hasFocus()) return `Окно неактивно — ${keyLabel(S.prefs.pttCode)} не сработает`;
return `Клавиша: ${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;
}