fix: preserve live voice during accompaniment changes

This commit is contained in:
illusia committed 2026-10-01 14:09:32 +08:00
1 parent 878e94a93a
commit 1a46ab83a3
8 files changed
+633 -302

No files matched your search

+25 -166
View File
@@ -3,6 +3,8 @@ import { createMicrophoneTest } from "../voice/microphone-test.js";
import { createMicrophoneCaptureFactory, type MicrophoneCapture, type MicrophoneProcessingSettings } from "../voice/microphone-capture.js";
export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.js";
import { createAudioSinkRouter } from "../voice/audio-sink.js";
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
import { createWebRtcInput, type WebRtcInput } from "../voice/webrtc-input.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";
@@ -259,18 +261,22 @@ export function useVoiceWebSocket() {
let pendingMicrophoneCapture: AbortController | null = null;
const accompanimentActive = ref(false);
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">("");
let accompanimentStream: MediaStream | null = null;
let accompanimentGeneration = 0;
let accompanimentEndedCleanup: (() => void) | null = null;
const accompanimentErrorCode = ref<AccompanimentErrorCode>("");
let webrtcInput: WebRtcInput | null = null;
const accompaniment = createAccompaniment({
isSupported: () => accompanimentSupported.value,
getTarget: () => webrtcActive.value && webrtcPeer && micStream ? webrtcInput : null,
onActive(active) {
const changed = accompanimentActive.value !== active;
accompanimentActive.value = active;
if (changed && webrtcActive.value) sendCmd("setAccompanimentActive", { active });
},
onError: code => { accompanimentErrorCode.value = code; },
});
const screenShare = createScreenShareController({
isOpen: () => ws.value?.readyState === WebSocket.OPEN,
send: message => ws.value?.send(JSON.stringify(message)),
});
let webrtcMixDestination: MediaStreamAudioDestinationNode | null = null;
let webrtcMixMicSource: MediaStreamAudioSourceNode | null = null;
let webrtcMixMicGain: GainNode | null = null;
let webrtcMixAccompanimentSource: MediaStreamAudioSourceNode | null = null;
let webrtcMicMonitorSource: MediaStreamAudioSourceNode | null = null;
let webrtcMicMonitorAnalyser: AnalyserNode | null = null;
let webrtcMicMonitorGain: GainNode | null = null;
@@ -750,170 +756,21 @@ export function useVoiceWebSocket() {
}
function stopWebRtcMix(): void {
webrtcMixAccompanimentSource?.disconnect();
webrtcMixMicSource?.disconnect();
webrtcMixMicGain?.disconnect();
webrtcMixDestination?.disconnect();
webrtcMixDestination?.stream.getTracks().forEach(track => track.stop());
webrtcMixAccompanimentSource = null;
webrtcMixMicSource = null;
webrtcMixMicGain = null;
webrtcMixDestination = null;
const input = webrtcInput;
webrtcInput = null;
input?.dispose();
}
function releaseAccompanimentStream(): void {
accompanimentGeneration++;
accompanimentEndedCleanup?.();
accompanimentEndedCleanup = null;
accompanimentStream?.getTracks().forEach((track) => track.stop());
accompanimentStream = null;
accompanimentActive.value = false;
}
function createWebRtcMixStream(): MediaStream {
if (!micStream) throw new Error("没有可用的麦克风音轨");
const ctx = getAudioCtx();
stopWebRtcMix();
const destination = ctx.createMediaStreamDestination();
destination.channelCount = 1;
destination.channelCountMode = "explicit";
// Use the browser-native processed track plus the browser-side RNNoise
// graph. Display/application audio is added separately below and never
// passes through this microphone denoiser.
const microphoneStream = microphoneCapture?.processedStream ?? micStream;
const microphoneSource = ctx.createMediaStreamSource(microphoneStream);
const microphoneGain = ctx.createGain();
microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
microphoneSource.connect(microphoneGain);
microphoneGain.connect(destination);
webrtcMixDestination = destination;
webrtcMixMicSource = microphoneSource;
webrtcMixMicGain = microphoneGain;
const accompanimentTrack = accompanimentStream?.getAudioTracks()[0];
if (accompanimentTrack) {
const accompanimentSource = ctx.createMediaStreamSource(accompanimentStream!);
// Keep the captured application audio at its source level. Do not add
// a fixed attenuation/gain node: it makes music sound quieter than the
// source and encourages later "compensation" steps to pump its volume.
accompanimentSource.connect(destination);
webrtcMixAccompanimentSource = accompanimentSource;
}
return destination.stream;
}
async function replaceWebRtcAudioTrack(): Promise<void> {
if (!webrtcPeer || !micStream) return;
const sender = webrtcPeer.getSenders().find((candidate) => candidate.track?.kind === "audio");
if (!sender) throw new Error("WebRTC 音频轨道尚未就绪");
const mixedStream = createWebRtcMixStream();
const mixedTrack = mixedStream.getAudioTracks()[0];
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
await sender.replaceTrack(mixedTrack);
accompaniment.stop();
}
async function startAccompaniment(): Promise<void> {
accompanimentErrorCode.value = "";
if (!accompanimentSupported.value) {
accompanimentErrorCode.value = "unsupported";
throw new Error("伴奏共享不可用");
}
if (!webrtcActive.value || !webrtcPeer || !micStream) {
accompanimentErrorCode.value = "needsWebRtc";
throw new Error("伴奏功能需要启用 WebRTC");
}
const generation = ++accompanimentGeneration;
const peer = webrtcPeer;
const sequence = connectionSequence;
const isCurrent = (): boolean => generation === accompanimentGeneration
&& sequence === connectionSequence && webrtcPeer === peer && webrtcActive.value;
const captureProcessingConstraints: MediaTrackConstraints = {
// Display/application audio must not pass through browser voice
// processing. Those processors are designed for speech and can change
// music level from frame to frame (AGC), suppress quiet passages, or
// cancel sustained tones.
autoGainControl: false,
echoCancellation: false,
noiseSuppression: false,
};
const audioConstraints = { ...captureProcessingConstraints } as MediaTrackConstraints & { restrictOwnAudio?: boolean };
const supportedConstraints = navigator.mediaDevices.getSupportedConstraints?.() as Record<string, boolean> | undefined;
if (supportedConstraints?.restrictOwnAudio) audioConstraints.restrictOwnAudio = true;
const options = {
video: { displaySurface: "browser" },
audio: audioConstraints,
selfBrowserSurface: "exclude",
systemAudio: "include",
windowAudio: "window",
} as unknown as DisplayMediaStreamOptions;
let nextStream: MediaStream;
try {
nextStream = await navigator.mediaDevices.getDisplayMedia(options);
} catch (error) {
if (!isCurrent()) return;
if (error instanceof DOMException && error.name === "AbortError") return;
accompanimentErrorCode.value = "permission";
throw error;
}
if (!isCurrent()) {
nextStream.getTracks().forEach(track => track.stop());
return;
}
const audioTrack = nextStream.getAudioTracks()[0];
nextStream.getVideoTracks().forEach((track) => track.stop());
if (!audioTrack) {
nextStream.getTracks().forEach((track) => track.stop());
accompanimentErrorCode.value = "noAudio";
throw new Error("所选来源没有可共享音频");
}
try {
// Do not pass the Chromium-only restrictOwnAudio hint to
// applyConstraints: rejecting an unknown key could otherwise cause the
// browser to discard all three standard processing-off constraints.
await audioTrack.applyConstraints(captureProcessingConstraints);
} catch {
// Some browsers expose display audio but reject one or more optional
// processing constraints. The capture can still proceed without
// introducing a WebSpeak-side gain stage.
}
if (!isCurrent()) {
nextStream.getTracks().forEach(track => track.stop());
return;
}
if ("contentHint" in audioTrack) audioTrack.contentHint = "music";
accompanimentEndedCleanup?.();
accompanimentStream?.getTracks().forEach((track) => track.stop());
accompanimentStream = nextStream;
accompanimentActive.value = true;
sendCmd("setAccompanimentActive", { active: true });
const onEnded = (): void => {
if (accompanimentStream === nextStream) void stopAccompaniment().catch(() => undefined);
};
audioTrack.addEventListener("ended", onEnded, { once: true });
accompanimentEndedCleanup = () => audioTrack.removeEventListener("ended", onEnded);
try {
await replaceWebRtcAudioTrack();
} catch (error) {
if (!isCurrent() || accompanimentStream !== nextStream) return;
releaseAccompanimentStream();
sendCmd("setAccompanimentActive", { active: false });
stopWebRtcMix();
accompanimentErrorCode.value = "permission";
throw error;
}
await accompaniment.start();
}
async function stopAccompaniment(): Promise<void> {
accompanimentErrorCode.value = "";
releaseAccompanimentStream();
if (webrtcActive.value) sendCmd("setAccompanimentActive", { active: false });
if (webrtcActive.value && webrtcPeer && micStream) await replaceWebRtcAudioTrack();
else stopWebRtcMix();
accompaniment.stop();
}
async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise<void> {
@@ -941,7 +798,9 @@ export function useVoiceWebSocket() {
const isCurrentPeer = (): boolean => isCurrent() && webrtcPeer === peer;
try {
microphoneTrack.enabled = !microphoneMuted.value;
const mixedStream = createWebRtcMixStream();
webrtcInput = createWebRtcInput(getAudioCtx(), microphoneCapture?.processedStream ?? micStream,
microphoneMuted.value ? 0 : inputVolume.value);
const mixedStream = webrtcInput.stream;
const mixedTrack = mixedStream.getAudioTracks()[0];
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
peer.addTrack(mixedTrack, mixedStream);
@@ -1946,7 +1805,7 @@ export function useVoiceWebSocket() {
voxRelease = 0;
accumLen = 0;
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = muted ? 0 : inputVolume.value;
webrtcInput?.setVolume(muted ? 0 : inputVolume.value);
sendCmd("setMicrophoneMuted", { muted });
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
void saveAudioPreferences();
@@ -2021,7 +1880,7 @@ export function useVoiceWebSocket() {
function setInputVolume(volume: number): void {
inputVolume.value = Math.max(0, Math.min(1, volume));
microphoneCapture?.setVolume(inputVolume.value);
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
webrtcInput?.setVolume(microphoneMuted.value ? 0 : inputVolume.value);
void saveAudioPreferences();
}
@@ -150,7 +150,9 @@ export function useWebClientAudioControls({
? "accompanimentNoAudio"
: accompanimentErrorCode.value === "unsupported"
? "accompanimentUnsupported"
: "accompanimentPermissionDenied";
: accompanimentErrorCode.value === "audio"
? "accompanimentAudioFailed"
: "accompanimentPermissionDenied";
showToast(t(messageKey));
}
}
+5
View File
@@ -118,6 +118,7 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
accompanimentNeedsWebRtc: "伴奏功能需要启用 WebRTC",
accompanimentNoAudio: "所选来源没有可共享音频,请重新选择并勾选共享音频",
accompanimentPermissionDenied: "无法获取伴奏音频,请允许屏幕共享并勾选共享音频",
accompanimentAudioFailed: "无法接入伴奏音频,请重新选择音频来源或稍后重试",
accompanimentUnsupported: "当前浏览器不支持伴奏共享",
screenShare: "屏幕共享",
screenShareTitle: "屏幕共享",
@@ -504,6 +505,7 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
accompanimentNeedsWebRtc: "Accompaniment requires WebRTC",
accompanimentNoAudio: "The selected source has no shareable audio. Select it again and enable audio sharing",
accompanimentPermissionDenied: "Could not access accompaniment audio. Allow screen sharing and enable audio sharing",
accompanimentAudioFailed: "Could not add accompaniment audio. Select the audio source again or try later",
accompanimentUnsupported: "This browser does not support accompaniment sharing",
screenShare: "Screen sharing",
screenShareTitle: "Screen sharing",
@@ -893,6 +895,7 @@ webClientTranslations.de = {
accompanimentNeedsWebRtc: "Die Begleitungsfunktion benötigt WebRTC.",
accompanimentNoAudio: "Die ausgewählte Quelle enthält kein teilbares Audio. Wähle sie erneut und aktiviere die Audiofreigabe.",
accompanimentPermissionDenied: "Begleitungs-Audio konnte nicht abgerufen werden. Erlaube die Bildschirmfreigabe und aktiviere die Audiofreigabe.",
accompanimentAudioFailed: "Begleitungs-Audio konnte nicht hinzugefügt werden. Wähle die Audioquelle erneut oder versuche es später.",
accompanimentUnsupported: "Dieser Browser unterstützt das Teilen von Begleitung nicht.",
startScreenShare: "Bildschirm teilen",
screenShareStarting: "Live-Stream wird gestartet",
@@ -1156,6 +1159,7 @@ webClientTranslations.de = {
webClientTranslations.ru = {
...webClientTranslations.en,
accompanimentAudioFailed: "Не удалось подключить звук сопровождения. Выберите источник звука заново или повторите попытку позже.",
themeSystem: "Системная тема",
themeLight: "Светлая тема",
themeDark: "Тёмная тема",
@@ -1329,6 +1333,7 @@ webClientTranslations.ru = {
webClientTranslations.ja = {
...webClientTranslations.en,
accompanimentAudioFailed: "伴奏音声を追加できませんでした。音声ソースを選び直すか、後でもう一度お試しください。",
themeSystem: "システム設定",
themeLight: "ライトテーマ",
themeDark: "ダークテーマ",
+125
View File
@@ -0,0 +1,125 @@
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio";
interface AccompanimentTarget {
setAccompaniment(stream: MediaStream | null): void;
}
interface AccompanimentOptions {
isSupported(): boolean;
getTarget(): AccompanimentTarget | null;
onActive(active: boolean): void;
onError(code: AccompanimentErrorCode): void;
}
interface Capture {
stream: MediaStream;
target: AccompanimentTarget;
audio: MediaStreamTrack | null;
onEnded: () => void;
disposed: boolean;
}
// Own both prepared and active captures. A generation also invalidates browser
// permission requests which cannot be cancelled until their streams arrive.
export function createAccompaniment(options: AccompanimentOptions) {
let generation = 0;
let pending: Capture | null = null;
let current: Capture | null = null;
function stopTracks(stream: MediaStream): void {
for (const track of stream.getTracks()) {
try { if (track.readyState !== "ended") track.stop(); } catch { /* stop remaining tracks too */ }
}
}
function release(capture: Capture | null): void {
if (!capture || capture.disposed) return;
capture.disposed = true;
capture.audio?.removeEventListener("ended", capture.onEnded);
stopTracks(capture.stream);
}
function cancelPending(): void {
const capture = pending;
pending = null;
release(capture);
}
function stop(): void {
generation++;
cancelPending();
const previous = current;
current = null;
// Use the original target even if the caller has already invalidated its
// peer. Stopping capture cannot leave an attached source or active flag.
try { previous?.target.setAccompaniment(null); }
finally {
release(previous);
options.onActive(false);
options.onError("");
}
}
async function start(): Promise<void> {
const ownGeneration = ++generation;
cancelPending();
options.onError("");
if (!options.isSupported()) {
options.onError("unsupported");
throw new Error("Accompaniment sharing is unavailable");
}
const target = options.getTarget();
if (!target) {
options.onError("needsWebRtc");
throw new Error("Accompaniment requires WebRTC");
}
const isCurrent = (): boolean => generation === ownGeneration && options.getTarget() === target;
const processing: MediaTrackConstraints = { autoGainControl: false, echoCancellation: false, noiseSuppression: false };
const audio = { ...processing } as MediaTrackConstraints & { restrictOwnAudio?: boolean };
const supported = navigator.mediaDevices.getSupportedConstraints?.() as Record<string, boolean> | undefined;
if (supported?.restrictOwnAudio) audio.restrictOwnAudio = true;
let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: { displaySurface: "browser" }, audio,
selfBrowserSurface: "exclude", systemAudio: "include", windowAudio: "window",
} as unknown as DisplayMediaStreamOptions);
} catch (error) {
if (!isCurrent() || (error instanceof DOMException && error.name === "AbortError")) return;
options.onError("permission");
throw error;
}
if (!isCurrent()) { stopTracks(stream); return; }
const candidate: Capture = { stream, target, audio: null, onEnded: () => {}, disposed: false };
pending = candidate;
let errorCode: AccompanimentErrorCode = "audio";
try {
for (const track of stream.getVideoTracks()) track.stop();
const track = stream.getAudioTracks()[0];
if (!track) { errorCode = "noAudio"; throw new Error("The selected source has no audio"); }
candidate.audio = track;
candidate.onEnded = () => {
if (current === candidate) stop();
else if (pending === candidate) cancelPending();
};
track.addEventListener("ended", candidate.onEnded, { once: true });
// Optional display constraints vary by browser. Do not pass the
// Chromium-only restrictOwnAudio hint to applyConstraints.
try { await track.applyConstraints(processing); } catch { /* capture can still be used */ }
if (!isCurrent() || candidate.disposed || track.readyState !== "live") return;
try { if ("contentHint" in track) track.contentHint = "music"; } catch { /* optional hint */ }
target.setAccompaniment(stream);
const previous = current;
current = candidate;
pending = null;
release(previous);
options.onActive(true);
} catch (error) {
if (!isCurrent() || candidate.disposed) return;
options.onError(errorCode);
throw error;
} finally {
if (pending === candidate) pending = null;
if (current !== candidate) release(candidate);
}
}
return { start, stop };
}
+79
View File
@@ -0,0 +1,79 @@
export interface WebRtcInput {
readonly stream: MediaStream;
setAccompaniment(stream: MediaStream | null): void;
setVolume(value: number): void;
dispose(): void;
}
// 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 {
let destination: MediaStreamAudioDestinationNode | null = null;
let microphoneSource: MediaStreamAudioSourceNode | null = null;
let microphoneGain: GainNode | null = null;
let accompanimentSource: MediaStreamAudioSourceNode | null = null;
let disposed = false;
const clean = (operation: () => void): void => { try { operation(); } catch { /* release other resources too */ } };
function dispose(): void {
if (disposed) return;
disposed = true;
if (accompanimentSource) clean(() => accompanimentSource!.disconnect());
if (microphoneSource) clean(() => microphoneSource!.disconnect());
if (microphoneGain) clean(() => microphoneGain!.disconnect());
if (destination) {
clean(() => destination!.disconnect());
for (const track of destination.stream.getTracks()) clean(() => track.stop());
}
accompanimentSource = null;
microphoneSource = null;
microphoneGain = null;
destination = null;
}
try {
destination = context.createMediaStreamDestination();
destination.channelCount = 1;
destination.channelCountMode = "explicit";
if (!destination.stream.getAudioTracks().some(track => track.readyState === "live")) {
throw new Error("WebRTC input has no live output track");
}
microphoneSource = context.createMediaStreamSource(microphone);
microphoneGain = context.createGain();
microphoneGain.gain.value = volume;
microphoneSource.connect(microphoneGain);
microphoneGain.connect(destination);
return {
stream: destination.stream,
setAccompaniment(stream) {
if (disposed) {
if (stream) throw new DOMException("WebRTC input closed", "AbortError");
return;
}
let candidate: MediaStreamAudioSourceNode | null = null;
try {
if (stream) {
if (!stream.getAudioTracks().some(track => track.readyState === "live")) {
throw new Error("Accompaniment has no live audio track");
}
candidate = context.createMediaStreamSource(stream);
// Application audio retains its source level and bypasses microphone
// gain/denoising. Prepare it before disconnecting the previous source.
candidate.connect(destination!);
}
} catch (error) {
if (candidate) clean(() => candidate!.disconnect());
throw error;
}
const previous = accompanimentSource;
accompanimentSource = candidate;
if (previous) clean(() => previous.disconnect());
},
setVolume(value) { if (microphoneGain) microphoneGain.gain.value = value; },
dispose,
};
} catch (error) {
dispose();
throw error;
}
}