mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat: experiment with native lock-screen voice calls
This commit is contained in:
1 parent
ae6788a796
commit
34cee80302
18 files changed
+594
-34
No files matched your search
@@ -47,15 +47,16 @@
|
||||
:value="inputVolume * 100"
|
||||
:style="rangeStyle(inputVolume, 1)"
|
||||
:aria-label="t('inputVolume')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onInputVolume"
|
||||
/>
|
||||
<div class="dock-panel-divider"></div>
|
||||
<label class="dock-switch-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong></span>
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -131,12 +132,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
const props = defineProps<{
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive" | "backgroundCallActive">;
|
||||
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
|
||||
t: (key: string) => string;
|
||||
rangeStyle: (value: number, max: number) => Record<string, string>;
|
||||
}>();
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive } = props.model;
|
||||
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
|
||||
const emit = defineEmits<{ settings: []; outputMute: [] }>();
|
||||
</script>
|
||||
@@ -25,6 +25,15 @@
|
||||
:size="19" /></button></header
|
||||
><div class="settings-content">
|
||||
<div class="settings-audio-card">
|
||||
<section class="settings-section">
|
||||
<label class="settings-form-row background-call-setting">
|
||||
<span><strong>{{ t("backgroundCallTitle") }}</strong><small>{{ t("backgroundCallHint") }}</small></span>
|
||||
<input type="checkbox" :checked="backgroundCallEnabled" @change="onBackgroundCallChange" />
|
||||
</label>
|
||||
<p v-if="backgroundCallActive" class="settings-hint background-call-note">{{ t("backgroundCallProcessingHint") }}</p>
|
||||
<p v-if="backgroundCallActive && backgroundCallInterrupted" class="settings-error background-call-note">{{ t("backgroundCallInterrupted") }}</p>
|
||||
<p v-else-if="!backgroundCallActive && backgroundCallEnabled" class="settings-hint background-call-note">{{ t("backgroundCallPending") }}</p>
|
||||
</section>
|
||||
<section class="settings-section"
|
||||
><h3
|
||||
><Icon
|
||||
@@ -78,10 +87,10 @@
|
||||
></div
|
||||
><label class="settings-form-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label
|
||||
><div class="settings-form-row settings-range-form-row"
|
||||
@@ -97,6 +106,7 @@
|
||||
:value="inputVolume * 100"
|
||||
:style="rangeStyle(inputVolume, 1)"
|
||||
:aria-label="t('inputVolume')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onInputVolume"
|
||||
/></div
|
||||
></div
|
||||
@@ -113,12 +123,13 @@
|
||||
:value="voxThreshold * 1000"
|
||||
:style="rangeStyle(voxThreshold, 0.08)"
|
||||
:aria-label="t('voxThreshold')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onVoxThreshold"
|
||||
/></div
|
||||
></div
|
||||
><div class="audio-level-row"
|
||||
><span>{{ t("micLevel") }}</span
|
||||
><strong>{{ Math.round(micLevel * 100) }}%</strong></div
|
||||
><strong>{{ backgroundCallActive ? t('backgroundCallNative') : `${Math.round(micLevel * 100)}%` }}</strong></div
|
||||
><div class="audio-level-track"
|
||||
><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div
|
||||
><div class="mic-test"
|
||||
@@ -214,7 +225,9 @@
|
||||
><div class="audio-diagnostic"
|
||||
><span>{{ t("audioStatus") }}</span
|
||||
><strong>{{
|
||||
audioContextState === "running"
|
||||
backgroundCallActive && backgroundCallInterrupted
|
||||
? t("audioSuspended")
|
||||
: backgroundCallActive || audioContextState === "running"
|
||||
? microphoneError
|
||||
? t("audioUnavailable")
|
||||
: t("audioReady")
|
||||
@@ -255,6 +268,10 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
|
||||
| "backgroundCallEnabled"
|
||||
| "backgroundCallActive"
|
||||
| "backgroundCallInterrupted"
|
||||
| "setBackgroundCallEnabled"
|
||||
| "inputDevices"
|
||||
| "outputDevices"
|
||||
| "selectedInputDeviceId"
|
||||
@@ -300,6 +317,10 @@ const { onDialogKeydown } = useDialogFocus(dialog, () => emit("close"));
|
||||
|
||||
// The page owns the stable voice refs and audio controller; this dialog only presents them.
|
||||
const {
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
inputDevices,
|
||||
outputDevices,
|
||||
selectedInputDeviceId,
|
||||
@@ -332,6 +353,10 @@ const {
|
||||
toggleMicrophone,
|
||||
} = props.controls;
|
||||
|
||||
function onBackgroundCallChange(event: Event): void {
|
||||
setBackgroundCallEnabled((event.target as HTMLInputElement).checked);
|
||||
}
|
||||
|
||||
const inputDeviceOptions = computed(() => [
|
||||
{ value: "", label: props.t("defaultMicrophone") },
|
||||
...inputDevices.map((device, index) => ({
|
||||
@@ -347,3 +372,12 @@ const outputDeviceOptions = computed(() => [
|
||||
})),
|
||||
]);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.background-call-setting { display: flex; align-items: flex-start; gap: 16px; }
|
||||
.background-call-setting span { flex: 1; min-width: 0; }
|
||||
.background-call-setting strong, .background-call-setting small { display: block; }
|
||||
.background-call-setting small { margin-top: 6px; font-size: 12px; line-height: 1.65; color: var(--text-muted); }
|
||||
.background-call-setting input { flex: none; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); }
|
||||
.background-call-note { font-size: 12px; line-height: 1.65; }
|
||||
</style>
|
||||
@@ -5,6 +5,8 @@ export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.j
|
||||
import { createAudioSinkRouter } from "../voice/audio-sink.js";
|
||||
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
|
||||
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
import { createNativeMicrophoneCapture } from "../voice/native-microphone.js";
|
||||
import { createCallMediaSession } from "../services/call-media-session.js";
|
||||
import { createVoiceConnection } from "../voice/connection.js";
|
||||
import { createVoiceCommands } from "../voice/commands.js";
|
||||
import { createVoiceSessionState } from "../voice/session-state.js";
|
||||
@@ -21,7 +23,7 @@ import type { ChatMessage } from "../../../src/shared/voice-models.js";
|
||||
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
|
||||
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
|
||||
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
|
||||
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
|
||||
import { computed, onScopeDispose, reactive, ref, shallowRef, watch } from "vue";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
|
||||
export interface VoiceState {
|
||||
@@ -257,6 +259,11 @@ export function useVoiceWebSocket() {
|
||||
let micStream: MediaStream | null = null;
|
||||
const microphoneCaptureFactory = createMicrophoneCaptureFactory();
|
||||
let microphoneCapture: MicrophoneCapture | null = null;
|
||||
let microphoneNative = false;
|
||||
const backgroundCallEnabled = ref(false);
|
||||
const backgroundCallActive = ref(false);
|
||||
const backgroundCallInterrupted = ref(false);
|
||||
let backgroundCallTouched = false;
|
||||
let pendingMicrophoneCapture: AbortController | null = null;
|
||||
const accompanimentActive = ref(false);
|
||||
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
|
||||
@@ -345,7 +352,7 @@ export function useVoiceWebSocket() {
|
||||
stunServer: () => webRtcStunServer,
|
||||
prepareMicrophone: async () => {
|
||||
await ensureMicrophone();
|
||||
return micStream ? { context: getAudioCtx(), stream: micStream,
|
||||
return micStream ? { context: microphoneNative ? null : getAudioCtx(), stream: micStream,
|
||||
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
|
||||
},
|
||||
stopPcm: stopCaptureGraph,
|
||||
@@ -366,6 +373,7 @@ export function useVoiceWebSocket() {
|
||||
async onFallback(reason, isCurrent) {
|
||||
if (!isCurrent()) return;
|
||||
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
|
||||
backgroundCallActive.value = false;
|
||||
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
|
||||
try { await startMicrophone(); }
|
||||
catch (error) { if (isCurrent()) setMicrophoneError(error); }
|
||||
@@ -387,6 +395,38 @@ export function useVoiceWebSocket() {
|
||||
onPlaying: syncAudioContextNotice,
|
||||
},
|
||||
});
|
||||
const callMediaSession = createCallMediaSession({
|
||||
resume() {
|
||||
// A media Play command resumes listening only. Unmuting needs an explicit
|
||||
// microphone action, never a page visibility or system playback event.
|
||||
outputMuted.value = false;
|
||||
applyOutputVolume();
|
||||
webrtc.resumePlayback();
|
||||
},
|
||||
pause() {
|
||||
setMicrophoneMuted(true);
|
||||
outputMuted.value = true;
|
||||
applyOutputVolume();
|
||||
},
|
||||
toggleMicrophone: () => setMicrophoneMuted(!microphoneMuted.value),
|
||||
hangup: () => disconnect(),
|
||||
});
|
||||
function syncCallMediaSession(): void {
|
||||
callMediaSession.sync({ active: state.connected && backgroundCallActive.value,
|
||||
muted: microphoneMuted.value, outputMuted: outputMuted.value, title: serverInfo.value?.name || "WebSpeak" });
|
||||
}
|
||||
watch([() => state.connected, backgroundCallActive, microphoneMuted, outputMuted, serverInfo], syncCallMediaSession);
|
||||
const resumeVisibleCall = () => {
|
||||
if (!state.connected || !backgroundCallActive.value || document.visibilityState !== "visible") return;
|
||||
webrtc.resumePlayback();
|
||||
};
|
||||
document.addEventListener("visibilitychange", resumeVisibleCall);
|
||||
window.addEventListener("pageshow", resumeVisibleCall);
|
||||
onScopeDispose(() => {
|
||||
callMediaSession.dispose();
|
||||
document.removeEventListener("visibilitychange", resumeVisibleCall);
|
||||
window.removeEventListener("pageshow", resumeVisibleCall);
|
||||
});
|
||||
const audioDiagnostics = createAudioDiagnostics({
|
||||
source() {
|
||||
const socket = ws.value;
|
||||
@@ -398,7 +438,7 @@ export function useVoiceWebSocket() {
|
||||
presentation({ peer }) {
|
||||
return {
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live" && !track.muted)),
|
||||
microphonePermission: audioPermission.value,
|
||||
playbackState: peer
|
||||
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
|
||||
@@ -414,6 +454,7 @@ export function useVoiceWebSocket() {
|
||||
preferredInputDeviceId: committedInputDeviceId,
|
||||
inputDeviceId: committedInputDeviceId,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
backgroundCallEnabled: backgroundCallEnabled.value,
|
||||
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
|
||||
noiseSuppressionLevel: committedNoiseSuppressionLevel,
|
||||
voxThreshold: voxThreshold.value,
|
||||
@@ -433,6 +474,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
|
||||
if (!backgroundCallTouched) backgroundCallEnabled.value = preferences.backgroundCallEnabled === true;
|
||||
if (!inputDeviceTouched) {
|
||||
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
@@ -549,7 +591,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
|
||||
function syncAudioContextNotice(): void {
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
if (!microphoneNative && audioCtx && audioCtx.state === "suspended") {
|
||||
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
|
||||
} else {
|
||||
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
|
||||
@@ -702,9 +744,10 @@ export function useVoiceWebSocket() {
|
||||
pendingMicrophoneCapture?.abort();
|
||||
const controller = new AbortController();
|
||||
pendingMicrophoneCapture = controller;
|
||||
const ctx = getAudioCtx();
|
||||
const native = backgroundCallActive.value;
|
||||
const ctx = native ? null : getAudioCtx();
|
||||
const assertCurrent = (): void => {
|
||||
if (generation !== microphoneGeneration || audioCtx !== ctx || controller.signal.aborted) throw new CancelledMediaOperation();
|
||||
if (generation !== microphoneGeneration || (ctx && audioCtx !== ctx) || controller.signal.aborted) throw new CancelledMediaOperation();
|
||||
};
|
||||
let nextStream: MediaStream | null = null;
|
||||
let nextCapture: MicrophoneCapture | null = null;
|
||||
@@ -712,24 +755,35 @@ export function useVoiceWebSocket() {
|
||||
try {
|
||||
nextStream = await requestMediaBeforeAudioResume(
|
||||
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }),
|
||||
() => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
() => ctx?.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
);
|
||||
assertCurrent();
|
||||
audioPermission.value = "granted";
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
if (native) {
|
||||
nextCapture = createNativeMicrophoneCapture(nextStream);
|
||||
factoryOwnsStream = true;
|
||||
} else {
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx!, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
}
|
||||
assertCurrent();
|
||||
// Commit only a complete graph. Permission and node failures leave the
|
||||
// previous stream, PCM route and WebRTC peer untouched.
|
||||
stopMicrophone(false);
|
||||
micStream = nextStream;
|
||||
microphoneCapture = nextCapture;
|
||||
microphoneNative = native;
|
||||
backgroundCallInterrupted.value = false;
|
||||
sessionTrace.record("microphone.route", { native });
|
||||
const microphoneTrack = nextStream.getAudioTracks()[0];
|
||||
if (microphoneTrack) {
|
||||
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
|
||||
const recordTrack = (stateName: string) => {
|
||||
sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
|
||||
if (micStream === nextStream && native) backgroundCallInterrupted.value = microphoneTrack.muted || microphoneTrack.readyState !== "live";
|
||||
};
|
||||
recordTrack(microphoneTrack.readyState);
|
||||
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
|
||||
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
|
||||
@@ -759,8 +813,8 @@ export function useVoiceWebSocket() {
|
||||
|
||||
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
|
||||
async function ensureMicrophone(): Promise<void> {
|
||||
if (microphoneStartPromise) return microphoneStartPromise;
|
||||
if (micStream) return;
|
||||
if (microphoneStartPromise) await microphoneStartPromise;
|
||||
if (micStream && microphoneNative === backgroundCallActive.value) return;
|
||||
if (!microphoneStartPromise) {
|
||||
const generation = microphoneGeneration + 1;
|
||||
const pending = startMicrophone().then(async () => {
|
||||
@@ -793,6 +847,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function startAccompaniment(): Promise<void> {
|
||||
if (backgroundCallActive.value) {
|
||||
accompanimentErrorCode.value = "backgroundMode";
|
||||
throw new DOMException("Accompaniment is unavailable in native call mode", "NotSupportedError");
|
||||
}
|
||||
await accompaniment.start();
|
||||
}
|
||||
|
||||
@@ -827,6 +885,8 @@ export function useVoiceWebSocket() {
|
||||
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
|
||||
microphoneCapture?.dispose();
|
||||
microphoneCapture = null;
|
||||
microphoneNative = false;
|
||||
backgroundCallInterrupted.value = false;
|
||||
webrtc.releaseInput();
|
||||
micStream = null;
|
||||
if (closeContext) {
|
||||
@@ -1067,6 +1127,8 @@ export function useVoiceWebSocket() {
|
||||
commands.clear(new Error("语音连接已关闭"));
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
webrtc.stop();
|
||||
backgroundCallActive.value = false;
|
||||
callMediaSession.dispose();
|
||||
remotePlayback.clearAll();
|
||||
stopMicrophone();
|
||||
clearSpeakingState();
|
||||
@@ -1106,6 +1168,9 @@ export function useVoiceWebSocket() {
|
||||
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
|
||||
screenShare.setIceServers(msg.screenShareIceServers);
|
||||
webRtcStunServer = msg.webRtcStunServer ?? "";
|
||||
backgroundCallActive.value = backgroundCallEnabled.value && msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined";
|
||||
sessionTrace.record("call.background", { requested: backgroundCallEnabled.value, native: backgroundCallActive.value });
|
||||
syncCallMediaSession();
|
||||
sessionState.connected(msg);
|
||||
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
|
||||
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
|
||||
@@ -1441,6 +1506,12 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
function setBackgroundCallEnabled(enabled: boolean): void {
|
||||
backgroundCallTouched = true;
|
||||
backgroundCallEnabled.value = enabled;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
|
||||
if (noiseSuppressionLevel.value === level) return;
|
||||
noiseSuppressionTouched = true;
|
||||
@@ -1479,7 +1550,7 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => sessionTrace.dispose());
|
||||
onScopeDispose(() => { disconnect(); sessionTrace.dispose(); });
|
||||
|
||||
return {
|
||||
pluginSession,
|
||||
@@ -1495,6 +1566,10 @@ export function useVoiceWebSocket() {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
noiseSuppressionEnabled,
|
||||
noiseSuppressionLevel,
|
||||
inputVolume,
|
||||
|
||||
@@ -166,7 +166,9 @@ export function useWebClientAudioControls({
|
||||
await startAccompaniment();
|
||||
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
|
||||
} catch {
|
||||
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
|
||||
const messageKey = accompanimentErrorCode.value === "backgroundMode"
|
||||
? "backgroundCallProcessingHint"
|
||||
: accompanimentErrorCode.value === "needsWebRtc"
|
||||
? "accompanimentNeedsWebRtc"
|
||||
: accompanimentErrorCode.value === "noAudio"
|
||||
? "accompanimentNoAudio"
|
||||
|
||||
@@ -347,6 +347,12 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
exportAudioTrace: "导出最近两分钟的音频诊断",
|
||||
audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。",
|
||||
backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。",
|
||||
backgroundCallTitle: "锁屏通话(实验性)",
|
||||
backgroundCallHint: "默认关闭,下次连接生效。尝试使用系统原生语音链路;锁屏或后台通话仍受浏览器与系统限制。",
|
||||
backgroundCallProcessingHint: "本次通话使用系统麦克风处理并持续开麦(可手动静音)。强降噪、输入增益、音量计、语音阈值和伴奏不可用;关闭此选项后重新连接可恢复。",
|
||||
backgroundCallPending: "等待下次连接启用;需要网关与浏览器支持 WebRTC,不可用时仍使用兼容传输。",
|
||||
backgroundCallNative: "系统原生语音",
|
||||
backgroundCallInterrupted: "系统已暂停或结束麦克风采集。返回页面后检查权限,必要时重新连接;不会自动取消静音。",
|
||||
rnnoise: "RNNoise 降噪",
|
||||
echoCancellation: "回声消除",
|
||||
autoGainControl: "自动增益",
|
||||
@@ -779,6 +785,12 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
exportAudioTrace: "Export the last two minutes of audio diagnostics",
|
||||
audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.",
|
||||
backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.",
|
||||
backgroundCallTitle: "Lock-screen calls (experimental)",
|
||||
backgroundCallHint: "Off by default; applies on the next connection. Tries the native audio path. Browser and OS background restrictions still apply.",
|
||||
backgroundCallProcessingHint: "This call uses system microphone processing with continuous transmission unless muted. Strong denoising, input gain, level meters, voice threshold and accompaniment are unavailable. Disable this option and reconnect to restore them.",
|
||||
backgroundCallPending: "Waiting for the next connection. Requires browser and gateway WebRTC support; otherwise compatibility transport is used.",
|
||||
backgroundCallNative: "Native system audio",
|
||||
backgroundCallInterrupted: "The system paused or ended microphone capture. Return to the page, check permission and reconnect if needed. Your microphone will not be unmuted automatically.",
|
||||
rnnoise: "RNNoise suppression",
|
||||
echoCancellation: "Echo cancellation",
|
||||
autoGainControl: "Automatic gain control",
|
||||
@@ -1204,6 +1216,12 @@ webClientTranslations.de = {
|
||||
exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren",
|
||||
audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.",
|
||||
backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.",
|
||||
backgroundCallTitle: "Telefonieren bei gesperrtem Bildschirm (experimentell)",
|
||||
backgroundCallHint: "Standardmäßig aus; gilt ab der nächsten Verbindung. Verwendet nach Möglichkeit den nativen Audiopfad. Browser- und Systembeschränkungen gelten weiterhin.",
|
||||
backgroundCallProcessingHint: "Dieser Anruf nutzt die Mikrofonverarbeitung des Systems und sendet dauerhaft, sofern nicht stummgeschaltet. Starke Rauschunterdrückung, Eingangsverstärkung, Pegelanzeige, Sprachschwelle und Begleitung sind nicht verfügbar. Zum Wiederherstellen deaktivieren und neu verbinden.",
|
||||
backgroundCallPending: "Wartet auf die nächste Verbindung. Erfordert WebRTC im Browser und Gateway; andernfalls wird der Kompatibilitätsmodus verwendet.",
|
||||
backgroundCallNative: "Natives Systemaudio",
|
||||
backgroundCallInterrupted: "Das System hat die Mikrofonaufnahme unterbrochen oder beendet. Zur Seite zurückkehren, Berechtigung prüfen und bei Bedarf neu verbinden. Das Mikrofon wird nicht automatisch eingeschaltet.",
|
||||
rnnoise: "RNNoise-Geräuschunterdrückung",
|
||||
echoCancellation: "Echounterdrückung",
|
||||
autoGainControl: "Automatische Verstärkungsregelung",
|
||||
@@ -1379,6 +1397,12 @@ webClientTranslations.ru = {
|
||||
exportAudioTrace: "Экспортировать диагностику звука за последние две минуты",
|
||||
audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.",
|
||||
backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.",
|
||||
backgroundCallTitle: "Звонки при блокировке экрана (эксперимент)",
|
||||
backgroundCallHint: "По умолчанию выключено; применяется при следующем подключении. Использует системный аудиотракт, когда возможно. Ограничения браузера и ОС сохраняются.",
|
||||
backgroundCallProcessingHint: "Используется системная обработка микрофона с непрерывной передачей, пока микрофон не выключен. Сильное шумоподавление, усиление входа, индикаторы уровня, порог голоса и аккомпанемент недоступны. Для восстановления выключите опцию и подключитесь заново.",
|
||||
backgroundCallPending: "Ожидание следующего подключения. Нужна поддержка WebRTC браузером и шлюзом; иначе используется совместимый режим.",
|
||||
backgroundCallNative: "Системный аудиотракт",
|
||||
backgroundCallInterrupted: "Система приостановила или завершила запись. Вернитесь на страницу, проверьте разрешение и при необходимости подключитесь заново. Микрофон не включается автоматически.",
|
||||
highQuality: "Качественный звук",
|
||||
opusAudio: "Передача Opus с низкой задержкой",
|
||||
secureJoin: "Безопасное подключение",
|
||||
@@ -1598,6 +1622,12 @@ webClientTranslations.ja = {
|
||||
exportAudioTrace: "直近 2 分間の音声診断をエクスポート",
|
||||
audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。",
|
||||
backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。",
|
||||
backgroundCallTitle: "ロック画面で通話(試験機能)",
|
||||
backgroundCallHint: "初期設定はオフ。次回接続時に適用されます。システムの音声経路を試しますが、ブラウザーと OS のバックグラウンド制限は適用されます。",
|
||||
backgroundCallProcessingHint: "システムのマイク処理を使い、ミュートするまで連続送信します。強いノイズ抑制、入力ゲイン、レベル表示、音声しきい値、伴奏は使えません。元に戻すにはオフにして再接続してください。",
|
||||
backgroundCallPending: "次回接続を待っています。ブラウザーとゲートウェイの WebRTC 対応が必要です。非対応の場合は互換モードになります。",
|
||||
backgroundCallNative: "システム音声",
|
||||
backgroundCallInterrupted: "システムがマイク収録を一時停止または終了しました。ページに戻り権限を確認し、必要なら再接続してください。ミュートは自動解除されません。",
|
||||
highQuality: "高品質な音声",
|
||||
opusAudio: "低遅延 Opus 転送",
|
||||
secureJoin: "安全に参加",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { createCallMediaSession } from "./call-media-session.js";
|
||||
|
||||
function fixture(t: TestContext, unsupported = false) {
|
||||
const original = Object.getOwnPropertyDescriptor(globalThis, "MediaMetadata");
|
||||
Object.defineProperty(globalThis, "MediaMetadata", { configurable: true, value: class {
|
||||
title: string;
|
||||
constructor(init: { title: string }) { this.title = init.title; }
|
||||
} });
|
||||
t.after(() => {
|
||||
if (original) Object.defineProperty(globalThis, "MediaMetadata", original);
|
||||
else Reflect.deleteProperty(globalThis, "MediaMetadata");
|
||||
});
|
||||
const handlers = new Map<string, (() => void) | null>();
|
||||
const events: string[] = [];
|
||||
const session = {
|
||||
metadata: null as MediaMetadata | null, playbackState: "none" as MediaSessionPlaybackState,
|
||||
setActionHandler(action: string, callback: (() => void) | null) {
|
||||
if (unsupported && action === "togglemicrophone") throw new Error("Not supported");
|
||||
handlers.set(action, callback);
|
||||
},
|
||||
setMicrophoneActive(active: boolean) { events.push(`mic:${active}`); },
|
||||
};
|
||||
const audioSession = { type: "auto" };
|
||||
const controller = createCallMediaSession({ resume: () => events.push("play"), pause: () => events.push("pause"),
|
||||
toggleMicrophone: () => events.push("toggle"), hangup: () => events.push("hangup") }, { mediaSession: session as unknown as MediaSession, audioSession });
|
||||
t.after(() => controller.dispose());
|
||||
const sync = (active = true, muted = false) => controller.sync({ active, muted, outputMuted: false, title: "Test room" });
|
||||
return { controller, handlers, events, session, audioSession, sync };
|
||||
}
|
||||
|
||||
test("call media controls are opt-in, reflect mute, and restore OS state on release", t => {
|
||||
const f = fixture(t);
|
||||
f.sync(false);
|
||||
assert.equal(f.handlers.size, 0);
|
||||
f.sync();
|
||||
assert.equal(f.audioSession.type, "play-and-record");
|
||||
assert.equal(f.session.metadata?.title, "Test room");
|
||||
f.handlers.get("play")!();
|
||||
f.handlers.get("pause")!();
|
||||
f.handlers.get("togglemicrophone")!();
|
||||
f.sync(true, true);
|
||||
assert.ok(f.events.includes("mic:false"));
|
||||
f.sync(false);
|
||||
assert.equal(f.audioSession.type, "auto");
|
||||
assert.equal(f.session.metadata, null);
|
||||
assert.equal(f.session.playbackState, "none");
|
||||
assert.ok([...f.handlers.values()].every(value => value === null));
|
||||
});
|
||||
|
||||
test("a queued OS action cannot affect a disconnected or replacement call", t => {
|
||||
const f = fixture(t);
|
||||
f.sync();
|
||||
const stale = f.handlers.get("togglemicrophone")!;
|
||||
f.sync(false);
|
||||
f.sync();
|
||||
stale();
|
||||
assert.ok(!f.events.includes("toggle"));
|
||||
f.handlers.get("togglemicrophone")!();
|
||||
assert.equal(f.events.filter(e => e === "toggle").length, 1);
|
||||
});
|
||||
|
||||
test("partial API support leaves the other call controls functional", t => {
|
||||
const f = fixture(t, true);
|
||||
assert.doesNotThrow(() => f.sync());
|
||||
f.handlers.get("hangup")!();
|
||||
assert.ok(f.events.includes("hangup"));
|
||||
assert.equal(f.handlers.has("togglemicrophone"), false);
|
||||
assert.doesNotThrow(() => f.controller.dispose());
|
||||
});
|
||||
|
||||
test("missing system APIs never prevent calling", () => {
|
||||
const controller = createCallMediaSession({ resume() {}, pause() {}, toggleMicrophone() {}, hangup() {} }, {});
|
||||
assert.doesNotThrow(() => controller.sync({ active: true, muted: false, outputMuted: false, title: "Room" }));
|
||||
assert.doesNotThrow(() => controller.dispose());
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
interface CallSnapshot { active: boolean; muted: boolean; outputMuted: boolean; title: string }
|
||||
interface AudioSession { type: string }
|
||||
type CallAction = MediaSessionAction | "hangup" | "togglemicrophone";
|
||||
type CallNavigator = Pick<Navigator, "mediaSession"> & { audioSession?: AudioSession };
|
||||
interface CallActions {
|
||||
resume(): void;
|
||||
pause(): void;
|
||||
toggleMicrophone(): void;
|
||||
hangup(): void;
|
||||
}
|
||||
|
||||
/** Optional OS integration, never a keepalive or permission to restart capture. */
|
||||
export function createCallMediaSession(actions: CallActions, target: Partial<CallNavigator> = navigator) {
|
||||
let active = false;
|
||||
let generation = 0;
|
||||
let metadata: MediaMetadata | null = null;
|
||||
let oldMetadata: MediaMetadata | null = null;
|
||||
let oldPlayback: MediaSessionPlaybackState = "none";
|
||||
let oldAudioType: string | undefined;
|
||||
const installed: CallAction[] = [];
|
||||
const safely = (operation: () => void) => { try { operation(); } catch { /* platform may only implement part of the API */ } };
|
||||
|
||||
function stop(): void {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
generation++;
|
||||
const session = target.mediaSession;
|
||||
safely(() => (session as (MediaSession & { setMicrophoneActive?: (active: boolean) => void }) | undefined)?.setMicrophoneActive?.(false));
|
||||
for (const action of installed.splice(0)) safely(() => session?.setActionHandler(action as MediaSessionAction, null));
|
||||
if (session && session.metadata === metadata) {
|
||||
safely(() => { session.metadata = oldMetadata; session.playbackState = oldPlayback; });
|
||||
}
|
||||
safely(() => {
|
||||
if (target.audioSession?.type === "play-and-record" && oldAudioType !== undefined) target.audioSession.type = oldAudioType;
|
||||
});
|
||||
metadata = null;
|
||||
}
|
||||
|
||||
return {
|
||||
sync(snapshot: CallSnapshot): void {
|
||||
if (!snapshot.active) { stop(); return; }
|
||||
const session = target.mediaSession;
|
||||
if (!active) {
|
||||
active = true;
|
||||
const currentGeneration = ++generation;
|
||||
oldMetadata = session?.metadata ?? null;
|
||||
oldPlayback = session?.playbackState ?? "none";
|
||||
safely(() => {
|
||||
oldAudioType = target.audioSession?.type;
|
||||
if (target.audioSession) target.audioSession.type = "play-and-record";
|
||||
});
|
||||
if (session) {
|
||||
const handlers: Partial<Record<CallAction, () => void>> = {
|
||||
play: actions.resume, pause: actions.pause,
|
||||
stop: actions.hangup, hangup: actions.hangup, togglemicrophone: actions.toggleMicrophone,
|
||||
};
|
||||
for (const [action, handler] of Object.entries(handlers)) safely(() => {
|
||||
session.setActionHandler(action as MediaSessionAction, () => { if (active && generation === currentGeneration) handler(); });
|
||||
installed.push(action as CallAction);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!session) return;
|
||||
safely(() => {
|
||||
if (!metadata || metadata.title !== snapshot.title) {
|
||||
metadata = new MediaMetadata({ title: snapshot.title, artist: "WebSpeak" });
|
||||
session.metadata = metadata;
|
||||
}
|
||||
session.playbackState = snapshot.outputMuted ? "paused" : "playing";
|
||||
});
|
||||
safely(() => (session as MediaSession & { setMicrophoneActive?: (active: boolean) => void }).setMicrophoneActive?.(!snapshot.muted));
|
||||
},
|
||||
dispose: stop,
|
||||
};
|
||||
}
|
||||
@@ -145,6 +145,7 @@ export interface LocalPreferences {
|
||||
theme?: "system" | "light" | "dark";
|
||||
skinId?: string;
|
||||
microphoneMuted?: boolean;
|
||||
backgroundCallEnabled?: boolean;
|
||||
noiseSuppressionEnabled?: boolean;
|
||||
noiseSuppressionLevel?: "off" | "standard" | "strong";
|
||||
voxThreshold?: number;
|
||||
|
||||
@@ -1048,6 +1048,10 @@ const {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
noiseSuppressionEnabled,
|
||||
noiseSuppressionLevel,
|
||||
inputVolume,
|
||||
@@ -1302,8 +1306,12 @@ function reconnectMobile(): void {
|
||||
reconnectNow();
|
||||
}
|
||||
const { toggleMicrophone, stopWhisperTalk } = audioControls;
|
||||
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive };
|
||||
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive };
|
||||
const audioSettingsState = {
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
inputDevices,
|
||||
outputDevices,
|
||||
selectedInputDeviceId,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio";
|
||||
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio" | "backgroundMode";
|
||||
|
||||
interface AccompanimentTarget {
|
||||
setAccompaniment(stream: MediaStream | null): void;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { MicrophoneCapture } from "./microphone-capture.js";
|
||||
|
||||
/** Native browser processing only: no RNNoise, PCM worklet, analyser or gain graph. */
|
||||
export function createNativeMicrophoneCapture(stream: MediaStream): MicrophoneCapture {
|
||||
const track = stream.getAudioTracks()[0];
|
||||
if (!track || track.readyState !== "live") throw new DOMException("No live microphone", "NotReadableError");
|
||||
const settings = track.getSettings();
|
||||
let disposed = false;
|
||||
return {
|
||||
processedStream: stream,
|
||||
processing: {
|
||||
echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null,
|
||||
noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null,
|
||||
autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null,
|
||||
rnnoise: false,
|
||||
},
|
||||
activate() {},
|
||||
setVolume() {},
|
||||
stopCapture() {},
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
for (const item of stream.getTracks()) {
|
||||
try { item.stop(); } catch { /* release the other tracks too */ }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,23 @@ export interface WebRtcInput {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** The capture owner releases this stream; no Web Audio graph or clone owns it. */
|
||||
export function createNativeWebRtcInput(stream: MediaStream, volume: number): WebRtcInput {
|
||||
const track = stream.getAudioTracks()[0];
|
||||
if (!track || track.readyState !== "live") throw new Error("No live native microphone track");
|
||||
let disposed = false;
|
||||
const setVolume = (value: number) => { if (!disposed) track.enabled = value > 0; };
|
||||
setVolume(volume);
|
||||
return {
|
||||
stream,
|
||||
setVolume,
|
||||
setAccompaniment(source) {
|
||||
if (source) throw new DOMException("Native call input does not mix accompaniment", "NotSupportedError");
|
||||
},
|
||||
dispose() { disposed = true; },
|
||||
};
|
||||
}
|
||||
|
||||
// Own only the mixing nodes and their output. Capture controllers own the input
|
||||
// streams. Keep the sender track alive when accompaniment starts/stops/changes.
|
||||
export function createWebRtcInput(context: AudioContext, microphone: MediaStream, volume: number): WebRtcInput {
|
||||
|
||||
@@ -58,7 +58,9 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
|
||||
const task = (async () => {
|
||||
const context = options.context();
|
||||
if (context?.state === "suspended") {
|
||||
try { await context.resume(); } catch { /* a real user gesture may still be required */ }
|
||||
// Capture may never resume while locked. Native remote playback must
|
||||
// not wait on that independent graph, including on a retry gesture.
|
||||
try { void context.resume().catch(() => undefined); } catch { /* retry on a user gesture */ }
|
||||
}
|
||||
if (!isCurrent(record)) return;
|
||||
try {
|
||||
@@ -108,6 +110,7 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
|
||||
|
||||
return {
|
||||
attach, stop,
|
||||
resume(): void { if (current) void play(current); },
|
||||
get output(): SinkAudioElement | null { return current?.output ?? null; },
|
||||
setVolume(value: number): void { if (current) current.output.volume = value; },
|
||||
};
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { isSessionDescription, type WebRtcClientMessage } from "../../../src/shared/webrtc.js";
|
||||
import { createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
|
||||
import { createNativeWebRtcInput, createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
|
||||
import { createMicrophoneMeter, type MicrophoneMeter } from "./microphone-meter.js";
|
||||
import { createWebRtcPlayback, type WebRtcPlaybackOptions } from "./webrtc-playback.js";
|
||||
import { addOpusFmtpParameters } from "../../../src/shared/opus-sdp.js";
|
||||
|
||||
interface Microphone {
|
||||
context: AudioContext;
|
||||
context: AudioContext | null;
|
||||
stream: MediaStream;
|
||||
processedStream: MediaStream;
|
||||
}
|
||||
@@ -134,7 +134,8 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
const peer = new RTCPeerConnection({ iceServers: stunServer ? [{ urls: stunServer }] : [] });
|
||||
record.peer = peer;
|
||||
track.enabled = !options.muted();
|
||||
const input = createWebRtcInput(context, processedStream, options.muted() ? 0 : options.inputVolume());
|
||||
const volume = options.muted() ? 0 : options.inputVolume();
|
||||
const input = context ? createWebRtcInput(context, processedStream, volume) : createNativeWebRtcInput(stream, volume);
|
||||
record.input = input;
|
||||
peer.addTrack(input.stream.getAudioTracks()[0]!, input.stream);
|
||||
peer.ontrack = event => {
|
||||
@@ -142,7 +143,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
try { playback.attach(event.streams[0] ?? new MediaStream([event.track])); }
|
||||
catch { void fail(record, "WEBRTC_PLAYBACK_FAILED"); }
|
||||
};
|
||||
record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
|
||||
if (context) record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
|
||||
peer.onconnectionstatechange = () => {
|
||||
options.onConnectionState?.(peer.connectionState);
|
||||
if (isCurrent(record) && peer.connectionState === "failed") void fail(record, "WEBRTC_CONNECTION_FAILED");
|
||||
@@ -196,5 +197,6 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
get active(): boolean { return current?.active ?? false; },
|
||||
get output() { return playback.output; },
|
||||
setOutputVolume: playback.setVolume,
|
||||
resumePlayback: playback.resume,
|
||||
};
|
||||
}
|
||||
@@ -156,6 +156,7 @@ let useWebClientChat;
|
||||
let useWebClientChannels;
|
||||
let webClientTranslations;
|
||||
let voice;
|
||||
let voiceScope;
|
||||
const savedGlobals = new Map();
|
||||
function replaceGlobal(name, value) {
|
||||
if (!savedGlobals.has(name)) savedGlobals.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
@@ -224,12 +225,14 @@ beforeEach(() => {
|
||||
getUserMedia: async () => microphoneStream(),
|
||||
enumerateDevices: async () => [],
|
||||
} });
|
||||
voice = useVoiceWebSocket();
|
||||
voiceScope = effectScope();
|
||||
voice = voiceScope.run(() => useVoiceWebSocket());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
voice?.stopMicrophoneTest();
|
||||
voice?.disconnect();
|
||||
voiceScope?.stop();
|
||||
for (const timer of browserTimers) clearTimeout(timer);
|
||||
browserTimers.clear();
|
||||
});
|
||||
@@ -733,6 +736,165 @@ async function connectWebRtc() {
|
||||
return { socket, peer: TestPeer.instances.at(-1) };
|
||||
}
|
||||
|
||||
test("experimental calls send the native mic without creating a Web Audio graph and preserve mute", async () => {
|
||||
const stream = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => stream;
|
||||
assert.equal(voice.backgroundCallEnabled.value, false);
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer, socket } = await connectWebRtc();
|
||||
assert.equal(voice.backgroundCallActive.value, true);
|
||||
assert.equal(peer.sender.track, stream.track);
|
||||
assert.equal(AudioContextStub.instances.length, 0);
|
||||
assert.equal(voice.microphoneProcessing.rnnoise, false);
|
||||
voice.setMicrophoneMuted(true);
|
||||
assert.equal(stream.track.enabled, false);
|
||||
assert.ok(socket.messages.some(m => m.type === "setMicrophoneMuted" && m.payload.muted));
|
||||
voice.setMicrophoneMuted(false);
|
||||
assert.equal(stream.track.enabled, true);
|
||||
await assert.rejects(voice.startAccompaniment(), /unavailable/);
|
||||
assert.equal(voice.accompanimentErrorCode.value, "backgroundMode");
|
||||
voice.disconnect();
|
||||
assert.equal(stream.track.readyState, "ended");
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
});
|
||||
|
||||
test("changing the experiment applies only to the next connection", async () => {
|
||||
await connectWebRtc();
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
const { peer } = await connectWebRtc();
|
||||
const track = peer.sender.track;
|
||||
voice.setBackgroundCallEnabled(false);
|
||||
assert.equal(voice.backgroundCallActive.value, true);
|
||||
assert.equal(track.readyState, "live");
|
||||
await connectWebRtc();
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
});
|
||||
|
||||
test("native input at zero gain stays silent and scope disposal releases the microphone", async () => {
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
voice.setInputVolume(0);
|
||||
const { peer } = await connectWebRtc();
|
||||
assert.equal(peer.sender.track.enabled, false);
|
||||
voice.setMicrophoneMuted(true);
|
||||
voice.setMicrophoneMuted(false);
|
||||
assert.equal(peer.sender.track.enabled, false, "unmute must preserve a zero input level");
|
||||
voiceScope.stop();
|
||||
assert.equal(peer.sender.track.readyState, "ended");
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
});
|
||||
|
||||
test("native system microphone interruption is reported without changing user mute", async () => {
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer } = await connectWebRtc();
|
||||
const track = peer.sender.track;
|
||||
track.muted = true;
|
||||
track.dispatchEvent(new Event("mute"));
|
||||
assert.equal(voice.backgroundCallInterrupted.value, true);
|
||||
voice.setMicrophoneMuted(true);
|
||||
track.muted = false;
|
||||
track.dispatchEvent(new Event("unmute"));
|
||||
assert.equal(voice.backgroundCallInterrupted.value, false);
|
||||
assert.equal(voice.microphoneMuted.value, true);
|
||||
assert.equal(track.enabled, false);
|
||||
});
|
||||
|
||||
test("an experimental connection replaces a processing preview still waiting on permission", async () => {
|
||||
const permission = deferred();
|
||||
const preview = microphoneStream();
|
||||
const native = microphoneStream();
|
||||
let requests = 0;
|
||||
navigator.mediaDevices.getUserMedia = () => ++requests === 1 ? permission.promise : Promise.resolve(native);
|
||||
const preparation = voice.prepareInputDevices();
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
permission.resolve(preview);
|
||||
await preparation.catch(() => {});
|
||||
await nextTurn();
|
||||
assert.equal(preview.track.readyState, "ended");
|
||||
assert.equal(TestPeer.instances.at(-1).sender.track, native.track);
|
||||
assert.equal(voice.backgroundCallActive.value, true);
|
||||
});
|
||||
|
||||
test("native mode falls back to processed PCM after WebRTC failure", async () => {
|
||||
const streams = [];
|
||||
navigator.mediaDevices.getUserMedia = async () => { const stream = microphoneStream(); streams.push(stream); return stream; };
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer } = await connectWebRtc();
|
||||
peer.connectionState = "failed";
|
||||
peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
assert.equal(streams[0].track.readyState, "ended");
|
||||
assert.equal(streams.at(-1).track.readyState, "live");
|
||||
assert.ok(AudioContextStub.processors.length > 0);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
});
|
||||
|
||||
test("a gateway without WebRTC keeps compatibility capture with the experiment enabled", async () => {
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1 });
|
||||
await nextTurn();
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
assert.ok(AudioContextStub.processors.length > 0);
|
||||
assert.equal(TestPeer.instances.length, 0);
|
||||
});
|
||||
|
||||
test("disconnect retires a pending native microphone permission request", async () => {
|
||||
const pending = deferred();
|
||||
navigator.mediaDevices.getUserMedia = () => pending.promise;
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
await nextTurn();
|
||||
voice.disconnect();
|
||||
const stream = microphoneStream();
|
||||
pending.resolve(stream);
|
||||
await nextTurn();
|
||||
assert.equal(stream.track.readyState, "ended");
|
||||
assert.equal(TestPeer.instances.length, 0);
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
});
|
||||
|
||||
test("native remote playback does not wait for a suspended capture context to resume", async () => {
|
||||
const { peer } = await connectWebRtc();
|
||||
const context = AudioContextStub.instances.at(-1);
|
||||
context.state = "suspended";
|
||||
context.resume = () => new Promise(() => {});
|
||||
let plays = 0;
|
||||
const output = new TestAudioElement();
|
||||
output.play = async () => { plays++; };
|
||||
document.createElement = () => output;
|
||||
peer.ontrack({ streams: [microphoneStream()] });
|
||||
await nextTurn();
|
||||
assert.equal(plays, 1);
|
||||
});
|
||||
|
||||
test("OS playback resume and page restoration never unmute a native call", async () => {
|
||||
const handlers = new Map();
|
||||
navigator.mediaSession = { metadata: null, playbackState: "none", setActionHandler: (action, handler) => handlers.set(action, handler) };
|
||||
navigator.audioSession = { type: "auto" };
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer } = await connectWebRtc();
|
||||
handlers.get("pause")();
|
||||
await nextTurn();
|
||||
assert.equal(peer.sender.track.enabled, false);
|
||||
handlers.get("play")();
|
||||
document.visibilityState = "visible";
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
await nextTurn();
|
||||
assert.equal(voice.microphoneMuted.value, true);
|
||||
assert.equal(peer.sender.track.enabled, false);
|
||||
handlers.get("togglemicrophone")();
|
||||
assert.equal(peer.sender.track.enabled, true);
|
||||
handlers.get("hangup")();
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(navigator.audioSession.type, "auto");
|
||||
});
|
||||
|
||||
function enableMicrophoneMeter(t) {
|
||||
const analysers = [];
|
||||
const intervals = [];
|
||||
|
||||
Reference in new issue
Block a user