Files
client/app/renderer/js/audio/engine.js
T
omar 7287fdb63e
ci / linux-x64 (push) Failing after 1m26s
ci / linux-arm64-cross (push) Failing after 2m20s
TeamsPeach desktop client: Electron UI, Rust core bridge, TS6 stream viewer, CI
2026-10-24 03:31:54 +03:00

146 lines
4.9 KiB
JavaScript

// Web Audio side of voice: one 48 kHz AudioContext, a capture worklet producing bridge-format
// frames and a playback worklet with a bounded ring buffer.
export class AudioEngine {
constructor({ onFrame, onError, log }) {
this.onFrame = onFrame;
this.onError = onError ?? (() => {});
this.log = log ?? (() => {});
this.ctx = null;
this.playback = null;
this.voiceGain = null;
this.capture = null;
this.ready = null;
this.stats = { framesOut: 0 };
this.statsWaiters = [];
}
init() {
if (!this.ready) this.ready = this._init();
return this.ready;
}
async _init() {
const ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
this.ctx = ctx;
await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url));
await ctx.audioWorklet.addModule(new URL('./playback-worklet.js', import.meta.url));
this.playback = new AudioWorkletNode(ctx, 'tp-playback', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [1],
});
this.playback.port.onmessage = (event) => {
if (event.data && event.data.type === 'stats') {
const waiters = this.statsWaiters.splice(0);
for (const resolve of waiters) resolve(event.data);
}
};
this.voiceGain = ctx.createGain();
this.playback.connect(this.voiceGain).connect(ctx.destination);
if (ctx.state !== 'running') await ctx.resume();
this.log('info', `audio: context ${ctx.sampleRate} Hz, baseLatency ${Math.round((ctx.baseLatency || 0) * 1000)} ms`);
}
setVoiceVolume(percent) {
if (this.voiceGain) this.voiceGain.gain.setTargetAtTime(percent / 100, this.ctx.currentTime, 0.02);
}
async setOutputDevice(deviceId) {
await this.init();
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Выбор устройства вывода не поддерживается');
await this.ctx.setSinkId(deviceId || '');
}
/** Copies the 1920-byte frame into the worklet (transfer). */
pushPlayback(bytes) {
if (!this.playback) return;
const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
this.playback.port.postMessage(copy, [copy]);
this.stats.framesOut += 1;
}
flushPlayback() {
if (this.playback) this.playback.port.postMessage({ type: 'flush' });
}
playbackStats() {
if (!this.playback) return Promise.resolve(null);
return new Promise((resolve) => {
this.statsWaiters.push(resolve);
this.playback.port.postMessage({ type: 'stats' });
});
}
get capturing() {
return this.capture !== null;
}
async startCapture({ deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
await this.init();
this.stopCapture();
const audio = {
channelCount: 1,
echoCancellation,
noiseSuppression,
autoGainControl,
};
if (deviceId) audio.deviceId = { exact: deviceId };
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
} catch (err) {
if (deviceId && err && err.name === 'OverconstrainedError') {
delete audio.deviceId;
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
this.onError({ code: 'device_fallback', message: 'Выбранный микрофон недоступен, используется микрофон по умолчанию' });
} else {
throw err;
}
}
const ctx = this.ctx;
const source = ctx.createMediaStreamSource(stream);
const node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
const sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
const track = stream.getAudioTracks()[0];
track.addEventListener('ended', () => {
if (this.capture && this.capture.stream === stream) {
this.stopCapture();
this.onError({ code: 'device_lost', message: 'Микрофон отключён' });
}
});
this.capture = { stream, source, node, sink, label: track ? track.label : '' };
this.log('info', `audio: capture started (${track ? track.getSettings().sampleRate : '?'} Hz device)`);
return this.capture.label;
}
stopCapture() {
const c = this.capture;
if (!c) return;
this.capture = null;
c.node.port.onmessage = null;
try {
c.source.disconnect();
c.node.disconnect();
c.sink.disconnect();
} catch {
// already disconnected
}
for (const t of c.stream.getTracks()) t.stop();
}
}