mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-04 20:43:02 +08:00
fix(voice): keep both mic-test takes playable
Record the original take from a pre-denoise AudioContext tap instead of the already-captured getUserMedia track, and wait for every MediaRecorder onstop before publishing URLs so a late dry dataavailable is not dropped. Show an explicit missing-take message when a tab has no playable URL, and flush recorders before releasing standalone capture.
This commit is contained in:
1 parent
47abe356f5
commit
5d3af8dfbb
8 files changed
+492
-44
No files matched your search
@@ -155,6 +155,11 @@
|
||||
controls
|
||||
:aria-label="t('microphoneTest')"
|
||||
></audio>
|
||||
<p
|
||||
v-else
|
||||
class="settings-hint mic-test-missing"
|
||||
role="status"
|
||||
>{{ t(testAudioMissingKey) }}</p>
|
||||
<p class="settings-hint">{{ t("micTestCompareHint") }}</p>
|
||||
</div></div
|
||||
></section>
|
||||
@@ -257,6 +262,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, type CSSProperties } from "vue";
|
||||
import { micTestPlaybackSource } from "../../voice/microphone-test.js";
|
||||
import Icon from "../Icon.vue";
|
||||
import AudioDeviceSelect from "./AudioDeviceSelect.vue";
|
||||
import { useDialogFocus } from "../../composables/useDialogFocus.js";
|
||||
@@ -361,9 +367,12 @@ const outputDeviceOptions = computed(() => [
|
||||
]);
|
||||
|
||||
const testVariant = ref<"processed" | "dry">("processed");
|
||||
const testAudioSrc = computed(() => testVariant.value === "dry"
|
||||
? testAudioDryUrl.value
|
||||
: (testAudioUrl.value || testAudioDryUrl.value));
|
||||
const testPlayback = computed(() => micTestPlaybackSource(testVariant.value, {
|
||||
processed: testAudioUrl.value,
|
||||
dry: testAudioDryUrl.value,
|
||||
}));
|
||||
const testAudioSrc = computed(() => testPlayback.value.src);
|
||||
const testAudioMissingKey = computed(() => testPlayback.value.missingKey);
|
||||
const processingFallback = computed(() => microphoneProcessing.fallback);
|
||||
const processingWarning = computed(() => microphoneProcessing.warning);
|
||||
// Reflect the engine that really ran, not the stored preference.
|
||||
|
||||
@@ -321,7 +321,10 @@ export function useVoiceWebSocket() {
|
||||
prepare: async () => {
|
||||
await prepareInputDevices();
|
||||
if (!micStream) return null;
|
||||
return { dry: micStream, processed: microphoneCapture?.processedStream ?? micStream };
|
||||
return {
|
||||
dry: microphoneCapture?.dryStream ?? micStream,
|
||||
processed: microphoneCapture?.processedStream ?? micStream,
|
||||
};
|
||||
},
|
||||
onActive: active => { microphoneTestActive.value = active; },
|
||||
onUrl: url => { testAudioUrl.value = url; },
|
||||
|
||||
@@ -364,6 +364,8 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
micTestOriginal: "原始",
|
||||
micTestDenoised: "降噪后",
|
||||
micTestCompareHint: "同一段录音分别播放原始与降噪后音频,便于对比。",
|
||||
micTestOriginalUnavailable: "原始录音没有可播放的音频。请重新测试麦克风。",
|
||||
micTestDenoisedUnavailable: "降噪后录音没有可播放的音频。请重新测试麦克风。",
|
||||
exportAudioTrace: "导出最近两分钟的音频诊断",
|
||||
audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。",
|
||||
backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。",
|
||||
@@ -816,6 +818,8 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
micTestOriginal: "Original",
|
||||
micTestDenoised: "Denoised",
|
||||
micTestCompareHint: "The same take plays raw and denoised so you can compare them.",
|
||||
micTestOriginalUnavailable: "The original take has no playable audio. Please run the microphone test again.",
|
||||
micTestDenoisedUnavailable: "The denoised take has no playable audio. Please run the microphone test again.",
|
||||
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.",
|
||||
@@ -1261,6 +1265,8 @@ webClientTranslations.de = {
|
||||
micTestOriginal: "Original",
|
||||
micTestDenoised: "Entrauscht",
|
||||
micTestCompareHint: "Dieselbe Aufnahme wird roh und entrauscht abgespielt, damit du vergleichen kannst.",
|
||||
micTestOriginalUnavailable: "Die Originalaufnahme enthält kein abspielbares Audio. Bitte den Mikrofontest erneut ausführen.",
|
||||
micTestDenoisedUnavailable: "Die entrauschte Aufnahme enthält kein abspielbares Audio. Bitte den Mikrofontest erneut ausführen.",
|
||||
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.",
|
||||
@@ -1454,6 +1460,8 @@ webClientTranslations.ru = {
|
||||
micTestOriginal: "Оригинал",
|
||||
micTestDenoised: "После обработки",
|
||||
micTestCompareHint: "Одна и та же запись воспроизводится в исходном и обработанном виде для сравнения.",
|
||||
micTestOriginalUnavailable: "Исходная запись не содержит воспроизводимого аудио. Повторите тест микрофона.",
|
||||
micTestDenoisedUnavailable: "Обработанная запись не содержит воспроизводимого аудио. Повторите тест микрофона.",
|
||||
exportAudioTrace: "Экспортировать диагностику звука за последние две минуты",
|
||||
audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.",
|
||||
backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.",
|
||||
@@ -1693,6 +1701,8 @@ webClientTranslations.ja = {
|
||||
micTestOriginal: "元の音声",
|
||||
micTestDenoised: "処理後",
|
||||
micTestCompareHint: "同じ録音を元の音声と処理後の音声で再生して比較できます。",
|
||||
micTestOriginalUnavailable: "元の録音を再生できる音声がありません。マイクテストをやり直してください。",
|
||||
micTestDenoisedUnavailable: "処理後の録音を再生できる音声がありません。マイクテストをやり直してください。",
|
||||
exportAudioTrace: "直近 2 分間の音声診断をエクスポート",
|
||||
audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。",
|
||||
backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。",
|
||||
|
||||
@@ -21,6 +21,8 @@ export interface MicrophoneProcessingSettings {
|
||||
|
||||
export interface MicrophoneCapture {
|
||||
processedStream: MediaStream;
|
||||
/** Pre-denoise tap of the same capture, safe to hand to MediaRecorder. */
|
||||
dryStream: MediaStream;
|
||||
processing: MicrophoneProcessingSettings;
|
||||
activate(): void;
|
||||
setVolume(value: number): void;
|
||||
@@ -103,6 +105,7 @@ export function createMicrophoneCaptureFactory() {
|
||||
let highpass: BiquadFilterNode | null = null;
|
||||
let denoiser: RnnoiseWorkletNode | GtcrnWorkletNode | null = null;
|
||||
let destination: MediaStreamAudioDestinationNode | null = null;
|
||||
let dryDestination: MediaStreamAudioDestinationNode | null = null;
|
||||
let gain: GainNode | null = null;
|
||||
let silent: GainNode | null = null;
|
||||
let worklet: AudioWorkletNode | null = null;
|
||||
@@ -131,6 +134,10 @@ export function createMicrophoneCaptureFactory() {
|
||||
if (denoiser) { clean(() => denoiser!.destroy()); clean(() => denoiser!.disconnect()); }
|
||||
if (highpass) clean(() => highpass!.disconnect());
|
||||
if (source) clean(() => source!.disconnect());
|
||||
if (dryDestination) {
|
||||
clean(() => dryDestination!.disconnect());
|
||||
for (const track of dryDestination.stream.getTracks()) clean(() => track.stop());
|
||||
}
|
||||
if (destination) {
|
||||
clean(() => destination!.disconnect());
|
||||
for (const track of destination.stream.getTracks()) clean(() => track.stop());
|
||||
@@ -176,6 +183,13 @@ export function createMicrophoneCaptureFactory() {
|
||||
highpass.connect(denoiser);
|
||||
processedSource = denoiser;
|
||||
}
|
||||
// A destination tap of the raw source, before the high-pass / model.
|
||||
// MediaRecorder cannot reliably record a getUserMedia track that is
|
||||
// already attached to an AudioContext as a MediaStreamSource.
|
||||
dryDestination = ctx.createMediaStreamDestination();
|
||||
dryDestination.channelCount = 1;
|
||||
dryDestination.channelCountMode = "explicit";
|
||||
source.connect(dryDestination);
|
||||
destination = ctx.createMediaStreamDestination();
|
||||
destination.channelCount = 1;
|
||||
destination.channelCountMode = "explicit";
|
||||
@@ -214,6 +228,7 @@ export function createMicrophoneCaptureFactory() {
|
||||
if (track.readyState !== "live") throw new DOMException("Microphone track ended", "NotReadableError");
|
||||
return {
|
||||
processedStream: destination.stream,
|
||||
dryStream: dryDestination.stream,
|
||||
processing: {
|
||||
echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null,
|
||||
noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null,
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { afterEach, test } from "node:test";
|
||||
import {
|
||||
MICROPHONE_TEST_DURATION_MS,
|
||||
createMicrophoneTest,
|
||||
micTestPlaybackSource,
|
||||
} from "./microphone-test.ts";
|
||||
import { webClientTranslations } from "../i18n/web-client.ts";
|
||||
|
||||
class Track {
|
||||
readyState: "live" | "ended" = "live";
|
||||
stopped = 0;
|
||||
stop() { this.stopped++; this.readyState = "ended"; }
|
||||
clone() {
|
||||
const copy = new Track();
|
||||
copy.readyState = this.readyState;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeStream {
|
||||
kind?: string;
|
||||
constructor(readonly track = new Track()) {}
|
||||
getTracks() { return [this.track]; }
|
||||
getAudioTracks() { return [this.track]; }
|
||||
getVideoTracks() { return []; }
|
||||
clone() {
|
||||
const copy = new FakeStream(this.track.clone());
|
||||
copy.kind = this.kind;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeRecorder {
|
||||
static instances: FakeRecorder[] = [];
|
||||
static failKinds = new Set<string>();
|
||||
static emptyKinds = new Set<string>();
|
||||
state: "inactive" | "recording" = "inactive";
|
||||
mimeType = "audio/webm";
|
||||
stops = 0;
|
||||
startTimeslice: number | undefined;
|
||||
ondataavailable: ((event: { data: Blob }) => void) | null = null;
|
||||
onstop: (() => void) | null = null;
|
||||
onerror: ((event: { error: Error }) => void) | null = null;
|
||||
constructor(readonly stream: FakeStream, _options?: unknown) {
|
||||
FakeRecorder.instances.push(this);
|
||||
}
|
||||
start(timeslice?: number) {
|
||||
const kind = (this.stream as FakeStream & { kind?: string }).kind;
|
||||
if (kind && FakeRecorder.failKinds.has(kind)) throw new Error(`${kind} recorder start failed`);
|
||||
this.startTimeslice = timeslice;
|
||||
this.state = "recording";
|
||||
}
|
||||
requestData() {}
|
||||
stop() {
|
||||
this.stops++;
|
||||
this.state = "inactive";
|
||||
}
|
||||
finish() {
|
||||
if (!FakeRecorder.emptyKinds.has((this.stream as FakeStream & { kind?: string }).kind ?? "")) {
|
||||
this.ondataavailable?.({ data: new Blob(["audio"]) });
|
||||
} else {
|
||||
this.ondataavailable?.({ data: new Blob([]) });
|
||||
}
|
||||
this.onstop?.();
|
||||
}
|
||||
}
|
||||
|
||||
const originalRecorder = globalThis.MediaRecorder;
|
||||
const originalURL = { createObjectURL: URL.createObjectURL, revokeObjectURL: URL.revokeObjectURL };
|
||||
|
||||
afterEach(() => {
|
||||
FakeRecorder.instances = [];
|
||||
FakeRecorder.failKinds = new Set();
|
||||
FakeRecorder.emptyKinds = new Set();
|
||||
// @ts-expect-error test stub restore
|
||||
globalThis.MediaRecorder = originalRecorder;
|
||||
URL.createObjectURL = originalURL.createObjectURL;
|
||||
URL.revokeObjectURL = originalURL.revokeObjectURL;
|
||||
});
|
||||
|
||||
function installRecorder() {
|
||||
// @ts-expect-error test stub
|
||||
globalThis.MediaRecorder = FakeRecorder;
|
||||
}
|
||||
|
||||
test("the raw tab must not reuse the denoised URL when the original take is missing", () => {
|
||||
const missingDry = micTestPlaybackSource("dry", { processed: "blob:processed", dry: "" });
|
||||
assert.equal(missingDry.src, "");
|
||||
assert.equal(missingDry.missing, true);
|
||||
assert.equal(missingDry.missingKey, "micTestOriginalUnavailable");
|
||||
|
||||
const processed = micTestPlaybackSource("processed", { processed: "blob:processed", dry: "" });
|
||||
assert.equal(processed.src, "blob:processed");
|
||||
assert.equal(processed.missing, false);
|
||||
assert.equal(processed.missingKey, "micTestDenoisedUnavailable");
|
||||
});
|
||||
|
||||
test("the denoised tab must not reuse the original URL when the processed take is missing", () => {
|
||||
const missingProcessed = micTestPlaybackSource("processed", { processed: "", dry: "blob:dry" });
|
||||
assert.equal(missingProcessed.src, "");
|
||||
assert.equal(missingProcessed.missing, true);
|
||||
assert.equal(missingProcessed.missingKey, "micTestDenoisedUnavailable");
|
||||
|
||||
const dry = micTestPlaybackSource("dry", { processed: "", dry: "blob:dry" });
|
||||
assert.equal(dry.src, "blob:dry");
|
||||
assert.equal(dry.missing, false);
|
||||
});
|
||||
|
||||
test("both sides of one take publish playback URLs after the shared deadline", async t => {
|
||||
installRecorder();
|
||||
const created: string[] = [];
|
||||
const urls = { processed: "", dry: "" };
|
||||
let active = false;
|
||||
let stopped = 0;
|
||||
t.mock.method(URL, "createObjectURL", () => `blob:${created.push("x")}`);
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
let deadline: (() => void) | undefined;
|
||||
t.mock.method(globalThis, "setTimeout", (callback: () => void, delay: number) => {
|
||||
assert.equal(delay, MICROPHONE_TEST_DURATION_MS);
|
||||
deadline = callback;
|
||||
return 1;
|
||||
});
|
||||
t.mock.method(globalThis, "clearTimeout", () => {});
|
||||
const dry = Object.assign(new FakeStream(), { kind: "dry" });
|
||||
const processed = Object.assign(new FakeStream(), { kind: "processed" });
|
||||
const test = createMicrophoneTest({
|
||||
prepare: async () => ({ dry, processed }),
|
||||
onActive(value) { active = value; },
|
||||
onUrl(url) { urls.processed = url; },
|
||||
onDryUrl(url) { urls.dry = url; },
|
||||
onStopped() { stopped++; },
|
||||
onError(error) { throw error; },
|
||||
});
|
||||
await test.start();
|
||||
assert.equal(FakeRecorder.instances.length, 2);
|
||||
assert.ok(FakeRecorder.instances.every(recorder => recorder.startTimeslice === 1_000));
|
||||
assert.equal(active, true);
|
||||
assert.ok(deadline);
|
||||
deadline();
|
||||
assert.equal(active, false);
|
||||
assert.equal(stopped, 0, "source teardown waits until recorders have flushed");
|
||||
assert.ok(FakeRecorder.instances.every(recorder => recorder.stops === 1));
|
||||
for (const recorder of FakeRecorder.instances) recorder.finish();
|
||||
assert.equal(stopped, 1);
|
||||
assert.equal(urls.processed, "blob:1");
|
||||
assert.equal(urls.dry, "blob:2");
|
||||
assert.equal(dry.track.readyState, "live");
|
||||
assert.equal(processed.track.readyState, "live");
|
||||
});
|
||||
|
||||
test("empty dry chunks leave the denoised URL and an empty original URL", async t => {
|
||||
installRecorder();
|
||||
FakeRecorder.emptyKinds.add("dry");
|
||||
const urls = { processed: "pending", dry: "pending" };
|
||||
t.mock.method(URL, "createObjectURL", () => "blob:processed-only");
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
t.mock.method(globalThis, "setTimeout", () => 1);
|
||||
t.mock.method(globalThis, "clearTimeout", () => {});
|
||||
const test = createMicrophoneTest({
|
||||
prepare: async () => ({
|
||||
dry: Object.assign(new FakeStream(), { kind: "dry" }),
|
||||
processed: Object.assign(new FakeStream(), { kind: "processed" }),
|
||||
}),
|
||||
onActive() {},
|
||||
onUrl(url) { urls.processed = url; },
|
||||
onDryUrl(url) { urls.dry = url; },
|
||||
onStopped() {},
|
||||
onError(error) { throw error; },
|
||||
});
|
||||
await test.start();
|
||||
test.stop();
|
||||
for (const recorder of FakeRecorder.instances) recorder.finish();
|
||||
assert.equal(urls.processed, "blob:processed-only");
|
||||
assert.equal(urls.dry, "");
|
||||
const playback = micTestPlaybackSource("dry", urls);
|
||||
assert.equal(playback.missing, true);
|
||||
assert.equal(playback.src, "");
|
||||
assert.equal(micTestPlaybackSource("processed", urls).src, "blob:processed-only");
|
||||
});
|
||||
|
||||
test("a dry start failure still records the processed side", async t => {
|
||||
installRecorder();
|
||||
FakeRecorder.failKinds.add("dry");
|
||||
const urls = { processed: "", dry: "" };
|
||||
t.mock.method(URL, "createObjectURL", () => "blob:processed-only");
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
t.mock.method(globalThis, "setTimeout", () => 1);
|
||||
t.mock.method(globalThis, "clearTimeout", () => {});
|
||||
const test = createMicrophoneTest({
|
||||
prepare: async () => ({
|
||||
dry: Object.assign(new FakeStream(), { kind: "dry" }),
|
||||
processed: Object.assign(new FakeStream(), { kind: "processed" }),
|
||||
}),
|
||||
onActive() {},
|
||||
onUrl(url) { urls.processed = url; },
|
||||
onDryUrl(url) { urls.dry = url; },
|
||||
onStopped() {},
|
||||
onError(error) { throw error; },
|
||||
});
|
||||
await test.start();
|
||||
assert.equal(FakeRecorder.instances.length, 2);
|
||||
assert.equal(FakeRecorder.instances.filter(recorder => recorder.state === "recording").length, 1);
|
||||
test.stop();
|
||||
for (const recorder of FakeRecorder.instances) {
|
||||
if (recorder.stops) recorder.finish();
|
||||
}
|
||||
assert.equal(urls.processed, "blob:processed-only");
|
||||
assert.equal(urls.dry, "");
|
||||
});
|
||||
|
||||
test("recording uses clones so stopping the test does not end the live tracks", async t => {
|
||||
installRecorder();
|
||||
t.mock.method(URL, "createObjectURL", () => "blob:ok");
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
t.mock.method(globalThis, "setTimeout", () => 1);
|
||||
t.mock.method(globalThis, "clearTimeout", () => {});
|
||||
const dry = Object.assign(new FakeStream(), { kind: "dry" });
|
||||
const processed = Object.assign(new FakeStream(), { kind: "processed" });
|
||||
const test = createMicrophoneTest({
|
||||
prepare: async () => ({ dry, processed }),
|
||||
onActive() {},
|
||||
onUrl() {},
|
||||
onDryUrl() {},
|
||||
onStopped() {},
|
||||
onError(error) { throw error; },
|
||||
});
|
||||
await test.start();
|
||||
const clones = FakeRecorder.instances.map(recorder => recorder.stream);
|
||||
assert.ok(clones.every(stream => stream !== dry && stream !== processed));
|
||||
test.stop();
|
||||
for (const recorder of FakeRecorder.instances) recorder.finish();
|
||||
assert.equal(dry.track.readyState, "live");
|
||||
assert.equal(processed.track.readyState, "live");
|
||||
assert.ok(clones.every(stream => stream.track.readyState === "ended"));
|
||||
});
|
||||
|
||||
|
||||
|
||||
test("a processed onstop that arrives before the dry dataavailable still keeps the original take", async t => {
|
||||
installRecorder();
|
||||
const urls = { processed: "", dry: "" };
|
||||
t.mock.method(URL, "createObjectURL", (blob: Blob) => blob.size ? `blob:${blob.size}` : "blob:empty");
|
||||
t.mock.method(URL, "revokeObjectURL", () => {});
|
||||
t.mock.method(globalThis, "setTimeout", () => 1);
|
||||
t.mock.method(globalThis, "clearTimeout", () => {});
|
||||
const test = createMicrophoneTest({
|
||||
prepare: async () => ({
|
||||
dry: Object.assign(new FakeStream(), { kind: "dry" }),
|
||||
processed: Object.assign(new FakeStream(), { kind: "processed" }),
|
||||
}),
|
||||
onActive() {},
|
||||
onUrl(url) { urls.processed = url; },
|
||||
onDryUrl(url) { urls.dry = url; },
|
||||
onStopped() {},
|
||||
onError(error) { throw error; },
|
||||
});
|
||||
await test.start();
|
||||
test.stop();
|
||||
const processed = FakeRecorder.instances.find(recorder => (recorder.stream as FakeStream & { kind?: string }).kind === "processed");
|
||||
const dry = FakeRecorder.instances.find(recorder => (recorder.stream as FakeStream & { kind?: string }).kind === "dry");
|
||||
assert.ok(processed && dry);
|
||||
processed!.ondataavailable?.({ data: new Blob(["processed-audio"]) });
|
||||
processed!.onstop?.();
|
||||
assert.equal(urls.processed, "", "must not publish until the dry recorder also stops");
|
||||
assert.equal(urls.dry, "");
|
||||
dry!.ondataavailable?.({ data: new Blob(["dry-audio"]) });
|
||||
dry!.onstop?.();
|
||||
assert.ok(urls.processed.startsWith("blob:"));
|
||||
assert.ok(urls.dry.startsWith("blob:"));
|
||||
assert.notEqual(urls.dry, "");
|
||||
});
|
||||
|
||||
test("original and denoised unavailable copy exists in every UI language", () => {
|
||||
for (const key of ["micTestOriginalUnavailable", "micTestDenoisedUnavailable"] as const) {
|
||||
const values = (["zh", "en", "de", "ru", "ja"] as const).map(language => webClientTranslations[language][key]);
|
||||
assert.ok(values.every(value => typeof value === "string" && value.length > 0), key);
|
||||
assert.equal(new Set(values).size, 5, key);
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface MicrophoneTestStreams {
|
||||
/** Raw getUserMedia stream, before any denoising. */
|
||||
/** Raw pre-denoise stream (graph dry tap, or a raw getUserMedia stream). */
|
||||
dry: MediaStream;
|
||||
/** Graph output that is actually sent to the room. */
|
||||
processed: MediaStream;
|
||||
@@ -21,12 +21,72 @@ interface RecorderSlot {
|
||||
recorder: MediaRecorder;
|
||||
chunks: Blob[];
|
||||
stopped: boolean;
|
||||
release(): void;
|
||||
}
|
||||
|
||||
interface Recording {
|
||||
slots: RecorderSlot[];
|
||||
timer: number | null;
|
||||
stopped: boolean;
|
||||
inactive: boolean;
|
||||
}
|
||||
|
||||
export const MICROPHONE_TEST_DURATION_MS = 5_000;
|
||||
|
||||
|
||||
function scheduleTimeout(callback: () => void, ms: number): number {
|
||||
const host = typeof window !== "undefined" ? window : globalThis;
|
||||
return host.setTimeout(callback, ms) as unknown as number;
|
||||
}
|
||||
|
||||
function cancelTimeout(timer: number): void {
|
||||
const host = typeof window !== "undefined" ? window : globalThis;
|
||||
host.clearTimeout(timer);
|
||||
}
|
||||
|
||||
|
||||
export type MicTestPlaybackVariant = "dry" | "processed";
|
||||
|
||||
export function micTestPlaybackSource(
|
||||
variant: MicTestPlaybackVariant,
|
||||
urls: { processed: string; dry: string },
|
||||
): {
|
||||
src: string;
|
||||
missing: boolean;
|
||||
missingKey: "micTestOriginalUnavailable" | "micTestDenoisedUnavailable";
|
||||
} {
|
||||
// Each tab shows only its own take. Falling back to the other URL would
|
||||
// hide a missing recording by swapping in the wrong audio.
|
||||
const src = variant === "dry" ? urls.dry : urls.processed;
|
||||
return {
|
||||
src,
|
||||
missing: !src,
|
||||
missingKey: variant === "dry" ? "micTestOriginalUnavailable" : "micTestDenoisedUnavailable",
|
||||
};
|
||||
}
|
||||
|
||||
function preferredRecorderOptions(): MediaRecorderOptions | undefined {
|
||||
if (typeof MediaRecorder === "undefined" || typeof MediaRecorder.isTypeSupported !== "function") return undefined;
|
||||
for (const mimeType of ["audio/webm;codecs=opus", "audio/webm", "audio/mp4"]) {
|
||||
try {
|
||||
if (MediaRecorder.isTypeSupported(mimeType)) return { mimeType };
|
||||
} catch { /* some stubs throw */ }
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function cloneForRecording(stream: MediaStream): { stream: MediaStream; release(): void } {
|
||||
const cloned = typeof stream.clone === "function" ? stream.clone() : stream;
|
||||
const owns = cloned !== stream;
|
||||
return {
|
||||
stream: cloned,
|
||||
release() {
|
||||
if (!owns) return;
|
||||
for (const track of cloned.getTracks()) {
|
||||
try { track.stop(); } catch { /* already ended */ }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Capture belongs to the caller. This controller owns only the test operation,
|
||||
@@ -48,27 +108,38 @@ export function createMicrophoneTest(options: MicrophoneTestOptions) {
|
||||
clearUrl("processed");
|
||||
}
|
||||
|
||||
function finishCapture(recording: Recording): void {
|
||||
if (recording.timer !== null) window.clearTimeout(recording.timer);
|
||||
function markInactive(recording: Recording): void {
|
||||
if (recording.timer !== null) cancelTimeout(recording.timer);
|
||||
recording.timer = null;
|
||||
if (recording.inactive) return;
|
||||
recording.inactive = true;
|
||||
options.onActive(false);
|
||||
}
|
||||
|
||||
function finishCapture(recording: Recording): void {
|
||||
markInactive(recording);
|
||||
if (recording.stopped) return;
|
||||
recording.stopped = true;
|
||||
options.onActive(false);
|
||||
options.onStopped();
|
||||
}
|
||||
|
||||
function releaseSlots(recording: Recording): void {
|
||||
for (const slot of recording.slots) {
|
||||
if (slot.recorder.state !== "inactive") {
|
||||
try { slot.recorder.stop(); } catch { /* already ended */ }
|
||||
}
|
||||
slot.release();
|
||||
slot.chunks.length = 0;
|
||||
}
|
||||
recording.slots.length = 0;
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
const recording = current;
|
||||
current = null;
|
||||
if (recording) {
|
||||
finishCapture(recording);
|
||||
for (const slot of recording.slots) {
|
||||
if (slot.recorder.state !== "inactive") {
|
||||
try { slot.recorder.stop(); } catch { /* already ended */ }
|
||||
}
|
||||
slot.chunks.length = 0;
|
||||
}
|
||||
recording.slots.length = 0;
|
||||
releaseSlots(recording);
|
||||
}
|
||||
clearUrls();
|
||||
}
|
||||
@@ -77,37 +148,72 @@ export function createMicrophoneTest(options: MicrophoneTestOptions) {
|
||||
const recording = current;
|
||||
if (!recording) return;
|
||||
// A pending permission or device enumeration must not create a recorder.
|
||||
if (!recording.slots.length) current = null;
|
||||
finishCapture(recording);
|
||||
if (!recording.slots.length) {
|
||||
current = null;
|
||||
finishCapture(recording);
|
||||
return;
|
||||
}
|
||||
// Stop recorders first, while source tracks are still live. Releasing the
|
||||
// standalone microphone is deferred until finalizeSlot so the last chunk
|
||||
// can flush. Active is cleared immediately so the UI can leave the
|
||||
// recording state.
|
||||
markInactive(recording);
|
||||
for (const slot of recording.slots) {
|
||||
if (slot.recorder.state === "inactive") continue;
|
||||
try { slot.recorder.stop(); }
|
||||
catch (error) { dispose(); options.onError(error); return; }
|
||||
try {
|
||||
if (typeof slot.recorder.requestData === "function" && slot.recorder.state === "recording") {
|
||||
try { slot.recorder.requestData(); } catch { /* optional flush */ }
|
||||
}
|
||||
slot.recorder.stop();
|
||||
} catch (error) {
|
||||
dispose();
|
||||
options.onError(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function publishSlot(candidate: RecorderSlot): void {
|
||||
if (!candidate.chunks.length) {
|
||||
if (candidate.kind === "dry") options.onDryUrl("");
|
||||
else options.onUrl("");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const url = URL.createObjectURL(new Blob(candidate.chunks, { type: candidate.recorder.mimeType || "audio/webm" }));
|
||||
clearUrl(candidate.kind);
|
||||
urls[candidate.kind] = url;
|
||||
if (candidate.kind === "dry") options.onDryUrl(url);
|
||||
else options.onUrl(url);
|
||||
} catch (error) { options.onError(error); }
|
||||
candidate.chunks.length = 0;
|
||||
}
|
||||
|
||||
function finalizeSlot(recording: Recording, slot: RecorderSlot): void {
|
||||
slot.stopped = true;
|
||||
if (current !== recording) return;
|
||||
if (!recording.slots.every(candidate => candidate.stopped || candidate.recorder.state === "inactive")) return;
|
||||
if (current !== recording) {
|
||||
slot.release();
|
||||
return;
|
||||
}
|
||||
// Wait for every recorder's onstop. `state === "inactive"` only means
|
||||
// stop() was called; the last dataavailable may not have arrived yet.
|
||||
if (!recording.slots.every(candidate => candidate.stopped)) return;
|
||||
current = null;
|
||||
finishCapture(recording);
|
||||
for (const candidate of recording.slots) {
|
||||
if (!candidate.chunks.length) continue;
|
||||
try {
|
||||
const url = URL.createObjectURL(new Blob(candidate.chunks, { type: candidate.recorder.mimeType || "audio/webm" }));
|
||||
clearUrl(candidate.kind);
|
||||
urls[candidate.kind] = url;
|
||||
if (candidate.kind === "dry") options.onDryUrl(url);
|
||||
else options.onUrl(url);
|
||||
} catch (error) { options.onError(error); }
|
||||
candidate.chunks.length = 0;
|
||||
}
|
||||
for (const candidate of recording.slots) publishSlot(candidate);
|
||||
for (const candidate of recording.slots) candidate.release();
|
||||
}
|
||||
|
||||
function armDeadline(recording: Recording): void {
|
||||
if (recording.timer !== null || recording.inactive) return;
|
||||
recording.timer = scheduleTimeout(() => {
|
||||
if (current === recording) stop();
|
||||
}, MICROPHONE_TEST_DURATION_MS);
|
||||
}
|
||||
|
||||
async function start(): Promise<void> {
|
||||
dispose();
|
||||
const recording: Recording = { slots: [], timer: null, stopped: false };
|
||||
const recording: Recording = { slots: [], timer: null, stopped: false, inactive: false };
|
||||
current = recording;
|
||||
options.onActive(true);
|
||||
try {
|
||||
@@ -116,12 +222,16 @@ export function createMicrophoneTest(options: MicrophoneTestOptions) {
|
||||
// Keep the existing level-meter-only test on browsers without recording.
|
||||
if (typeof MediaRecorder === "undefined" || !streams) return;
|
||||
let startError: unknown = null;
|
||||
const optionsForRecorder = preferredRecorderOptions();
|
||||
for (const kind of ["processed", "dry"] as const) {
|
||||
const cloned = cloneForRecording(streams[kind]);
|
||||
try {
|
||||
const recorder = new MediaRecorder(streams[kind]);
|
||||
const slot: RecorderSlot = { kind, recorder, chunks: [], stopped: false };
|
||||
const recorder = optionsForRecorder
|
||||
? new MediaRecorder(cloned.stream, optionsForRecorder)
|
||||
: new MediaRecorder(cloned.stream);
|
||||
const slot: RecorderSlot = { kind, recorder, chunks: [], stopped: false, release: cloned.release };
|
||||
recorder.ondataavailable = event => {
|
||||
if (current === recording && event.data.size) slot.chunks.push(event.data);
|
||||
if (current === recording && event.data?.size) slot.chunks.push(event.data);
|
||||
};
|
||||
recorder.onstop = () => finalizeSlot(recording, slot);
|
||||
recorder.onerror = event => {
|
||||
@@ -129,10 +239,11 @@ export function createMicrophoneTest(options: MicrophoneTestOptions) {
|
||||
dispose();
|
||||
options.onError("error" in event ? event.error : new Error("Microphone recording failed"));
|
||||
};
|
||||
recorder.start();
|
||||
recorder.start(1_000);
|
||||
recording.slots.push(slot);
|
||||
} catch (error) {
|
||||
// One path failing must not disable the other; A/B degrades to mono.
|
||||
cloned.release();
|
||||
startError ??= error;
|
||||
}
|
||||
}
|
||||
@@ -141,9 +252,7 @@ export function createMicrophoneTest(options: MicrophoneTestOptions) {
|
||||
if (startError) throw startError;
|
||||
return;
|
||||
}
|
||||
recording.timer = window.setTimeout(() => {
|
||||
if (current === recording) stop();
|
||||
}, 5_000);
|
||||
armDeadline(recording);
|
||||
} catch (error) {
|
||||
if (current !== recording) return;
|
||||
dispose();
|
||||
|
||||
Reference in new issue
Block a user