Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

fix(virtual-background): trip the inference failure breaker for every effect.

Jaya Allamsetty6db1b14b503f
diff --git a/react/features/base/tracks/loadEffects.web.ts b/react/features/base/tracks/loadEffects.web.ts
index 50419587a7..0d58f25dba 100644
--- a/react/features/base/tracks/loadEffects.web.ts
+++ b/react/features/base/tracks/loadEffects.web.ts
@@ -1,7 +1,9 @@
import { IStore } from '../../app/types';
import { NoiseSuppressionEffect } from '../../stream-effects/noise-suppression/NoiseSuppressionEffect';
import { createVirtualBackgroundEffect } from '../../stream-effects/virtual-background';
+import { backgroundEffectFailed } from '../../virtual-background/actions';
+import { getLocalJitsiVideoTrack } from './functions.any';
import logger from './logger';
/**
@@ -20,6 +22,20 @@ export default function loadEffects(store: IStore): Promise<any> {
const backgroundPromise = virtualBackground.backgroundEffectEnabled
? createVirtualBackgroundEffect(virtualBackground)
+ .then(effect => {
+ if (effect) {
+ effect.onInferenceFailure = () => {
+ const track = getLocalJitsiVideoTrack(store.getState());
+
+ // A stale effect no longer on the local video track has already gone passthrough.
+ if (track?._streamEffect === effect) {
+ store.dispatch(backgroundEffectFailed(track));
+ }
+ };
+ }
+
+ return effect;
+ })
.catch((error: Error) => {
logger.error('Failed to obtain the background effect instance with error: ', error);
diff --git a/react/features/stream-effects/virtual-background/BackgroundFrameProcessor.ts b/react/features/stream-effects/virtual-background/BackgroundFrameProcessor.ts
index e42ec2b92e..edc90c53bb 100644
--- a/react/features/stream-effects/virtual-background/BackgroundFrameProcessor.ts
+++ b/react/features/stream-effects/virtual-background/BackgroundFrameProcessor.ts
@@ -279,21 +279,30 @@ export default class BackgroundFrameProcessor {
/**
* Checks whether consecutive inference failures have exceeded the threshold. When they do,
- * fires the {@code onInferenceFailure} callback once and switches to permanent passthrough.
+ * stops the backend, switches to passthrough until the next init and fires the
+ * {@code onInferenceFailure} callback once if one is set.
*
* @private
* @returns {void}
*/
_checkFailureThreshold(): void {
- if (this._consecutiveFailures >= FAILURE_THRESHOLD && this.onInferenceFailure) {
- logger.error(
- '[BackgroundFrameProcessor] Persistent inference failure'
- + ` (${FAILURE_THRESHOLD} consecutive) — switching to passthrough`
- );
- this.onInferenceFailure();
- this.onInferenceFailure = null;
- this._isReady = false;
+ if (this._consecutiveFailures < FAILURE_THRESHOLD) {
+ return;
}
+
+ logger.error(
+ '[BackgroundFrameProcessor] Persistent inference failure'
+ + ` (${FAILURE_THRESHOLD} consecutive) — switching to passthrough`
+ );
+
+ // Trip even without an owner callback (effects created via loadEffects have none) and stop the
+ // worker, otherwise a permanent error such as a lost WebGPU device is retried on every frame.
+ this._isReady = false;
+ this._consecutiveFailures = 0;
+ this._backend.stop().catch(() => undefined);
+
+ this.onInferenceFailure?.();
+ this.onInferenceFailure = null;
}
/**
diff --git a/react/features/stream-effects/virtual-background/JitsiStreamBackgroundEffect.ts b/react/features/stream-effects/virtual-background/JitsiStreamBackgroundEffect.ts
index fd79d165ac..7f5d37e65b 100644
--- a/react/features/stream-effects/virtual-background/JitsiStreamBackgroundEffect.ts
+++ b/react/features/stream-effects/virtual-background/JitsiStreamBackgroundEffect.ts
@@ -194,7 +194,9 @@ export default class JitsiStreamBackgroundEffect {
this._startTimerLoop(async () => {
const result = await this._processor?.processFrame(this._inputVideoElement);
- if (result && this._outputCanvasCtx) {
+ // A frame still in flight when stopEffect clears the input video comes back 0x0, which
+ // drawImage rejects (and the rejection would end the timer loop).
+ if (result?.width && result.height && this._outputCanvasCtx) {
this._outputCanvasCtx.drawImage(result, 0, 0);
} else if (this._outputCanvasCtx) {
this._outputCanvasCtx.drawImage(
diff --git a/react/features/virtual-background/actions.ts b/react/features/virtual-background/actions.ts
index cf7a748230..03f98efb1a 100644
--- a/react/features/virtual-background/actions.ts
+++ b/react/features/virtual-background/actions.ts
@@ -50,6 +50,21 @@ async function handleEffectFailure(
));
}
+/**
+ * Handles a persistent mid-session inference failure: clears the effect and leaves the same state as
+ * selecting "None", so the dialog doesn't show a background as selected while it is off.
+ *
+ * @param {Object} jitsiTrack - The local video track carrying the failed effect.
+ * @returns {Function}
+ */
+export function backgroundEffectFailed(jitsiTrack: TrackParam) {
+ return (dispatch: IStore['dispatch']) => handleEffectFailure(
+ dispatch,
+ { backgroundEffectEnabled: false, selectedThumbnail: 'none' },
+ jitsiTrack,
+ 'persistent inference failure');
+}
+
/**
* Signals the local participant activate the virtual background video or not.
*
@@ -74,9 +89,10 @@ export function toggleBackgroundEffect(options: IVirtualBackground, jitsiTrack:
const effect = await createVirtualBackgroundEffect(virtualBackground);
if (effect) {
+ // Turn VB off rather than reverting to prevBackground, which the settings preview
+ // may already have switched on.
effect.onInferenceFailure = () => {
- handleEffectFailure(dispatch, prevBackground, jitsiTrack,
- 'persistent inference failure');
+ dispatch(backgroundEffectFailed(jitsiTrack));
};
}
diff --git a/tests/pageobjects/VirtualBackgroundDialog.ts b/tests/pageobjects/VirtualBackgroundDialog.ts
index 9372e47585..765c77a464 100644
--- a/tests/pageobjects/VirtualBackgroundDialog.ts
+++ b/tests/pageobjects/VirtualBackgroundDialog.ts
@@ -36,9 +36,9 @@ export default class VirtualBackgroundDialog extends BaseDialog {
*/
private async clickAndWaitChecked(selector: string, label: string): Promise<void> {
await this.participant.log(`VirtualBackgroundDialog: clicking ${label} thumbnail`);
- const el = this.participant.driver.$(selector);
- await el.waitForClickable({ timeout: 3000, timeoutMsg: `${label} thumbnail not clickable` });
+ await this.participant.driver.$(selector)
+ .waitForClickable({ timeout: 3000, timeoutMsg: `${label} thumbnail not clickable` });
// Selecting an effect makes the preview (re)load the segmentation model/wasm, which
// saturates the main thread. Two flaky failure modes follow from that:
@@ -50,13 +50,21 @@ export default class VirtualBackgroundDialog extends BaseDialog {
// Re-issue the click on every poll until aria-checked confirms it landed (covers 1), and
// allow a generous timeout for the cold-start re-render under load (covers 2). The poll
// interval is kept large so a still-pending selection is not needlessly re-triggered.
+ // The element is looked up on every poll and errors count as "not yet": a re-render can
+ // replace the node mid-poll, and a click can time out while the main thread is blocked.
await this.participant.driver.waitUntil(
async () => {
- if (await el.getAttribute('aria-checked') === 'true') {
- return true;
- }
+ try {
+ const el = this.participant.driver.$(selector);
- await el.click();
+ if (await el.getAttribute('aria-checked') === 'true') {
+ return true;
+ }
+
+ await el.click();
+ } catch {
+ // Retried on the next poll.
+ }
return false;
},
diff --git a/tests/specs/misc/virtualBackgroundV2.spec.ts b/tests/specs/misc/virtualBackgroundV2.spec.ts
index 2d34fb3440..38e27da253 100644
--- a/tests/specs/misc/virtualBackgroundV2.spec.ts
+++ b/tests/specs/misc/virtualBackgroundV2.spec.ts
@@ -115,6 +115,87 @@ async function waitForEffectEnabled(expected: boolean, timeout = 15000, stabilit
);
}
+/** Simulates a lost WebGPU device by answering every V2 'infer' request with 'infer_error'. */
+async function setInferenceFailures(enabled: boolean): Promise<void> {
+ await ctx.p1.execute((on: boolean) => {
+ const w = window as any;
+
+ if (!w.__vbInferFault) {
+ const fault = { enabled: false, inferCalls: 0 };
+ const originalPostMessage = Worker.prototype.postMessage;
+
+ w.__vbInferFault = fault;
+ Worker.prototype.postMessage = function(this: Worker, msg: any, transfer?: any) {
+ if (msg?.type === 'infer' && msg.bitmap) {
+ fault.inferCalls++;
+ if (fault.enabled) {
+ msg.bitmap.close();
+ setTimeout(() => this.dispatchEvent(new MessageEvent('message', {
+ data: { error: 'Device is lost (injected)', type: 'infer_error' }
+ })), 0);
+
+ return;
+ }
+ }
+
+ return (originalPostMessage as any).call(this, msg, transfer);
+ };
+ }
+ w.__vbInferFault.enabled = on;
+ }, enabled);
+}
+
+async function getInferenceFailureState(): Promise<{
+ effectOnTrack: boolean; errorNotifications: number; inferCalls: number; }> {
+ return ctx.p1.execute(() => {
+ const state = APP.store.getState();
+ const localVideo = state['features/base/tracks'].find((t: any) => t.local && t.mediaType === 'video');
+
+ return {
+ effectOnTrack: Boolean((localVideo?.jitsiTrack as any)?._streamEffect),
+ errorNotifications: state['features/notifications'].notifications.filter(
+ (n: any) => n.props?.titleKey === 'virtualBackground.backgroundEffectError').length,
+ inferCalls: (window as any).__vbInferFault?.inferCalls ?? 0
+ };
+ });
+}
+
+/** Trips the inference breaker and checks it stays tripped with VB off. */
+async function expectBreakerToTrip(): Promise<void> {
+ // A ready processor may still be stuck on its first inference (slow on CI's software GPU), and frames
+ // queued behind it never reach the injected failure, so wait until frames are actually flowing.
+ await ctx.p1.driver.waitUntil(
+ async () => ((await getV2ProcessorState())?.frameCount ?? 0) >= 5,
+ { timeout: 60000, timeoutMsg: 'V2 effect did not process 5 frames within 60s' }
+ );
+
+ await setInferenceFailures(true);
+
+ try {
+ // The breaker trips after 30 consecutive failures.
+ await waitForEffectEnabled(false, 30000).catch(async err => {
+ throw new Error(`${err.message}; state: ${JSON.stringify({
+ ...await getInferenceFailureState(),
+ processor: await getV2ProcessorState()
+ })}`);
+ });
+
+ const afterTrip = await getInferenceFailureState();
+
+ await ctx.p1.driver.pause(2000);
+
+ const later = await getInferenceFailureState();
+
+ expect(later.inferCalls).toBe(afterTrip.inferCalls);
+ expect(later.effectOnTrack).toBe(false);
+ expect(later.errorNotifications).toBe(1);
+ expect((await getVBState()).selectedThumbnail).toBe('none');
+ } finally {
+ // Leave inference working for later tests even if an assertion above failed.
+ await setInferenceFailures(false);
+ }
+}
+
describe('Virtual backgrounds V2 engine', () => {
it('joining the meeting with V2 enabled', async () => {
await ensureOneParticipant({
@@ -334,3 +415,41 @@ describe('Virtual backgrounds V2 with insertable streams disabled', () => {
await waitForEffectEnabled(false);
});
});
+
+describe('Virtual backgrounds V2 persistent inference failure', () => {
+ it('hangup and rejoin with V2 enabled', async () => {
+ await hangupAllParticipants();
+ await ensureOneParticipant({
+ configOverwrite: V2_CONFIG
+ });
+ });
+
+ it('enabled from the dialog — breaker stops inference and turns VB off', async () => {
+ await openVBDialog();
+ await ctx.p1.getVirtualBackgroundDialog().clickBlur();
+ await ctx.p1.getVirtualBackgroundDialog().confirm();
+ await waitForEffectEnabled(true);
+ await waitForV2EffectReady();
+
+ await expectBreakerToTrip();
+ });
+
+ it('already enabled when joining — breaker stops inference and turns VB off', async () => {
+ await openVBDialog();
+ await ctx.p1.getVirtualBackgroundDialog().clickBlur();
+ await ctx.p1.getVirtualBackgroundDialog().confirm();
+ await waitForEffectEnabled(true);
+
+ // The persisted VB state makes the rejoin create the effect via loadEffects.
+ await hangupAllParticipants();
+ await ensureOneParticipant({
+ configOverwrite: V2_CONFIG
+ });
+ await waitForEffectEnabled(true);
+
+ // The rejoin loads a fresh page, so the worker and model start cold.
+ await waitForV2EffectReady(30000);
+
+ await expectBreakerToTrip();
+ });
+});