mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
fix: isolate remote playback and microphone recording lifecycles
This commit is contained in:
1 parent
f0712fa3fc
commit
797fc135a9
7 files changed
+621
-199
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import { createRemotePlayback } from "../voice/remote-playback.js";
|
||||
import { createMicrophoneTest } from "../voice/microphone-test.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";
|
||||
@@ -307,8 +309,13 @@ export function useVoiceWebSocket() {
|
||||
const micLevel = ref(0);
|
||||
const microphoneTestActive = ref(false);
|
||||
const testAudioUrl = ref("");
|
||||
let testRecorder: MediaRecorder | null = null;
|
||||
let testRecorderTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const microphoneTest = createMicrophoneTest({
|
||||
prepare: async () => { await prepareInputDevices(); return micStream; },
|
||||
onActive: active => { microphoneTestActive.value = active; },
|
||||
onUrl: url => { testAudioUrl.value = url; },
|
||||
onStopped: () => { if (!state.connected) stopMicrophone(); },
|
||||
onError: error => { setMicrophoneError(error); },
|
||||
});
|
||||
const microphoneMuted = ref(false);
|
||||
const noiseSuppressionEnabled = ref(true);
|
||||
const inputVolume = ref(1);
|
||||
@@ -324,15 +331,6 @@ export function useVoiceWebSocket() {
|
||||
let accumBuf = new Int16Array(2048);
|
||||
let accumLen = 0;
|
||||
|
||||
// Playback is kept per client so frames from multiple speakers cannot
|
||||
// interleave into one decoder or one scheduling queue.
|
||||
const remoteDecoders = new Map<number, AudioDecoder>();
|
||||
const remoteDecoderGenerations = new Map<number, number>();
|
||||
let nextRemoteDecoderGeneration = 0;
|
||||
const remotePlayTimes = new Map<number, number>();
|
||||
const remotePlaybackSources = new Map<number, Set<AudioBufferSourceNode>>();
|
||||
const remoteGains = new Map<number, GainNode>();
|
||||
const remoteDecodeTimestamps = new Map<number, number>();
|
||||
const volumes = reactive<Record<number, number>>({});
|
||||
const speakingIds = reactive(new Set<number>());
|
||||
const whisperTargetIds = reactive(new Set<number>());
|
||||
@@ -343,11 +341,12 @@ export function useVoiceWebSocket() {
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const MAX_AUDIO_BUFFERED_FRAMES = 10;
|
||||
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
|
||||
// Keep the WebSocket playback buffer below the 100 ms latency target. A
|
||||
// 20 ms frame plus three queued decoder frames leaves only a short cushion
|
||||
// for jitter; stale audio is discarded instead of being played late.
|
||||
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
|
||||
const MAX_REMOTE_DECODE_QUEUE_FRAMES = 3;
|
||||
const remotePlayback = createRemotePlayback({
|
||||
getContext: getAudioCtx,
|
||||
getVolume: clientId => (volumes[clientId] ?? 1) * effectiveOutputVolume(),
|
||||
onDecodeError: () => { fallbackAudioDecodeErrors++; },
|
||||
onDrop: () => { fallbackAudioFramesDropped++; },
|
||||
});
|
||||
|
||||
async function saveAudioPreferences(): Promise<void> {
|
||||
await saveLocalPreferences({
|
||||
@@ -417,7 +416,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function applyOutputVolume(): void {
|
||||
const level = effectiveOutputVolume();
|
||||
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * level;
|
||||
remotePlayback.updateVolumes();
|
||||
if (webrtcOutputElement) webrtcOutputElement.volume = level;
|
||||
}
|
||||
|
||||
@@ -1288,41 +1287,11 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function startMicrophoneTest(): Promise<void> {
|
||||
microphoneTestActive.value = true;
|
||||
if (testAudioUrl.value) {
|
||||
URL.revokeObjectURL(testAudioUrl.value);
|
||||
testAudioUrl.value = "";
|
||||
}
|
||||
try {
|
||||
await prepareInputDevices();
|
||||
if (typeof MediaRecorder !== "undefined" && micStream) {
|
||||
const chunks: Blob[] = [];
|
||||
const recorder = new MediaRecorder(micStream);
|
||||
testRecorder = recorder;
|
||||
recorder.ondataavailable = (event) => {
|
||||
if (event.data.size) chunks.push(event.data);
|
||||
};
|
||||
recorder.onstop = () => {
|
||||
if (chunks.length) {
|
||||
testAudioUrl.value = URL.createObjectURL(new Blob(chunks, { type: recorder.mimeType || "audio/webm" }));
|
||||
}
|
||||
if (testRecorder === recorder) testRecorder = null;
|
||||
};
|
||||
recorder.start();
|
||||
testRecorderTimer = setTimeout(() => stopMicrophoneTest(), 5_000);
|
||||
}
|
||||
} catch (error) {
|
||||
microphoneTestActive.value = false;
|
||||
throw error;
|
||||
}
|
||||
await microphoneTest.start();
|
||||
}
|
||||
|
||||
function stopMicrophoneTest(): void {
|
||||
microphoneTestActive.value = false;
|
||||
if (testRecorderTimer) clearTimeout(testRecorderTimer);
|
||||
testRecorderTimer = null;
|
||||
if (testRecorder && testRecorder.state !== "inactive") testRecorder.stop();
|
||||
if (!state.connected) stopMicrophone();
|
||||
microphoneTest.stop();
|
||||
}
|
||||
|
||||
async function setOutputDevice(deviceId: string): Promise<void> {
|
||||
@@ -1371,122 +1340,6 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
}
|
||||
|
||||
function playAudioFrame(clientId: number, opusData: Uint8Array): void {
|
||||
if (opusData.length < 3) {
|
||||
fallbackAudioFramesDropped++;
|
||||
return;
|
||||
}
|
||||
let decoder = remoteDecoders.get(clientId);
|
||||
const ctx = getAudioCtx();
|
||||
const now = ctx.currentTime;
|
||||
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
|
||||
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
|
||||
if (
|
||||
decoder &&
|
||||
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
|
||||
) {
|
||||
resetRemotePlayback(clientId);
|
||||
decoder = undefined;
|
||||
}
|
||||
|
||||
if (!decoder) {
|
||||
const gainNode = ctx.createGain();
|
||||
gainNode.gain.value = (volumes[clientId] ?? 1) * effectiveOutputVolume();
|
||||
gainNode.connect(ctx.destination);
|
||||
remoteGains.set(clientId, gainNode);
|
||||
const generation = ++nextRemoteDecoderGeneration;
|
||||
const nextDecoder = new AudioDecoder({
|
||||
output: (chunk: AudioData) => {
|
||||
if (remoteDecoderGenerations.get(clientId) !== generation) {
|
||||
chunk.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
for (let ch = 0; ch < numberOfChannels; ch++) {
|
||||
const data = new Float32Array(numberOfFrames);
|
||||
chunk.copyTo(data, { planeIndex: ch, format: "f32-planar" });
|
||||
buffer.copyToChannel(data, ch);
|
||||
}
|
||||
const source = ctx.createBufferSource();
|
||||
source.buffer = buffer;
|
||||
source.connect(gainNode);
|
||||
let sources = remotePlaybackSources.get(clientId);
|
||||
if (!sources) {
|
||||
sources = new Set<AudioBufferSourceNode>();
|
||||
remotePlaybackSources.set(clientId, sources);
|
||||
}
|
||||
sources.add(source);
|
||||
source.addEventListener("ended", () => {
|
||||
source.disconnect();
|
||||
sources?.delete(source);
|
||||
if (sources?.size === 0) remotePlaybackSources.delete(clientId);
|
||||
}, { once: true });
|
||||
let playTime = remotePlayTimes.get(clientId) ?? ctx.currentTime;
|
||||
if (playTime < ctx.currentTime) playTime = ctx.currentTime;
|
||||
if (playTime + numberOfFrames / sampleRate > ctx.currentTime + MAX_REMOTE_PLAY_AHEAD_SECONDS) {
|
||||
source.disconnect();
|
||||
sources.delete(source);
|
||||
if (sources.size === 0) remotePlaybackSources.delete(clientId);
|
||||
chunk.close();
|
||||
resetRemotePlayback(clientId);
|
||||
return;
|
||||
}
|
||||
source.start(playTime);
|
||||
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
|
||||
} catch {
|
||||
// A decoder can finish while the audio context is being torn down.
|
||||
}
|
||||
chunk.close();
|
||||
},
|
||||
error: () => {
|
||||
if (remoteDecoderGenerations.get(clientId) === generation) {
|
||||
fallbackAudioDecodeErrors++;
|
||||
remoteDecoderGenerations.delete(clientId);
|
||||
remoteDecoders.delete(clientId);
|
||||
}
|
||||
},
|
||||
});
|
||||
nextDecoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
|
||||
decoder = nextDecoder;
|
||||
remoteDecoderGenerations.set(clientId, generation);
|
||||
remoteDecoders.set(clientId, decoder);
|
||||
}
|
||||
|
||||
try {
|
||||
const timestamp = remoteDecodeTimestamps.get(clientId) ?? 0;
|
||||
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
|
||||
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
|
||||
} catch {
|
||||
fallbackAudioDecodeErrors++;
|
||||
// Ignore malformed frames; the next valid frame can still be decoded.
|
||||
}
|
||||
}
|
||||
|
||||
function clearRemotePlayback(clientId: number): void {
|
||||
const decoder = remoteDecoders.get(clientId);
|
||||
if (decoder) {
|
||||
try { decoder.close(); } catch { /* already closed */ }
|
||||
}
|
||||
remoteDecoders.delete(clientId);
|
||||
remoteDecoderGenerations.delete(clientId);
|
||||
remotePlayTimes.delete(clientId);
|
||||
remoteDecodeTimestamps.delete(clientId);
|
||||
const sources = remotePlaybackSources.get(clientId);
|
||||
if (sources) {
|
||||
for (const source of sources) {
|
||||
try { source.stop(); } catch { /* already ended */ }
|
||||
source.disconnect();
|
||||
}
|
||||
remotePlaybackSources.delete(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
function resetRemotePlayback(clientId: number): void {
|
||||
clearRemotePlayback(clientId);
|
||||
}
|
||||
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = "", accelerated = false, accelerationRelayId = ""): void {
|
||||
disconnect(true);
|
||||
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity, accelerated, accelerationRelayId };
|
||||
@@ -1668,16 +1521,12 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** All ways a session ends release the same owned media and pending work. */
|
||||
function releaseSessionResources(sendScreenStop = false): void {
|
||||
microphoneTest.dispose();
|
||||
clearAudioStatusProbes();
|
||||
rejectPendingCommands(new Error("语音连接已关闭"));
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
stopWebRtcTransport();
|
||||
for (const clientId of new Set([...remoteDecoders.keys(), ...remotePlaybackSources.keys()])) clearRemotePlayback(clientId);
|
||||
remoteDecoderGenerations.clear();
|
||||
remotePlayTimes.clear();
|
||||
remoteDecodeTimestamps.clear();
|
||||
for (const gain of remoteGains.values()) gain.disconnect();
|
||||
remoteGains.clear();
|
||||
remotePlayback.clearAll();
|
||||
stopMicrophone();
|
||||
clearSpeakingState();
|
||||
whisperTargetIds.clear();
|
||||
@@ -1758,7 +1607,7 @@ export function useVoiceWebSocket() {
|
||||
case "memberLeave": {
|
||||
const clientId = Number(msg.id);
|
||||
clearSpeaking(clientId);
|
||||
clearRemotePlayback(clientId);
|
||||
remotePlayback.clear(clientId);
|
||||
const index = members.findIndex((member) => member.id === clientId);
|
||||
if (index >= 0) members.splice(index, 1);
|
||||
break;
|
||||
@@ -1932,7 +1781,7 @@ export function useVoiceWebSocket() {
|
||||
if (clientId === state.tsClientId) return;
|
||||
fallbackAudioFramesReceived++;
|
||||
markSpeaking(clientId);
|
||||
playAudioFrame(clientId, data.slice(3));
|
||||
remotePlayback.play(clientId, data.slice(3));
|
||||
}
|
||||
|
||||
function sendCmd<K extends ClientCommandType>(type: K, payload: ClientCommandPayloads[K], requestId = ""): void {
|
||||
@@ -2206,8 +2055,7 @@ export function useVoiceWebSocket() {
|
||||
storedVolumesByUid[member.uid] = normalized;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
const gain = remoteGains.get(clientId);
|
||||
if (gain) gain.gain.value = normalized * effectiveOutputVolume();
|
||||
remotePlayback.updateVolume(clientId);
|
||||
if (webrtcPeer || webrtcActive.value) sendCmd("setMemberVolume", { clientId, volume: normalized });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
interface MicrophoneTestOptions {
|
||||
prepare(): Promise<MediaStream | null>;
|
||||
onActive(active: boolean): void;
|
||||
onUrl(url: string): void;
|
||||
onStopped(): void;
|
||||
onError(error: unknown): void;
|
||||
}
|
||||
|
||||
interface Recording {
|
||||
recorder: MediaRecorder | null;
|
||||
timer: number | null;
|
||||
chunks: Blob[];
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
// Capture belongs to the caller. This controller owns only the test operation,
|
||||
// recorder, deadline and playback URL, including results queued after stop().
|
||||
export function createMicrophoneTest(options: MicrophoneTestOptions) {
|
||||
let current: Recording | null = null;
|
||||
let url = "";
|
||||
|
||||
function clearUrl(): void {
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
options.onUrl("");
|
||||
}
|
||||
|
||||
function finishCapture(recording: Recording): void {
|
||||
if (recording.timer !== null) window.clearTimeout(recording.timer);
|
||||
recording.timer = null;
|
||||
if (recording.stopped) return;
|
||||
recording.stopped = true;
|
||||
options.onActive(false);
|
||||
options.onStopped();
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
const recording = current;
|
||||
current = null;
|
||||
if (recording) {
|
||||
finishCapture(recording);
|
||||
if (recording.recorder?.state !== "inactive") {
|
||||
try { recording.recorder?.stop(); } catch { /* already ended */ }
|
||||
}
|
||||
recording.chunks.length = 0;
|
||||
}
|
||||
clearUrl();
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
const recording = current;
|
||||
if (!recording) return;
|
||||
// A pending permission or device enumeration must not create a recorder.
|
||||
if (!recording.recorder) current = null;
|
||||
finishCapture(recording);
|
||||
if (recording.recorder?.state !== "inactive") {
|
||||
try { recording.recorder?.stop(); }
|
||||
catch (error) { dispose(); options.onError(error); }
|
||||
}
|
||||
}
|
||||
|
||||
async function start(): Promise<void> {
|
||||
dispose();
|
||||
const recording: Recording = { recorder: null, timer: null, chunks: [], stopped: false };
|
||||
current = recording;
|
||||
options.onActive(true);
|
||||
try {
|
||||
const stream = await options.prepare();
|
||||
if (current !== recording) return;
|
||||
// Keep the existing level-meter-only test on browsers without recording.
|
||||
if (typeof MediaRecorder === "undefined" || !stream) return;
|
||||
const recorder = new MediaRecorder(stream);
|
||||
recording.recorder = recorder;
|
||||
recorder.ondataavailable = event => {
|
||||
if (current === recording && event.data.size) recording.chunks.push(event.data);
|
||||
};
|
||||
recorder.onstop = () => {
|
||||
if (current !== recording) return;
|
||||
current = null;
|
||||
finishCapture(recording);
|
||||
try {
|
||||
if (recording.chunks.length) {
|
||||
clearUrl();
|
||||
url = URL.createObjectURL(new Blob(recording.chunks, { type: recorder.mimeType || "audio/webm" }));
|
||||
options.onUrl(url);
|
||||
}
|
||||
} catch (error) { options.onError(error); }
|
||||
recording.chunks.length = 0;
|
||||
};
|
||||
recorder.onerror = event => {
|
||||
if (current !== recording) return;
|
||||
dispose();
|
||||
options.onError("error" in event ? event.error : new Error("Microphone recording failed"));
|
||||
};
|
||||
recorder.start();
|
||||
recording.timer = window.setTimeout(() => {
|
||||
if (current === recording) stop();
|
||||
}, 5_000);
|
||||
} catch (error) {
|
||||
if (current !== recording) return;
|
||||
dispose();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return { start, stop, dispose };
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
interface RemotePlaybackOptions {
|
||||
getContext(): AudioContext;
|
||||
getVolume(clientId: number): number;
|
||||
onDecodeError(): void;
|
||||
onDrop(): void;
|
||||
}
|
||||
|
||||
interface SpeakerPlayback {
|
||||
context: AudioContext;
|
||||
decoder: AudioDecoder | null;
|
||||
gain: GainNode;
|
||||
sources: Set<AudioBufferSourceNode>;
|
||||
playTime: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
// Preserve the compatibility path's bounded jitter buffer and decoder queue.
|
||||
const MAX_PLAY_AHEAD_SECONDS = 0.08;
|
||||
const MAX_DECODE_QUEUE_FRAMES = 3;
|
||||
|
||||
export function createRemotePlayback(options: RemotePlaybackOptions) {
|
||||
const speakers = new Map<number, SpeakerPlayback>();
|
||||
|
||||
function clear(clientId: number): void {
|
||||
const stream = speakers.get(clientId);
|
||||
if (!stream) return;
|
||||
// Invalidate callbacks before closing their resources.
|
||||
speakers.delete(clientId);
|
||||
try { stream.decoder?.close(); } catch { /* decoder may already be closed */ }
|
||||
for (const source of stream.sources) {
|
||||
try { source.stop(); } catch { /* not started or already ended */ }
|
||||
source.disconnect();
|
||||
}
|
||||
stream.sources.clear();
|
||||
stream.gain.disconnect();
|
||||
}
|
||||
|
||||
function output(clientId: number, stream: SpeakerPlayback, chunk: AudioData): void {
|
||||
try {
|
||||
if (speakers.get(clientId) !== stream) return;
|
||||
const { context, gain, sources } = stream;
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
const playTime = Math.max(stream.playTime, context.currentTime);
|
||||
const duration = numberOfFrames / sampleRate;
|
||||
if (playTime + duration > context.currentTime + MAX_PLAY_AHEAD_SECONDS) {
|
||||
clear(clientId);
|
||||
return;
|
||||
}
|
||||
const buffer = context.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
for (let channel = 0; channel < numberOfChannels; channel++) {
|
||||
const samples = new Float32Array(numberOfFrames);
|
||||
chunk.copyTo(samples, { planeIndex: channel, format: "f32-planar" });
|
||||
buffer.copyToChannel(samples, channel);
|
||||
}
|
||||
const source = context.createBufferSource();
|
||||
sources.add(source);
|
||||
source.buffer = buffer;
|
||||
source.connect(gain);
|
||||
source.addEventListener("ended", () => {
|
||||
source.disconnect();
|
||||
// The old stream owns this set; never delete a replacement's resources.
|
||||
sources.delete(source);
|
||||
}, { once: true });
|
||||
source.start(playTime);
|
||||
stream.playTime = playTime + duration;
|
||||
} catch {
|
||||
if (speakers.get(clientId) === stream) {
|
||||
options.onDecodeError();
|
||||
clear(clientId);
|
||||
}
|
||||
} finally {
|
||||
chunk.close();
|
||||
}
|
||||
}
|
||||
|
||||
function create(clientId: number, context: AudioContext): SpeakerPlayback {
|
||||
const stream: SpeakerPlayback = {
|
||||
context, decoder: null, gain: context.createGain(), sources: new Set(),
|
||||
playTime: context.currentTime, timestamp: 0,
|
||||
};
|
||||
speakers.set(clientId, stream);
|
||||
stream.gain.gain.value = options.getVolume(clientId);
|
||||
stream.gain.connect(context.destination);
|
||||
stream.decoder = new AudioDecoder({
|
||||
output: chunk => output(clientId, stream, chunk),
|
||||
error: () => {
|
||||
if (speakers.get(clientId) !== stream) return;
|
||||
options.onDecodeError();
|
||||
clear(clientId);
|
||||
},
|
||||
});
|
||||
stream.decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
|
||||
return stream;
|
||||
}
|
||||
|
||||
function play(clientId: number, opusData: Uint8Array): void {
|
||||
if (opusData.length < 3) { options.onDrop(); return; }
|
||||
try {
|
||||
const context = options.getContext();
|
||||
let stream = speakers.get(clientId);
|
||||
if (stream && (stream.context !== context || stream.playTime > context.currentTime + MAX_PLAY_AHEAD_SECONDS || (stream.decoder?.decodeQueueSize ?? 0) >= MAX_DECODE_QUEUE_FRAMES)) {
|
||||
clear(clientId);
|
||||
stream = undefined;
|
||||
}
|
||||
stream ??= create(clientId, context);
|
||||
if (speakers.get(clientId) !== stream) return;
|
||||
stream.decoder?.decode(new EncodedAudioChunk({ type: "key", timestamp: stream.timestamp, duration: 20_000, data: opusData }));
|
||||
stream.timestamp += 20_000;
|
||||
} catch {
|
||||
options.onDecodeError();
|
||||
clear(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
play,
|
||||
clear,
|
||||
clearAll() { for (const id of speakers.keys()) clear(id); },
|
||||
updateVolume(clientId: number) {
|
||||
const stream = speakers.get(clientId);
|
||||
if (stream) stream.gain.gain.value = options.getVolume(clientId);
|
||||
},
|
||||
updateVolumes() { for (const [id, stream] of speakers) stream.gain.gain.value = options.getVolume(id); },
|
||||
};
|
||||
}
|
||||
@@ -32,12 +32,52 @@ class TestTrack extends EventTarget {
|
||||
|
||||
class AudioNodeStub {
|
||||
gain = { value: 1 };
|
||||
disconnects = 0;
|
||||
connect() {}
|
||||
disconnect() {}
|
||||
disconnect() { this.disconnects++; }
|
||||
}
|
||||
class AudioSourceStub extends EventTarget {
|
||||
static failStart = false;
|
||||
stopped = 0;
|
||||
disconnects = 0;
|
||||
connect() {}
|
||||
disconnect() { this.disconnects++; }
|
||||
start(time) { if (AudioSourceStub.failStart) throw new Error("Source cannot start"); this.startedAt = time; }
|
||||
stop() { this.stopped++; }
|
||||
}
|
||||
class AudioDecoderStub {
|
||||
static instances = [];
|
||||
static failConfigure = false;
|
||||
decodeQueueSize = 0;
|
||||
closed = 0;
|
||||
constructor(callbacks) { this.callbacks = callbacks; AudioDecoderStub.instances.push(this); }
|
||||
configure() { if (AudioDecoderStub.failConfigure) throw new Error("Codec unavailable"); }
|
||||
decode(chunk) { this.lastChunk = chunk; }
|
||||
close() { this.closed++; }
|
||||
}
|
||||
class RecorderStub {
|
||||
static instances = [];
|
||||
static failStart = false;
|
||||
state = "inactive";
|
||||
mimeType = "audio/webm";
|
||||
stops = 0;
|
||||
constructor(stream) { this.stream = stream; RecorderStub.instances.push(this); }
|
||||
start() { if (RecorderStub.failStart) throw new Error("Recorder start failed"); this.state = "recording"; }
|
||||
stop() { this.stops++; this.state = "inactive"; }
|
||||
finish() { this.state = "inactive"; this.ondataavailable?.({ data: new Blob(["audio"]) }); this.onstop?.(); }
|
||||
}
|
||||
function decodedChunk() {
|
||||
return { sampleRate: 48000, numberOfChannels: 1, numberOfFrames: 960, closed: 0, copyTo() {}, close() { this.closed++; } };
|
||||
}
|
||||
function receiveAudio(socket, clientId = 7) {
|
||||
socket.onmessage({ data: new Uint8Array([4, clientId >> 8, clientId & 255, 1, 2, 3]).buffer });
|
||||
}
|
||||
class AudioContextStub extends EventTarget {
|
||||
static processors = [];
|
||||
static sources = [];
|
||||
static gains = [];
|
||||
state = "running";
|
||||
currentTime = 0;
|
||||
sampleRate = 48000;
|
||||
destination = new AudioNodeStub();
|
||||
close() { this.state = "closed"; return Promise.resolve(); }
|
||||
@@ -46,7 +86,9 @@ class AudioContextStub extends EventTarget {
|
||||
return new AudioNodeStub();
|
||||
}
|
||||
createMediaStreamDestination() { return Object.assign(new AudioNodeStub(), { stream: microphoneStream() }); }
|
||||
createGain() { return new AudioNodeStub(); }
|
||||
createGain() { const node = new AudioNodeStub(); AudioContextStub.gains.push(node); return node; }
|
||||
createBuffer(channels, frames, sampleRate) { return { duration: frames / sampleRate, copyToChannel() {} }; }
|
||||
createBufferSource() { const node = new AudioSourceStub(); AudioContextStub.sources.push(node); return node; }
|
||||
createScriptProcessor() { const node = new AudioNodeStub(); AudioContextStub.processors.push(node); return node; }
|
||||
}
|
||||
function microphoneStream() {
|
||||
@@ -119,6 +161,13 @@ beforeEach(() => {
|
||||
TestSocket.instances.length = 0;
|
||||
TestPeer.instances.length = 0;
|
||||
AudioContextStub.processors.length = 0;
|
||||
AudioContextStub.sources.length = 0;
|
||||
AudioContextStub.gains.length = 0;
|
||||
AudioDecoderStub.instances.length = 0;
|
||||
AudioDecoderStub.failConfigure = false;
|
||||
AudioSourceStub.failStart = false;
|
||||
RecorderStub.instances.length = 0;
|
||||
RecorderStub.failStart = false;
|
||||
audioElements.clear();
|
||||
replaceGlobal("RTCPeerConnection", TestPeer);
|
||||
replaceGlobal("window", Object.assign(new EventTarget(), {
|
||||
@@ -137,6 +186,9 @@ beforeEach(() => {
|
||||
replaceGlobal("location", { protocol: "https:", host: "gateway.example" });
|
||||
replaceGlobal("fetch", async () => ({ ok: true, json: async () => ({ ticket: "test-ticket" }) }));
|
||||
replaceGlobal("AudioContext", AudioContextStub);
|
||||
replaceGlobal("AudioDecoder", AudioDecoderStub);
|
||||
replaceGlobal("MediaRecorder", RecorderStub);
|
||||
replaceGlobal("EncodedAudioChunk", class { constructor(init) { Object.assign(this, init); } });
|
||||
replaceGlobal("HTMLMediaElement", class {});
|
||||
replaceGlobal("navigator", { mediaDevices: {
|
||||
getDisplayMedia: async () => displayStream(),
|
||||
@@ -147,6 +199,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
voice?.stopMicrophoneTest();
|
||||
voice?.disconnect();
|
||||
for (const timer of browserTimers) clearTimeout(timer);
|
||||
browserTimers.clear();
|
||||
@@ -436,3 +489,253 @@ test("an offer rejected after a new connection opens cannot report a microphone
|
||||
assert.equal(voice.state.microphoneErrorCode, "");
|
||||
assert.equal(voice.state.audioNoticeCode, "");
|
||||
});
|
||||
|
||||
|
||||
test("resetting an overloaded remote decoder disconnects its old gain", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const gain = AudioContextStub.gains.at(-1);
|
||||
AudioDecoderStub.instances.at(-1).decodeQueueSize = 3;
|
||||
receiveAudio(socket);
|
||||
assert.equal(gain.disconnects, 1);
|
||||
assert.equal(AudioDecoderStub.instances.length, 2);
|
||||
});
|
||||
|
||||
test("an old source ending cannot hide replacement playback from session cleanup", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const first = AudioDecoderStub.instances.at(-1);
|
||||
first.callbacks.output(decodedChunk());
|
||||
const oldSource = AudioContextStub.sources.at(-1);
|
||||
first.decodeQueueSize = 3;
|
||||
receiveAudio(socket);
|
||||
AudioDecoderStub.instances.at(-1).callbacks.output(decodedChunk());
|
||||
const replacement = AudioContextStub.sources.at(-1);
|
||||
oldSource.dispatchEvent(new Event("ended"));
|
||||
voice.disconnect();
|
||||
assert.equal(replacement.stopped, 1);
|
||||
});
|
||||
|
||||
test("decoder failure releases the speaker's queued sources and gain immediately", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const decoder = AudioDecoderStub.instances.at(-1);
|
||||
decoder.callbacks.output(decodedChunk());
|
||||
const source = AudioContextStub.sources.at(-1);
|
||||
const gain = AudioContextStub.gains.at(-1);
|
||||
decoder.callbacks.error(new Error("Decode failed"));
|
||||
assert.equal(source.stopped, 1);
|
||||
assert.equal(gain.disconnects, 1);
|
||||
});
|
||||
|
||||
test("codec configuration failure is contained and releases the partially created stream", async () => {
|
||||
const socket = await connect();
|
||||
AudioDecoderStub.failConfigure = true;
|
||||
assert.doesNotThrow(() => receiveAudio(socket));
|
||||
assert.equal(AudioDecoderStub.instances.at(-1).closed, 1);
|
||||
assert.equal(AudioContextStub.gains.at(-1).disconnects, 1);
|
||||
AudioDecoderStub.failConfigure = false;
|
||||
receiveAudio(socket);
|
||||
assert.equal(AudioDecoderStub.instances.length, 2);
|
||||
});
|
||||
|
||||
test("a failed audio source start does not retain a connected playback node", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
AudioSourceStub.failStart = true;
|
||||
const chunk = decodedChunk();
|
||||
AudioDecoderStub.instances.at(-1).callbacks.output(chunk);
|
||||
assert.ok(AudioContextStub.sources.at(-1).disconnects > 0);
|
||||
assert.equal(chunk.closed, 1);
|
||||
});
|
||||
|
||||
test("late decoded chunks after disconnect close without creating playback", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const old = AudioDecoderStub.instances.at(-1);
|
||||
voice.disconnect();
|
||||
const chunk = decodedChunk();
|
||||
old.callbacks.output(chunk);
|
||||
assert.equal(chunk.closed, 1);
|
||||
assert.equal(AudioContextStub.sources.length, 0);
|
||||
});
|
||||
|
||||
test("a departing speaker releases only its own playback", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "memberEnter", id: 7, nickname: "Leaving" });
|
||||
socket.receive({ type: "memberEnter", id: 8, nickname: "Staying" });
|
||||
receiveAudio(socket, 7);
|
||||
receiveAudio(socket, 8);
|
||||
const [leaving, staying] = AudioDecoderStub.instances;
|
||||
leaving.callbacks.output(decodedChunk());
|
||||
staying.callbacks.output(decodedChunk());
|
||||
const [oldSource, currentSource] = AudioContextStub.sources;
|
||||
socket.receive({ type: "memberLeave", id: 7 });
|
||||
assert.deepEqual(voice.members.map(member => member.id), [8]);
|
||||
assert.equal(leaving.closed, 1);
|
||||
assert.equal(oldSource.stopped, 1);
|
||||
assert.equal(staying.closed, 0);
|
||||
assert.equal(currentSource.stopped, 0);
|
||||
});
|
||||
|
||||
test("remote playback preserves member volume through output mute and decoder reset", async () => {
|
||||
const socket = await connect();
|
||||
voice.setVolume(7, 0.4);
|
||||
voice.setOutputVolume(0.5);
|
||||
receiveAudio(socket, 7);
|
||||
receiveAudio(socket, 8);
|
||||
assert.deepEqual(AudioContextStub.gains.map(node => node.gain.value), [0.2, 0.5]);
|
||||
voice.toggleOutputMute();
|
||||
assert.deepEqual(AudioContextStub.gains.map(node => node.gain.value), [0, 0]);
|
||||
const old = AudioDecoderStub.instances[0];
|
||||
old.decodeQueueSize = 3;
|
||||
receiveAudio(socket, 7);
|
||||
const replacement = AudioDecoderStub.instances.at(-1);
|
||||
old.callbacks.error(new Error("stale decoder error"));
|
||||
assert.equal(replacement.closed, 0);
|
||||
assert.equal(AudioContextStub.gains.at(-1).gain.value, 0);
|
||||
voice.toggleOutputMute();
|
||||
assert.equal(AudioContextStub.gains.at(-1).gain.value, 0.2);
|
||||
assert.equal(AudioContextStub.gains[1].gain.value, 0.5);
|
||||
});
|
||||
|
||||
test("decoded audio stays within the 80 ms playback window and recovers after overflow", async () => {
|
||||
const socket = await connect();
|
||||
receiveAudio(socket);
|
||||
const decoder = AudioDecoderStub.instances[0];
|
||||
const chunks = Array.from({ length: 5 }, decodedChunk);
|
||||
for (const chunk of chunks) decoder.callbacks.output(chunk);
|
||||
assert.deepEqual(AudioContextStub.sources.map(source => source.startedAt), [0, 0.02, 0.04, 0.06]);
|
||||
assert.equal(decoder.closed, 1);
|
||||
assert.ok(AudioContextStub.sources.every(source => source.stopped === 1));
|
||||
assert.ok(chunks.every(chunk => chunk.closed === 1));
|
||||
receiveAudio(socket);
|
||||
const replacement = AudioDecoderStub.instances.at(-1);
|
||||
replacement.callbacks.output(decodedChunk());
|
||||
assert.notEqual(replacement, decoder);
|
||||
assert.equal(AudioContextStub.sources.at(-1).startedAt, 0);
|
||||
});
|
||||
|
||||
test("old socket audio cannot create a decoder in a replacement session", async () => {
|
||||
const old = await connect();
|
||||
const current = await connect();
|
||||
receiveAudio(old);
|
||||
assert.equal(AudioDecoderStub.instances.length, 0);
|
||||
receiveAudio(current);
|
||||
assert.equal(AudioDecoderStub.instances.length, 1);
|
||||
});
|
||||
|
||||
test("disconnect stops a microphone test and discards its late recording", async () => {
|
||||
await voice.startMicrophoneTest();
|
||||
const recorder = RecorderStub.instances.at(-1);
|
||||
voice.disconnect();
|
||||
assert.equal(recorder.stops, 1);
|
||||
assert.equal(voice.microphoneTestActive.value, false);
|
||||
recorder.finish();
|
||||
assert.equal(voice.testAudioUrl.value, "");
|
||||
});
|
||||
|
||||
test("a replacement microphone test stops the old recorder and ignores its late result", async t => {
|
||||
const created = [];
|
||||
t.mock.method(URL, "createObjectURL", blob => { created.push(blob); return `blob:test-${created.length}`; });
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
await voice.startMicrophoneTest();
|
||||
const old = RecorderStub.instances.at(-1);
|
||||
await voice.startMicrophoneTest();
|
||||
const current = RecorderStub.instances.at(-1);
|
||||
assert.equal(old.stops, 1);
|
||||
current.finish();
|
||||
const currentUrl = voice.testAudioUrl.value;
|
||||
old.finish();
|
||||
assert.equal(voice.testAudioUrl.value, currentUrl);
|
||||
assert.equal(created.length, 1);
|
||||
});
|
||||
|
||||
test("an old microphone test permission failure cannot stop a new recording", async () => {
|
||||
const oldPermission = deferred();
|
||||
let requests = 0;
|
||||
navigator.mediaDevices.getUserMedia = () => ++requests === 1 ? oldPermission.promise : Promise.resolve(microphoneStream());
|
||||
const old = voice.startMicrophoneTest().catch(() => {});
|
||||
voice.stopMicrophoneTest();
|
||||
await voice.startMicrophoneTest();
|
||||
oldPermission.reject(new Error("Old permission failed"));
|
||||
await old;
|
||||
assert.equal(voice.microphoneTestActive.value, true);
|
||||
assert.equal(RecorderStub.instances.at(-1).state, "recording");
|
||||
});
|
||||
|
||||
test("stopping a microphone test while devices refresh prevents recorder creation", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1 });
|
||||
await nextTurn();
|
||||
const refresh = deferred();
|
||||
navigator.mediaDevices.enumerateDevices = () => refresh.promise;
|
||||
const pending = voice.startMicrophoneTest();
|
||||
voice.stopMicrophoneTest();
|
||||
refresh.resolve([]);
|
||||
await pending;
|
||||
assert.equal(RecorderStub.instances.length, 0);
|
||||
assert.equal(voice.microphoneTestActive.value, false);
|
||||
});
|
||||
|
||||
test("a naturally finished microphone recording clears active state and standalone capture", async t => {
|
||||
const revoked = [];
|
||||
t.mock.method(URL, "createObjectURL", () => "blob:finished");
|
||||
t.mock.method(URL, "revokeObjectURL", url => revoked.push(url));
|
||||
await voice.startMicrophoneTest();
|
||||
const recorder = RecorderStub.instances.at(-1);
|
||||
recorder.finish();
|
||||
assert.equal(voice.microphoneTestActive.value, false);
|
||||
assert.equal(recorder.stream.track.readyState, "ended");
|
||||
assert.equal(voice.testAudioUrl.value, "blob:finished");
|
||||
voice.disconnect();
|
||||
assert.deepEqual(revoked, ["blob:finished"]);
|
||||
assert.equal(voice.testAudioUrl.value, "");
|
||||
});
|
||||
|
||||
test("recorder startup failure releases standalone microphone capture", async () => {
|
||||
RecorderStub.failStart = true;
|
||||
await assert.rejects(voice.startMicrophoneTest(), /Recorder start failed/);
|
||||
assert.equal(voice.microphoneTestActive.value, false);
|
||||
assert.equal(RecorderStub.instances.at(-1).stream.track.readyState, "ended");
|
||||
});
|
||||
|
||||
test("stopping a connected microphone test publishes its recording without stopping room capture", async t => {
|
||||
t.mock.method(URL, "createObjectURL", () => "blob:connected");
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1 });
|
||||
await nextTurn();
|
||||
await voice.startMicrophoneTest();
|
||||
const recorder = RecorderStub.instances.at(-1);
|
||||
voice.stopMicrophoneTest();
|
||||
recorder.finish();
|
||||
assert.equal(voice.testAudioUrl.value, "blob:connected");
|
||||
assert.equal(recorder.stream.track.readyState, "live");
|
||||
assert.equal(voice.state.connected, true);
|
||||
});
|
||||
|
||||
test("the microphone test deadline stops recording and is removed on completion", async t => {
|
||||
let deadline;
|
||||
const cleared = [];
|
||||
t.mock.method(window, "setTimeout", (callback, delay) => { assert.equal(delay, 5_000); deadline = callback; return 123; });
|
||||
t.mock.method(window, "clearTimeout", timer => cleared.push(timer));
|
||||
await voice.startMicrophoneTest();
|
||||
const recorder = RecorderStub.instances.at(-1);
|
||||
deadline();
|
||||
assert.equal(recorder.stops, 1);
|
||||
assert.equal(voice.microphoneTestActive.value, false);
|
||||
assert.deepEqual(cleared, [123]);
|
||||
});
|
||||
|
||||
test("an asynchronous recorder failure stops capture and reports a microphone error", async () => {
|
||||
await voice.startMicrophoneTest();
|
||||
const recorder = RecorderStub.instances.at(-1);
|
||||
recorder.onerror({ error: new Error("Recorder failed") });
|
||||
assert.equal(recorder.stops, 1);
|
||||
assert.equal(recorder.stream.track.readyState, "ended");
|
||||
assert.equal(voice.microphoneTestActive.value, false);
|
||||
assert.notEqual(voice.state.microphoneErrorCode, "");
|
||||
recorder.finish();
|
||||
assert.equal(voice.testAudioUrl.value, "");
|
||||
});
|
||||
Reference in new issue
Block a user