Voice activation (core voice detector, set_transmit handshake), transmission mode in Settings → Audio, atomic prefs commit, ARM64 unit tests under qemu; version 0.1.3
This commit is contained in:
1 parent
8439fe062e
commit
b7951e0693
46 files changed
+1905
-191
No files matched your search
@@ -118,6 +118,7 @@ const COMMANDS = {
|
||||
return out;
|
||||
},
|
||||
set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }),
|
||||
set_transmit: shape({ mode: oneOf('direct', 'vad'), sensitivity: optional(oneOf('high', 'normal', 'low')) }),
|
||||
stream_list: shape({ client_id: optional(posInt) }),
|
||||
stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }),
|
||||
stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }),
|
||||
|
||||
+5
-2
@@ -9,7 +9,9 @@ const path = require('node:path');
|
||||
*/
|
||||
const SCHEMA = {
|
||||
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
|
||||
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' },
|
||||
// 'ptt' push-to-talk, 'open' continuous open microphone, 'vad' voice activation (the core's detector).
|
||||
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' || v === 'vad' },
|
||||
vadSensitivity: { default: 'normal', check: (v) => v === 'high' || v === 'normal' || v === 'low' },
|
||||
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
|
||||
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
|
||||
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
|
||||
@@ -77,11 +79,12 @@ class Prefs {
|
||||
if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`);
|
||||
next[key] = value;
|
||||
}
|
||||
this.values = next;
|
||||
// Persist first: if writing fails, neither the file nor the in-memory values change.
|
||||
fs.mkdirSync(path.dirname(this.file), { recursive: true });
|
||||
const tmp = `${this.file}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
|
||||
fs.renameSync(tmp, this.file);
|
||||
this.values = next;
|
||||
return this.get();
|
||||
}
|
||||
}
|
||||
|
||||
+22
-8
@@ -300,6 +300,26 @@
|
||||
<label class="field"><span class="field-label"><span data-i18n="ui.voice.volume">Voice volume</span> <output id="voice-volume-value" for="voice-volume"></output></span>
|
||||
<input id="voice-volume" class="range" type="range" min="0" max="200" step="5"></label>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-transmit">
|
||||
<h2 id="card-transmit" class="card-title" data-i18n="ui.voice.transmission">Voice transmission</h2>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="visually-hidden" data-i18n="ui.transmission.mode">Transmission mode</legend>
|
||||
<label class="choice"><input type="radio" name="transmit" value="ptt"> <span data-i18n="ui.push.to.talk">Push to talk</span></label>
|
||||
<label class="choice"><input type="radio" name="transmit" value="vad"> <span data-i18n="transmit.mode.vad">Voice activation</span></label>
|
||||
<label class="choice"><input type="radio" name="transmit" value="open"> <span data-i18n="transmit.mode.open">Open microphone (continuous transmission)</span></label>
|
||||
</fieldset>
|
||||
<div id="vad-options" hidden>
|
||||
<label class="field"><span class="field-label" data-i18n="transmit.vad.sensitivity">Voice activation sensitivity</span>
|
||||
<select id="vad-sensitivity">
|
||||
<option value="high" data-i18n="transmit.vad.high">High: quieter speech</option>
|
||||
<option value="normal" data-i18n="transmit.vad.normal">Normal</option>
|
||||
<option value="low" data-i18n="transmit.vad.low">Low: noisier surroundings</option>
|
||||
</select>
|
||||
</label>
|
||||
<p class="hint" data-i18n="transmit.vad.hint">Voice detection runs locally on this computer, not in the cloud. It detects speech rather than just sound level; audio is only held briefly in memory to decide, and nothing is saved as a recording or transcribed into words. Transmission starts when speech is detected and ends about 0.4 s after the last detected speech. Noise suppression can help, but a TV, other voices, or noise may still trigger transmission or keep it open.</p>
|
||||
</div>
|
||||
<p class="hint" data-i18n="transmit.mic.test.hint">The microphone test shows the input level, not whether speech is detected. The test itself never sends audio. In a channel, the selected transmission mode and mute controls determine when others hear you.</p>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="card-processing">
|
||||
<h2 id="card-processing" class="card-title" data-i18n="ui.microphone.processing">Microphone processing</h2>
|
||||
<fieldset class="fieldset">
|
||||
@@ -342,14 +362,8 @@
|
||||
|
||||
<div class="settings-panel" data-panel="keys" hidden>
|
||||
<h1 class="panel-title" data-i18n="ui.keyboard">Keyboard</h1>
|
||||
<section class="card" aria-labelledby="card-transmit">
|
||||
<h2 id="card-transmit" class="card-title" data-i18n="ui.voice.transmission">Voice transmission</h2>
|
||||
<fieldset class="fieldset">
|
||||
<legend class="visually-hidden" data-i18n="ui.transmission.mode">Transmission mode</legend>
|
||||
<label class="choice"><input type="radio" name="transmit" value="ptt"> <span data-i18n="ui.push.to.talk">Push to talk</span></label>
|
||||
<label class="choice"><input type="radio" name="transmit" value="open"> <span data-i18n="ui.open.microphone">Open microphone</span></label>
|
||||
</fieldset>
|
||||
<div class="card-divider"></div>
|
||||
<section class="card" aria-labelledby="card-ptt">
|
||||
<h2 id="card-ptt" class="card-title" data-i18n="ui.push.to.talk">Push to talk</h2>
|
||||
<div class="ptt-row">
|
||||
<span class="row-name" data-i18n="ui.push.to.talk.key">Push-to-talk key</span>
|
||||
<kbd id="ptt-key" class="kbd"></kbd>
|
||||
|
||||
@@ -67,17 +67,22 @@ function onCoreStatus(status) {
|
||||
showView('#boot');
|
||||
break;
|
||||
case 'stopped':
|
||||
voice.forgetCoreTransmitMode();
|
||||
setText($('#boot-text'), () => t('ui.restarting.core'));
|
||||
showView('#boot');
|
||||
resetConnection(null);
|
||||
break;
|
||||
case 'ready':
|
||||
// A (re)started core transmits directly until told otherwise: apply the chosen mode first.
|
||||
voice.forgetCoreTransmitMode();
|
||||
voice.applyTransmitMode();
|
||||
loadProfile();
|
||||
break;
|
||||
case 'missing':
|
||||
showFatal(t('ui.teamspeach.core.not.found'), t('ui.the.core.executable.is.missing.build.it'), status.candidates ?? []);
|
||||
break;
|
||||
default:
|
||||
voice.forgetCoreTransmitMode();
|
||||
resetConnection(null);
|
||||
showFatal(t('ui.the.core.stopped'), coreStatusText(status), []);
|
||||
}
|
||||
@@ -467,7 +472,7 @@ Object.defineProperty(window, 'teamspeachDiagnostics', {
|
||||
clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [],
|
||||
talking: Array.from(S.talking),
|
||||
audio: { ...S.audio },
|
||||
voice: { ...voice.voiceStats, sending: voice.isSending(), capturing: voice.isCapturing() },
|
||||
voice: { ...voice.voiceStats, sending: voice.isSending(), capturing: voice.isCapturing(), coreMode: voice.confirmedTransmitMode() },
|
||||
streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })),
|
||||
watch: { ...watch.watchStats },
|
||||
videoCodecs: settings.videoCodecs(),
|
||||
|
||||
@@ -135,10 +135,17 @@ export function initSettings(h0) {
|
||||
if (radio.checked) {
|
||||
await hooks.savePrefs({ transmitMode: radio.value });
|
||||
renderAudio();
|
||||
await voice.applyTransmitMode();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$('#vad-sensitivity').addEventListener('change', async (e) => {
|
||||
await hooks.savePrefs({ vadSensitivity: e.target.value });
|
||||
renderAudio();
|
||||
await voice.applyTransmitMode();
|
||||
});
|
||||
|
||||
$('#ptt-assign').addEventListener('click', async () => {
|
||||
const btn = $('#ptt-assign');
|
||||
btn.disabled = true;
|
||||
@@ -189,6 +196,8 @@ export function renderProfile() {
|
||||
export function renderAudio() {
|
||||
const prefs = S.prefs;
|
||||
for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode;
|
||||
$('#vad-options').hidden = prefs.transmitMode !== 'vad';
|
||||
$('#vad-sensitivity').value = prefs.vadSensitivity;
|
||||
setText($('#ptt-key'), () => keyLabel(prefs.pttCode));
|
||||
$('#ptt-assign').disabled = false;
|
||||
$('#opt-ns').checked = prefs.noiseSuppression;
|
||||
|
||||
+81
-18
@@ -2,7 +2,7 @@
|
||||
// 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 { tp, log, call } from './core.js';
|
||||
import { AudioEngine } from './audio/engine.js';
|
||||
import { buildDeviceOptions } from './audio/devices.js';
|
||||
import { toast } from './toast.js';
|
||||
@@ -79,18 +79,81 @@ function channelCanTransmit() {
|
||||
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();
|
||||
// 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;
|
||||
let coreTxPending = 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 and ends an open burst (the core ends its talk spurt on audio_end). */
|
||||
function stopForwarding() {
|
||||
if (!sending) return;
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (txKey(coreTx) === key && !coreTxFailed) return;
|
||||
coreTx = null;
|
||||
stopForwarding();
|
||||
coreTxPending = key;
|
||||
try {
|
||||
const result = await call('set_transmit', want);
|
||||
if (coreTxPending !== key) return; // a newer change is on its way
|
||||
coreTx = { mode: result.mode, sensitivity: result.sensitivity };
|
||||
coreTxFailed = false;
|
||||
log('info', `voice: transmit mode ${result.mode}${result.sensitivity ? ` (${result.sensitivity})` : ''}`);
|
||||
} catch (err) {
|
||||
if (coreTxPending !== key) return;
|
||||
coreTxFailed = true;
|
||||
log('error', `voice: set_transmit failed: ${err.code} ${err.message}`);
|
||||
toast(() => t('error.transmit_mode', { detail: errorText(err) }), 'error');
|
||||
} finally {
|
||||
if (coreTxPending === key) coreTxPending = null;
|
||||
hooks.onTransmitChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/** The core stopped or restarted: its transmit mode is unknown until applied again. */
|
||||
export function forgetCoreTransmitMode() {
|
||||
coreTx = null;
|
||||
coreTxPending = null;
|
||||
sending = false;
|
||||
burst = 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 (shouldTransmit()) {
|
||||
if (shouldForward()) {
|
||||
tp.sendAudioFrame(new Uint8Array(pcm));
|
||||
voiceStats.framesSent += 1;
|
||||
if (!sending) {
|
||||
@@ -102,12 +165,8 @@ function onFrame(pcm, rms, peak) {
|
||||
}
|
||||
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();
|
||||
} else {
|
||||
stopForwarding();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,10 +185,7 @@ export async function syncCapture() {
|
||||
const want = isConnected() || micTest;
|
||||
if (!want) {
|
||||
engine.stopCapture();
|
||||
if (sending) {
|
||||
tp.endAudio();
|
||||
sending = false;
|
||||
}
|
||||
stopForwarding();
|
||||
return;
|
||||
}
|
||||
if (engine.capturing || engine.captureStarting) return;
|
||||
@@ -154,6 +210,7 @@ export async function syncCapture() {
|
||||
*/
|
||||
export async function restartCapture() {
|
||||
engine.stopCapture();
|
||||
stopForwarding();
|
||||
await syncCapture();
|
||||
}
|
||||
|
||||
@@ -290,6 +347,7 @@ export function capturePttKey() {
|
||||
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) });
|
||||
@@ -299,6 +357,11 @@ export function isCapturing() {
|
||||
return Boolean(engine && engine.capturing);
|
||||
}
|
||||
|
||||
/** The transmit mode the core confirmed, or null (diagnostics). */
|
||||
export function confirmedTransmitMode() {
|
||||
return coreTx ? { ...coreTx } : null;
|
||||
}
|
||||
|
||||
export function isSending() {
|
||||
return sending;
|
||||
}
|
||||
|
||||
@@ -108,6 +108,16 @@
|
||||
"ui.transmission.mode": "Transmission mode",
|
||||
"ui.push.to.talk": "Push to talk",
|
||||
"ui.open.microphone": "Open microphone",
|
||||
"transmit.mode.vad": "Voice activation",
|
||||
"transmit.mode.open": "Open microphone (continuous transmission)",
|
||||
"transmit.vad.sensitivity": "Voice activation sensitivity",
|
||||
"transmit.vad.high": "High: quieter speech",
|
||||
"transmit.vad.normal": "Normal",
|
||||
"transmit.vad.low": "Low: noisier surroundings",
|
||||
"transmit.vad.hint": "Voice detection runs locally on this computer, not in the cloud. It detects speech rather than just sound level; audio is only held briefly in memory to decide, and nothing is saved as a recording or transcribed into words. Transmission starts when speech is detected and ends about 0.4 s after the last detected speech. Noise suppression can help, but a TV, other voices, or noise may still trigger transmission or keep it open.",
|
||||
"transmit.mic.test.hint": "The microphone test shows the input level, not whether speech is detected. The test itself never sends audio. In a channel, the selected transmission mode and mute controls determine when others hear you.",
|
||||
"transmit.header.vad": "Voice activation",
|
||||
"error.transmit_mode": "The transmission mode could not be applied ({detail}). Nothing is transmitted until it is applied.",
|
||||
"ui.push.to.talk.key": "Push-to-talk key",
|
||||
"ui.assign": "Assign",
|
||||
"ui.the.key.works.while.teamspeach.is.focused": "The key works while TeamsPeach is focused. Letter keys do not trigger while typing. Press Esc to cancel assignment.",
|
||||
|
||||
@@ -108,6 +108,16 @@
|
||||
"ui.transmission.mode": "Режим передачи",
|
||||
"ui.push.to.talk": "Нажми и говори",
|
||||
"ui.open.microphone": "Открытый микрофон",
|
||||
"transmit.mode.vad": "Активация голосом",
|
||||
"transmit.mode.open": "Открытый микрофон (непрерывная передача)",
|
||||
"transmit.vad.sensitivity": "Чувствительность активации голосом",
|
||||
"transmit.vad.high": "Высокая: для тихой речи",
|
||||
"transmit.vad.normal": "Обычная",
|
||||
"transmit.vad.low": "Низкая: для шумной обстановки",
|
||||
"transmit.vad.hint": "Детектор работает на этом компьютере, без облачных сервисов. Он определяет наличие речи, а не просто уровень звука; звук лишь кратко держится в памяти для решения, ничего не сохраняется как запись и не переводится в текст. Передача начинается при обнаружении речи и заканчивается примерно через 0,4 с после последней обнаруженной речи. Шумоподавление может помочь, но телевизор, чужие голоса или шум всё равно могут включить передачу или продлить её.",
|
||||
"transmit.mic.test.hint": "Проверка микрофона показывает уровень входного сигнала, а не результат определения речи. Сама проверка не отправляет звук. В канале слышимость вашего голоса зависит от выбранного режима передачи и кнопок отключения микрофона и звука.",
|
||||
"transmit.header.vad": "Активация голосом",
|
||||
"error.transmit_mode": "Не удалось применить режим передачи ({detail}). Пока он не применён, ничего не передаётся.",
|
||||
"ui.push.to.talk.key": "Клавиша «нажми и говори»",
|
||||
"ui.assign": "Назначить",
|
||||
"ui.the.key.works.while.teamspeach.is.focused": "Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста. Esc отменяет назначение.",
|
||||
|
||||
Reference in new issue
Block a user