fix: preserve audio capture across device reconfiguration

This commit is contained in:
illusia committed 2026-10-01 11:30:40 +08:00
1 parent 797fc135a9
commit 0785f82386
5 files changed
+382 -45

No files matched your search

+101 -31
View File
@@ -1,5 +1,6 @@
import { createRemotePlayback } from "../voice/remote-playback.js";
import { createMicrophoneTest } from "../voice/microphone-test.js";
import { createAudioSinkRouter } from "../voice/audio-sink.js";
import { createScreenShareController } from "../voice/screen-share.js";
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
import { parseServerMessage } from "../../../src/shared/server-messages.js";
@@ -265,6 +266,7 @@ export function useVoiceWebSocket() {
let audioCtx: SinkAudioContext | null = null;
let micStream: MediaStream | null = null;
let scriptNode: ScriptProcessorNode | null = null;
let captureGraphGeneration = 0;
let workletNode: AudioWorkletNode | null = null;
let workletContext: AudioContext | null = null;
let workletModulePromise: Promise<void> | null = null;
@@ -297,6 +299,14 @@ export function useVoiceWebSocket() {
const outputDevices = reactive<AudioOutputDevice[]>([]);
const selectedInputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:input-device") ?? "" : "");
const selectedOutputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:output-device") ?? "" : "");
let committedInputDeviceId = selectedInputDeviceId.value;
let committedOutputDeviceId = selectedOutputDeviceId.value;
let inputDeviceTouched = false;
let outputDeviceTouched = false;
let inputDeviceGeneration = 0;
let outputDeviceGeneration = 0;
let deviceListGeneration = 0;
const audioSinkRouter = createAudioSinkRouter();
const outputDeviceSupported = ref(false);
const audioPermission = ref<AudioPermission>("unknown");
const microphoneProcessing = reactive<MicrophoneProcessingSettings>({
@@ -318,6 +328,8 @@ export function useVoiceWebSocket() {
});
const microphoneMuted = ref(false);
const noiseSuppressionEnabled = ref(true);
let noiseSuppressionTouched = false;
let committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
const inputVolume = ref(1);
const outputVolume = ref(1);
const outputMuted = ref(false);
@@ -351,15 +363,15 @@ export function useVoiceWebSocket() {
async function saveAudioPreferences(): Promise<void> {
await saveLocalPreferences({
schemaVersion: 1,
preferredInputDeviceId: selectedInputDeviceId.value,
inputDeviceId: selectedInputDeviceId.value,
preferredInputDeviceId: committedInputDeviceId,
inputDeviceId: committedInputDeviceId,
microphoneMuted: microphoneMuted.value,
noiseSuppressionEnabled: noiseSuppressionEnabled.value,
noiseSuppressionEnabled: committedNoiseSuppressionEnabled,
voxThreshold: voxThreshold.value,
inputGain: inputVolume.value,
outputVolume: outputVolume.value,
notificationVolume: notificationVolume.value,
preferredOutputDeviceId: selectedOutputDeviceId.value,
preferredOutputDeviceId: committedOutputDeviceId,
volumesByUid: { ...storedVolumesByUid },
});
}
@@ -373,13 +385,22 @@ export function useVoiceWebSocket() {
}
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
if (!inputDeviceTouched) {
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
committedInputDeviceId = selectedInputDeviceId.value;
}
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
if (typeof preferences.noiseSuppressionEnabled === "boolean") noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
if (!noiseSuppressionTouched && typeof preferences.noiseSuppressionEnabled === "boolean") {
noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
committedNoiseSuppressionEnabled = preferences.noiseSuppressionEnabled;
}
if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08);
if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain));
if (typeof preferences.outputVolume === "number") outputVolume.value = Math.max(0, Math.min(1, preferences.outputVolume));
if (!selectedOutputDeviceId.value) selectedOutputDeviceId.value = preferences.preferredOutputDeviceId ?? "";
if (!outputDeviceTouched) {
if (!selectedOutputDeviceId.value) selectedOutputDeviceId.value = preferences.preferredOutputDeviceId ?? "";
committedOutputDeviceId = selectedOutputDeviceId.value;
}
if (typeof preferences.notificationVolume === "number") notificationVolume.value = clamp(preferences.notificationVolume, 0, 1);
Object.assign(storedVolumesByUid, preferences.volumesByUid ?? {});
syncKnownMemberVolumes();
@@ -487,6 +508,10 @@ export function useVoiceWebSocket() {
}
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
const generation = outputDeviceGeneration;
const output = webrtcOutputElement;
const isCurrent = () => generation === outputDeviceGeneration && audioCtx === ctx
&& selectedOutputDeviceId.value === deviceId;
const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
if (!ctx.setSinkId && !mediaSinkSupported) {
outputDeviceSupported.value = false;
@@ -494,8 +519,8 @@ export function useVoiceWebSocket() {
return;
}
outputDeviceSupported.value = true;
if (ctx.setSinkId) await ctx.setSinkId(deviceId || "default");
if (webrtcOutputElement?.setSinkId) await webrtcOutputElement.setSinkId(deviceId || "default");
if (ctx.setSinkId) await audioSinkRouter.set(ctx, deviceId, isCurrent);
if (output?.setSinkId) await audioSinkRouter.set(output, deviceId, () => isCurrent() && output === webrtcOutputElement);
}
function installWebRtcPlaybackRetry(): void {
@@ -563,6 +588,9 @@ export function useVoiceWebSocket() {
}
async function refreshAudioDevices(): Promise<void> {
const generation = ++deviceListGeneration;
const sequence = connectionSequence;
const isCurrent = () => generation === deviceListGeneration && sequence === connectionSequence;
if (!navigator.mediaDevices?.enumerateDevices) {
inputDevices.length = 0;
outputDevices.length = 0;
@@ -572,8 +600,10 @@ export function useVoiceWebSocket() {
let devices: MediaDeviceInfo[];
try {
devices = await navigator.mediaDevices.enumerateDevices();
if (!isCurrent()) return;
clearAudioNotice("DEVICE_LIST_UNAVAILABLE");
} catch {
if (!isCurrent()) return;
// enumerateDevices rejects when the device list is blocked (for example in a
// locked-down iframe). Use the browser defaults and explain the limitation.
inputDevices.length = 0;
@@ -590,13 +620,17 @@ export function useVoiceWebSocket() {
inputDevices.splice(0, inputDevices.length, ...microphones);
outputDevices.splice(0, outputDevices.length, ...speakers);
if (selectedInputDeviceId.value && !microphones.some((device) => device.deviceId === selectedInputDeviceId.value)) {
inputDeviceTouched = true;
selectedInputDeviceId.value = "";
committedInputDeviceId = "";
localStorage.setItem("webspeak:input-device", selectedInputDeviceId.value);
void saveAudioPreferences();
if (micStream) void startMicrophone().catch(() => undefined);
}
if (selectedOutputDeviceId.value && !speakers.some((device) => device.deviceId === selectedOutputDeviceId.value)) {
outputDeviceTouched = true;
selectedOutputDeviceId.value = "";
committedOutputDeviceId = "";
localStorage.setItem("webspeak:output-device", "");
void saveAudioPreferences();
if (audioCtx && outputDeviceSupported.value) void setAudioSink(audioCtx, "").catch(() => undefined);
@@ -693,8 +727,11 @@ export function useVoiceWebSocket() {
silentGain = ctx.createGain();
silentGain.gain.value = 0;
const captureGeneration = captureGraphGeneration;
const handleCaptureChunk = (input: Float32Array, rms?: number): void => {
if (generation !== microphoneGeneration) return;
// A replacement permission request does not invalidate the live graph.
// Only replacing or stopping that graph may silence its callbacks.
if (captureGeneration !== captureGraphGeneration || micStream !== nextStream || audioCtx !== ctx) return;
if (!input.length) return;
micLevel.value = Math.min(1, (rms ?? Math.sqrt(input.reduce((sum, sample) => sum + sample * sample, 0) / input.length)) * 6);
const socket = ws.value;
@@ -1044,8 +1081,11 @@ export function useVoiceWebSocket() {
document.body.append(output);
webrtcOutputElement = output;
webrtcPlaybackStream = stream;
if (selectedOutputDeviceId.value && output.setSinkId) {
void output.setSinkId(selectedOutputDeviceId.value).catch(() => undefined);
if (selectedOutputDeviceId.value && typeof output.setSinkId === "function") {
const deviceId = selectedOutputDeviceId.value;
const generation = outputDeviceGeneration;
void audioSinkRouter.set(output, deviceId, () => generation === outputDeviceGeneration
&& webrtcOutputElement === output && selectedOutputDeviceId.value === deviceId).catch(() => undefined);
}
void syncWebRtcPlayback();
};
@@ -1214,6 +1254,7 @@ export function useVoiceWebSocket() {
}
function stopCaptureGraph(): void {
captureGraphGeneration++;
accumLen = 0;
voxAttack = 0;
voxRelease = 0;
@@ -1266,22 +1307,35 @@ export function useVoiceWebSocket() {
}
async function setInputDevice(deviceId: string): Promise<void> {
const previousDeviceId = selectedInputDeviceId.value;
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
inputDeviceTouched = true;
selectedInputDeviceId.value = deviceId;
localStorage.setItem("webspeak:input-device", deviceId);
void saveAudioPreferences();
await reconfigureMicrophone();
}
async function reconfigureMicrophone(): Promise<void> {
const generation = ++inputDeviceGeneration;
deviceListGeneration++;
const sequence = connectionSequence;
const socket = ws.value;
const isCurrent = () => generation === inputDeviceGeneration && sequence === connectionSequence;
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
try {
if (shouldRestartWebRtc) stopWebRtcTransport();
// Keep the current peer alive until the replacement microphone is ready.
if (micStream) await startMicrophone();
if (shouldRestartWebRtc && ws.value) {
stopWebRtcTransport();
await startWebRtcTransport(connectionSequence, ws.value);
}
if (!isCurrent()) return;
if (shouldRestartWebRtc && socket) await startWebRtcTransport(sequence, socket);
if (!isCurrent()) return;
await refreshAudioDevices();
if (!isCurrent()) return;
committedInputDeviceId = selectedInputDeviceId.value;
committedNoiseSuppressionEnabled = noiseSuppressionEnabled.value;
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
await saveAudioPreferences();
} catch (error) {
selectedInputDeviceId.value = previousDeviceId;
localStorage.setItem("webspeak:input-device", previousDeviceId);
if (!isCurrent() || error instanceof CancelledMediaOperation) return;
selectedInputDeviceId.value = committedInputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
localStorage.setItem("webspeak:input-device", committedInputDeviceId);
throw error;
}
}
@@ -1292,21 +1346,35 @@ export function useVoiceWebSocket() {
function stopMicrophoneTest(): void {
microphoneTest.stop();
// Closing settings also releases device-preview capture when no recorder
// was started. Room capture remains owned by the connected session.
if (!state.connected) stopMicrophone();
}
async function setOutputDevice(deviceId: string): Promise<void> {
const previousDeviceId = selectedOutputDeviceId.value;
if (deviceId && !outputDevices.some((device) => device.deviceId === deviceId)) {
throw new Error("所选扬声器当前不可用");
}
outputDeviceTouched = true;
const generation = ++outputDeviceGeneration;
deviceListGeneration++;
const sequence = connectionSequence;
const isCurrent = () => generation === outputDeviceGeneration && sequence === connectionSequence;
const previousDeviceId = committedOutputDeviceId;
selectedOutputDeviceId.value = deviceId;
localStorage.setItem("webspeak:output-device", deviceId);
try {
await setAudioSink(getAudioCtx(), deviceId);
if (!isCurrent()) return;
committedOutputDeviceId = deviceId;
localStorage.setItem("webspeak:output-device", deviceId);
await saveAudioPreferences();
} catch (error) {
if (!isCurrent()) return;
selectedOutputDeviceId.value = previousDeviceId;
localStorage.setItem("webspeak:output-device", previousDeviceId);
// One endpoint may have changed before the other rejected the request.
if (audioCtx) await setAudioSink(audioCtx, previousDeviceId).catch(() => undefined);
if (!isCurrent()) return;
throw error;
}
}
@@ -1521,6 +1589,12 @@ export function useVoiceWebSocket() {
/** All ways a session ends release the same owned media and pending work. */
function releaseSessionResources(sendScreenStop = false): void {
inputDeviceGeneration++;
outputDeviceGeneration++;
deviceListGeneration++;
selectedInputDeviceId.value = committedInputDeviceId;
selectedOutputDeviceId.value = committedOutputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
microphoneTest.dispose();
clearAudioStatusProbes();
rejectPendingCommands(new Error("语音连接已关闭"));
@@ -2077,14 +2151,10 @@ export function useVoiceWebSocket() {
async function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
if (noiseSuppressionEnabled.value === enabled) return;
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
noiseSuppressionTouched = true;
noiseSuppressionEnabled.value = enabled;
void saveAudioPreferences();
if (!micStream) return;
try {
if (shouldRestartWebRtc) stopWebRtcTransport();
await startMicrophone();
if (shouldRestartWebRtc && ws.value) await startWebRtcTransport(connectionSequence, ws.value);
await reconfigureMicrophone();
} catch (error) {
setMicrophoneError(error);
}
+22
View File
@@ -0,0 +1,22 @@
interface AudioSink {
setSinkId?(deviceId: string): Promise<void>;
}
// Browser sink changes cannot be cancelled once started. Serialize each
// endpoint so an older completion cannot leave it on the wrong device.
export function createAudioSinkRouter() {
const pending = new WeakMap<AudioSink, Promise<void>>();
function set(sink: AudioSink, deviceId: string, isCurrent: () => boolean): Promise<void> {
const previous = pending.get(sink) ?? Promise.resolve();
const task = previous.catch(() => {}).then(async () => {
if (isCurrent()) await sink.setSinkId?.(deviceId || "default");
});
pending.set(sink, task);
const cleanup = () => { if (pending.get(sink) === task) pending.delete(sink); };
void task.then(cleanup, cleanup);
return task;
}
return { set };
}
+229
View File
@@ -73,6 +73,7 @@ function receiveAudio(socket, clientId = 7) {
socket.onmessage({ data: new Uint8Array([4, clientId >> 8, clientId & 255, 1, 2, 3]).buffer });
}
class AudioContextStub extends EventTarget {
static instances = [];
static processors = [];
static sources = [];
static gains = [];
@@ -80,6 +81,8 @@ class AudioContextStub extends EventTarget {
currentTime = 0;
sampleRate = 48000;
destination = new AudioNodeStub();
constructor() { super(); AudioContextStub.instances.push(this); }
async setSinkId(id) { this.sinkId = id; }
close() { this.state = "closed"; return Promise.resolve(); }
createMediaStreamSource() {
if (this.state === "closed") throw new Error("Audio context closed");
@@ -161,6 +164,7 @@ beforeEach(() => {
TestSocket.instances.length = 0;
TestPeer.instances.length = 0;
AudioContextStub.processors.length = 0;
AudioContextStub.instances.length = 0;
AudioContextStub.sources.length = 0;
AudioContextStub.gains.length = 0;
AudioDecoderStub.instances.length = 0;
@@ -188,6 +192,8 @@ beforeEach(() => {
replaceGlobal("AudioContext", AudioContextStub);
replaceGlobal("AudioDecoder", AudioDecoderStub);
replaceGlobal("MediaRecorder", RecorderStub);
const storage = new Map();
replaceGlobal("localStorage", { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, String(value)), removeItem: key => storage.delete(key) });
replaceGlobal("EncodedAudioChunk", class { constructor(init) { Object.assign(this, init); } });
replaceGlobal("HTMLMediaElement", class {});
replaceGlobal("navigator", { mediaDevices: {
@@ -739,3 +745,226 @@ test("an asynchronous recorder failure stops capture and reports a microphone er
recorder.finish();
assert.equal(voice.testAudioUrl.value, "");
});
const availableDevices = [
...["mic-a", "mic-b"].map(deviceId => ({ deviceId, kind: "audioinput", label: deviceId, groupId: "" })),
...["speaker-a", "speaker-b"].map(deviceId => ({ deviceId, kind: "audiooutput", label: deviceId, groupId: "" })),
];
test("an old input switch failure cannot roll back a newer microphone selection", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
await voice.ensureMicrophone();
const permission = deferred();
const current = microphoneStream();
navigator.mediaDevices.getUserMedia = ({ audio }) => audio.deviceId.exact === "mic-a" ? permission.promise : Promise.resolve(current);
const old = voice.setInputDevice("mic-a").catch(() => {});
await voice.setInputDevice("mic-b");
permission.reject(new Error("Old microphone unavailable"));
await old;
assert.equal(voice.selectedInputDeviceId.value, "mic-b");
assert.equal(localStorage.getItem("webspeak:input-device"), "mic-b");
assert.equal(current.track.readyState, "live");
});
test("a failed microphone switch leaves an existing WebRTC peer and capture alive", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
const stream = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => stream;
const { peer, socket } = await connectWebRtc();
navigator.mediaDevices.getUserMedia = async () => { throw new Error("New device unavailable"); };
await assert.rejects(voice.setInputDevice("mic-a"), /New device unavailable/);
assert.notEqual(peer.connectionState, "closed");
receiveAudio(socket);
assert.equal(AudioDecoderStub.instances.length, 0, "WebRTC still owns playback");
assert.equal(stream.track.readyState, "live");
assert.equal(voice.selectedInputDeviceId.value, "");
});
test("an old output switch rejection cannot roll back the latest selection", async t => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
await voice.ensureMicrophone();
const ctx = AudioContextStub.instances.at(-1);
const oldSink = deferred();
t.mock.method(ctx, "setSinkId", id => id === "speaker-a" ? oldSink.promise : Promise.resolve());
const old = voice.setOutputDevice("speaker-a").catch(() => {});
await nextTurn();
const current = voice.setOutputDevice("speaker-b");
oldSink.reject(new Error("Old output unavailable"));
await Promise.all([old, current]);
assert.equal(voice.selectedOutputDeviceId.value, "speaker-b");
assert.equal(localStorage.getItem("webspeak:output-device"), "speaker-b");
});
test("overlapping output switches leave the actual sink on the latest device", async t => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
await voice.ensureMicrophone();
const ctx = AudioContextStub.instances.at(-1);
const oldSink = deferred();
t.mock.method(ctx, "setSinkId", async id => { if (id === "speaker-a") await oldSink.promise; ctx.sinkId = id; });
const old = voice.setOutputDevice("speaker-a");
await nextTurn();
const current = voice.setOutputDevice("speaker-b");
oldSink.resolve();
await Promise.all([old, current]);
assert.equal(ctx.sinkId, "speaker-b");
assert.equal(voice.selectedOutputDeviceId.value, "speaker-b");
});
test("an older device enumeration cannot replace a newer device list", async () => {
const oldDevices = deferred();
let calls = 0;
navigator.mediaDevices.enumerateDevices = () => ++calls === 1 ? oldDevices.promise : Promise.resolve(availableDevices);
const old = voice.refreshAudioDevices();
await voice.refreshAudioDevices();
oldDevices.resolve([]);
await old;
assert.deepEqual(voice.inputDevices.map(device => device.deviceId), ["mic-a", "mic-b"]);
});
test("device enumeration rejected after disconnect cannot restore an audio notice", async () => {
const devices = deferred();
navigator.mediaDevices.enumerateDevices = () => devices.promise;
const pending = voice.refreshAudioDevices();
voice.disconnect();
devices.reject(new Error("Old device query rejected"));
await pending;
assert.equal(voice.state.audioNoticeCode, "");
});
test("a successful microphone switch replaces the WebRTC peer and persists the new device", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
const initial = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => initial;
const { peer: old, socket } = await connectWebRtc();
const replacement = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => replacement;
await voice.setInputDevice("mic-b");
assert.equal(old.connectionState, "closed");
assert.notEqual(TestPeer.instances.at(-1), old);
assert.equal(initial.track.readyState, "ended");
assert.equal(replacement.track.readyState, "live");
assert.equal(socket.messages.filter(message => message.type === "webrtcOffer").length, 2);
assert.equal(localStorage.getItem("webspeak:input-device"), "mic-b");
});
test("a failed replacement input restores the last working device instead of another pending choice", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
await voice.ensureMicrophone();
const permission = deferred();
navigator.mediaDevices.getUserMedia = ({ audio }) => audio.deviceId.exact === "mic-a"
? permission.promise : Promise.reject(new Error("Replacement failed"));
const old = voice.setInputDevice("mic-a");
await assert.rejects(voice.setInputDevice("mic-b"), /Replacement failed/);
const late = microphoneStream();
permission.resolve(late);
await old;
assert.equal(voice.selectedInputDeviceId.value, "");
assert.equal(localStorage.getItem("webspeak:input-device"), "");
assert.equal(late.track.readyState, "ended");
});
test("disconnect skips queued output changes and keeps only the last committed device", async t => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
await voice.ensureMicrophone();
const ctx = AudioContextStub.instances.at(-1);
const oldSink = deferred();
const applied = [];
t.mock.method(ctx, "setSinkId", async id => { applied.push(id); await oldSink.promise; });
const first = voice.setOutputDevice("speaker-a");
await nextTurn();
const second = voice.setOutputDevice("speaker-b");
voice.disconnect();
oldSink.resolve();
await Promise.all([first, second]);
assert.deepEqual(applied, ["speaker-a"]);
assert.equal(voice.selectedOutputDeviceId.value, "");
assert.equal(localStorage.getItem("webspeak:output-device"), null);
});
test("failure on the WebRTC output restores the previously committed context sink", async t => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
const { peer } = await connectWebRtc();
peer.ontrack({ streams: [microphoneStream()] });
const output = [...audioElements][0];
output.setSinkId = async id => { if (id === "speaker-a") throw new Error("Output denied"); output.sinkId = id; };
const ctx = AudioContextStub.instances.at(-1);
await assert.rejects(voice.setOutputDevice("speaker-a"), /Output denied/);
assert.equal(ctx.sinkId, "default");
assert.equal(output.sinkId, "default");
assert.equal(voice.selectedOutputDeviceId.value, "");
});
test("a failed noise suppression change restores its setting and preserves WebRTC capture", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
const initial = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => initial;
const { peer } = await connectWebRtc();
navigator.mediaDevices.getUserMedia = async () => { throw new Error("Capture reconfiguration failed"); };
await voice.setNoiseSuppressionEnabled(false);
assert.notEqual(peer.connectionState, "closed");
assert.equal(voice.noiseSuppressionEnabled.value, true);
assert.equal(initial.track.readyState, "live");
assert.notEqual(voice.state.microphoneErrorCode, "");
});
test("changing processing during an input switch commits the device actually acquired", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
await voice.ensureMicrophone();
const permission = deferred();
let calls = 0;
navigator.mediaDevices.getUserMedia = () => ++calls === 1 ? permission.promise : Promise.resolve(microphoneStream());
const input = voice.setInputDevice("mic-a");
await voice.setNoiseSuppressionEnabled(false);
const late = microphoneStream();
permission.resolve(late);
await input;
assert.equal(localStorage.getItem("webspeak:input-device"), "mic-a");
assert.equal(late.track.readyState, "ended");
voice.disconnect();
assert.equal(voice.selectedInputDeviceId.value, "mic-a");
});
test("closing audio settings releases standalone capture even without a recording test", async () => {
const stream = microphoneStream();
navigator.mediaDevices.getUserMedia = async () => stream;
await voice.prepareInputDevices();
voice.stopMicrophoneTest();
assert.equal(stream.track.readyState, "ended");
});
test("compatibility capture keeps sending while a replacement permission is pending or fails", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
const capture = AudioContextStub.processors.at(-1);
const permission = deferred();
navigator.mediaDevices.getUserMedia = () => permission.promise;
const pending = voice.setInputDevice("mic-a");
const rejected = assert.rejects(pending, /Device denied/);
const samples = new Float32Array(960).fill(0.25);
capture.onaudioprocess({ inputBuffer: { getChannelData: () => samples } });
const beforeFailure = socket.messages.filter(message => message instanceof ArrayBuffer).length;
permission.reject(new Error("Device denied"));
await rejected;
capture.onaudioprocess({ inputBuffer: { getChannelData: () => samples } });
assert.equal(beforeFailure, 1);
assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 2);
});
test("replacing compatibility capture prevents the old graph from sending into the new session", async () => {
navigator.mediaDevices.enumerateDevices = async () => availableDevices;
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
const old = AudioContextStub.processors.at(-1);
await voice.setInputDevice("mic-b");
const current = AudioContextStub.processors.at(-1);
const event = { inputBuffer: { getChannelData: () => new Float32Array(960).fill(0.25) } };
old.onaudioprocess(event);
current.onaudioprocess(event);
assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1);
voice.disconnect();
current.onaudioprocess(event);
assert.equal(socket.messages.filter(message => message instanceof ArrayBuffer).length, 1);
});