Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
fix(external-api): handle the toggleNoiseSuppression command (#18110)
Navyac1365f2580ab
diff --git a/modules/API/API.js b/modules/API/API.jsindex fdc8a7077e..19a41bf41d 100755--- a/modules/API/API.js+++ b/modules/API/API.js@@ -107,7 +107,7 @@ import {import { answerKnockingParticipant, toggleLobbyMode } from '../../react/features/lobby/actions';import { getLobbyEnabled } from '../../react/features/lobby/functions';import { setSecondScreen } from '../../react/features/multi-screen/actions.web';-import { setNoiseSuppressionEnabled } from '../../react/features/noise-suppression/actions';+import { setNoiseSuppressionEnabled, toggleNoiseSuppression } from '../../react/features/noise-suppression/actions';import { hideNotification, showNotification } from '../../react/features/notifications/actions';import { NOTIFICATION_TIMEOUT_TYPE, NOTIFICATION_TYPE } from '../../react/features/notifications/constants';import {@@ -570,6 +570,9 @@ function initCommands() {'set-noise-suppression-enabled': (options = {}) => {APP.store.dispatch(setNoiseSuppressionEnabled(options.enabled));},+ 'toggle-noise-suppression': () => {+ APP.store.dispatch(toggleNoiseSuppression());+ },'toggle-subtitles': () => {APP.store.dispatch(toggleRequestingSubtitles());},@@ -2716,6 +2719,19 @@ class API {});}+ /**+ * Notify the external application (if API is enabled) when noise suppression is enabled or disabled.+ *+ * @param {boolean} enabled - Whether noise suppression is enabled or not.+ * @returns {void}+ */+ notifyNoiseSuppressionChanged(enabled) {+ this._sendEvent({+ name: 'noise-suppression-changed',+ enabled+ });+ }+/*** Disposes the allocated resources.*diff --git a/modules/API/external/external_api.js b/modules/API/external/external_api.jsindex 518db3aca2..bf6ed74b27 100644--- a/modules/API/external/external_api.js+++ b/modules/API/external/external_api.js@@ -157,6 +157,7 @@ const events = {'mouse-enter': 'mouseEnter','mouse-leave': 'mouseLeave','mouse-move': 'mouseMove',+ 'noise-suppression-changed': 'noiseSuppressionChanged','non-participant-message-received': 'nonParticipantMessageReceived','notification-triggered': 'notificationTriggered','outgoing-message': 'outgoingMessage',diff --git a/react/features/external-api/subscriber.ts b/react/features/external-api/subscriber.tsindex 32fd0dec45..a75fbf291b 100644--- a/react/features/external-api/subscriber.ts+++ b/react/features/external-api/subscriber.ts@@ -71,3 +71,13 @@ StateListenerRegistry.register(APP.API.notifyLowBandwidthModeChanged(enabled);});++/**+ * Notifies the external API when noise suppression is enabled or disabled.+ */+StateListenerRegistry.register(+ /* selector */ state => state['features/noise-suppression'].enabled,+ /* listener */ enabled => {+ APP.API.notifyNoiseSuppressionChanged(enabled);+ }+);diff --git a/react/features/noise-suppression/actions.ts b/react/features/noise-suppression/actions.tsindex e2e6aafd6a..56d4707bf4 100644--- a/react/features/noise-suppression/actions.ts+++ b/react/features/noise-suppression/actions.ts@@ -1,5 +1,6 @@import { IStore } from '../app/types';import { getLocalJitsiAudioTrack } from '../base/tracks/functions';+import { timeoutPromise } from '../base/util/timeoutPromise';import { showErrorNotification } from '../notifications/actions';import { NoiseSuppressionEffect } from '../stream-effects/noise-suppression/NoiseSuppressionEffect';@@ -23,19 +24,51 @@ export function setNoiseSuppressionEnabledState(enabled: boolean): any {};}+/**+ * The last queued noise suppression change. The enabled state is only updated once the effect has been applied to+ * (or removed from) the local audio track, so changes are run one after another, otherwise back-to-back calls would+ * all see the same, stale, state.+ */+let pendingChange: Promise<void> = Promise.resolve();++/**+ * The maximum time, in milliseconds, a queued noise suppression change is waited for before moving on to the next one.+ */+const CHANGE_TIMEOUT = 10_000;++/**+ * Runs the given noise suppression change once all the previously queued ones have finished.+ *+ * @param {Function} change - The change to run.+ * @returns {Promise<void>}+ */+function queueChange(change: () => Promise<void>): Promise<void> {+ // A change which never settles (e.g. the noise suppressor worklet failing to load) would otherwise block all the+ // later changes, as well as the callers awaiting them (e.g. screen sharing with audio).+ const result = pendingChange.then(() => timeoutPromise(change(), CHANGE_TIMEOUT).catch(error => {+ if (error?.message !== 'timeout') {+ throw error;+ }++ logger.error(`Noise suppression change did not complete within ${CHANGE_TIMEOUT}ms, moving on`);+ }));++ // Keep the queue going even if a change fails, the failure is still reported to the caller through result.+ pendingChange = result.catch(() => undefined);++ return result;+}+/*** Enabled/disable noise suppression depending on the current state.** @returns {Function}*/export function toggleNoiseSuppression(): any {- return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {- if (isNoiseSuppressionEnabled(getState())) {- dispatch(setNoiseSuppressionEnabled(false));- } else {- dispatch(setNoiseSuppressionEnabled(true));- }- };+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) =>++ // The state is read only when the change runs, so that it reflects any previously queued change.+ queueChange(() => dispatch(applyNoiseSuppressionEnabled(!isNoiseSuppressionEnabled(getState()))));}/**@@ -46,6 +79,18 @@ export function toggleNoiseSuppression(): any {* @returns {Function}*/export function setNoiseSuppressionEnabled(enabled: boolean): any {+ return (dispatch: IStore['dispatch']) => queueChange(() => dispatch(applyNoiseSuppressionEnabled(enabled)));+}++/**+ * Enables or disables noise suppression by applying or removing the {@link NoiseSuppressionEffect} on the local+ * audio track. Must only be run through {@link queueChange}.+ *+ * @param {boolean} enabled - Enable or disable noise suppression.+ *+ * @returns {Function}+ */+function applyNoiseSuppressionEnabled(enabled: boolean): any {return async (dispatch: IStore['dispatch'], getState: IStore['getState']) => {const state = getState();@@ -72,6 +117,8 @@ export function setNoiseSuppressionEnabled(enabled: boolean): any {try {if (enabled) {if (!canEnableNoiseSuppression(state, dispatch, localAudio)) {+ logger.warn('Noise suppression cannot be enabled for the current local audio track');+return;}diff --git a/tests/specs/iframe/noiseSuppression.spec.ts b/tests/specs/iframe/noiseSuppression.spec.tsnew file mode 100644index 0000000000..d71fbf33bc--- /dev/null+++ b/tests/specs/iframe/noiseSuppression.spec.ts@@ -0,0 +1,178 @@+import { expect } from '@wdio/globals';++import type { Participant } from '../../helpers/Participant';+import { setTestProperties } from '../../helpers/TestProperties';+import { ensureOneParticipant } from '../../helpers/participants';++import { checkIframeApi } from './util';++setTestProperties(__filename, {+ usesBrowsers: [ 'p1' ]+});++describe('Noise suppression iframe API commands and events', () => {+ let p1: Participant;++ /**+ * Reads the noise suppression state in the iframe: the redux flag and whether an effect is set on the local+ * audio track. Without a local audio track only the flag is updated, so the effect has to be checked as well.+ */+ async function getNoiseSuppressionState(): Promise<{ effectOnTrack: boolean; enabled: boolean; }> {+ await p1.switchToIFrame();++ return p1.execute(() => {+ const state = APP.store.getState();+ const localAudio = state['features/base/tracks'].find((t: any) => t.local && t.mediaType === 'audio');++ return {+ effectOnTrack: Boolean((localAudio?.jitsiTrack as any)?._streamEffect),+ enabled: state['features/noise-suppression'].enabled+ };+ });+ }++ /**+ * Waits for noise suppression to be enabled or disabled, both in redux and on the local audio track.+ *+ * @param expected Whether noise suppression is expected to be enabled.+ * @param timeoutMsg The message to fail with.+ */+ async function waitForNoiseSuppression(expected: boolean, timeoutMsg: string) {+ await p1.driver.waitUntil(+ async () => {+ const { effectOnTrack, enabled } = await getNoiseSuppressionState();++ return enabled === expected && effectOnTrack === expected;+ },+ {+ timeout: 10_000,+ timeoutMsg+ });+ }++ /**+ * Puts noise suppression in a known state, so that every case is independent of the previous ones and of the+ * state persisted in local storage. Clears the noiseSuppressionChanged event result afterwards.+ *+ * @param enabled Whether noise suppression should be enabled.+ */+ async function setInitialState(enabled: boolean) {+ await p1.switchToMainFrame();+ await p1.getIframeAPI().executeCommand('setNoiseSuppressionEnabled', { enabled });+ await waitForNoiseSuppression(enabled, `Could not ${enabled ? 'enable' : 'disable'} noise suppression`);++ await p1.switchToMainFrame();+ await p1.getIframeAPI().clearEventResults('noiseSuppressionChanged');+ }++ /**+ * Waits for the noiseSuppressionChanged event with the expected enabled value.+ *+ * @param expected The expected enabled value.+ * @param command The command which is expected to have triggered the event.+ */+ async function waitForChangedEvent(expected: boolean, command: string) {+ await p1.switchToMainFrame();+ await p1.driver.waitUntil(+ async () => (await p1.getIframeAPI().getEventResult('noiseSuppressionChanged'))?.enabled === expected,+ {+ timeout: 10_000,+ timeoutMsg: `noiseSuppressionChanged event (enabled: ${expected}) was not received for ${command}`+ });+ }++ /**+ * Executes the given iframe API command and checks that noise suppression ends up in the expected state and that+ * the noiseSuppressionChanged event is fired.+ *+ * @param command The iframe API command to execute.+ * @param expected Whether noise suppression is expected to be enabled afterwards.+ * @param args Arguments for the command.+ */+ async function executeAndExpect(command: string, expected: boolean, ...args: any[]) {+ await p1.switchToMainFrame();+ await p1.getIframeAPI().executeCommand(command, ...args);++ await waitForChangedEvent(expected, command);+ await waitForNoiseSuppression(expected, `Noise suppression was not ${expected ? 'enabled' : 'disabled'} by ${+ command}`);+ }++ it('joining the meeting', async () => {+ // A local audio track is needed, otherwise only the redux flag is updated and no effect is applied.+ await ensureOneParticipant({+ configOverwrite: {+ // The tests disable audio processing by default, with it disabled Chrome's fake microphone is stereo,+ // regardless of the requested channelCount, and noise suppression can't be enabled on stereo tracks.+ disableAP: false,+ startSilent: false,+ startWithAudioMuted: false+ }+ }, { name: 'p1', iFrameApi: true });++ p1 = ctx.p1;++ if (!await checkIframeApi(p1)) {+ return;+ }++ await p1.switchToIFrame();+ await p1.driver.waitUntil(+ () => p1.execute(() => APP.store.getState()['features/base/tracks']+ .some((t: any) => t.local && t.mediaType === 'audio' && t.jitsiTrack)),+ {+ timeout: 10_000,+ timeoutMsg: 'No local audio track was created'+ });++ // Noise suppression is only supported on mono tracks, see canEnableNoiseSuppression.+ expect(await p1.execute(() => APP.store.getState()['features/base/tracks']+ .find((t: any) => t.local && t.mediaType === 'audio')?.jitsiTrack.getTrack().getSettings().channelCount))+ .toBe(1);++ await p1.switchToMainFrame();+ await p1.getIframeAPI().addEventListener('noiseSuppressionChanged');+ });++ it('enables noise suppression via setNoiseSuppressionEnabled command', async () => {+ await setInitialState(false);+ await executeAndExpect('setNoiseSuppressionEnabled', true, { enabled: true });+ });++ it('disables noise suppression via setNoiseSuppressionEnabled command', async () => {+ await setInitialState(true);+ await executeAndExpect('setNoiseSuppressionEnabled', false, { enabled: false });+ });++ it('enables noise suppression via toggleNoiseSuppression command', async () => {+ await setInitialState(false);+ await executeAndExpect('toggleNoiseSuppression', true);+ });++ it('disables noise suppression via toggleNoiseSuppression command', async () => {+ await setInitialState(true);+ await executeAndExpect('toggleNoiseSuppression', false);+ });++ it('applies back-to-back toggleNoiseSuppression commands in order', async () => {+ await setInitialState(false);++ // Both commands are sent before the first one has finished applying the effect, they should still result in+ // on -> off and not in noise suppression being enabled twice.+ await p1.switchToMainFrame();+ await p1.execute(() => {+ const { jitsiAPI } = window as any;++ jitsiAPI.executeCommand('toggleNoiseSuppression');+ jitsiAPI.executeCommand('toggleNoiseSuppression');+ });++ await waitForChangedEvent(false, 'two toggleNoiseSuppression commands');+ await waitForNoiseSuppression(false, 'Noise suppression was not disabled by the second toggle');++ expect(await getNoiseSuppressionState()).toEqual({+ effectOnTrack: false,+ enabled: false+ });+ });+});