@voltkit-rtc/client 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +102 -0
  3. package/dist/cjs/diagnostics.d.ts +1 -1
  4. package/dist/cjs/diagnostics.js +1 -1
  5. package/dist/cjs/effects-core.d.ts +95 -0
  6. package/dist/cjs/effects-core.d.ts.map +1 -0
  7. package/dist/cjs/effects-core.js +154 -0
  8. package/dist/cjs/effects-core.js.map +1 -0
  9. package/dist/cjs/effects-gl.d.ts +79 -0
  10. package/dist/cjs/effects-gl.d.ts.map +1 -0
  11. package/dist/cjs/effects-gl.js +351 -0
  12. package/dist/cjs/effects-gl.js.map +1 -0
  13. package/dist/cjs/index.d.ts +57 -0
  14. package/dist/cjs/index.d.ts.map +1 -1
  15. package/dist/cjs/index.js +278 -64
  16. package/dist/cjs/index.js.map +1 -1
  17. package/dist/cjs/noise-suppression.d.ts +44 -0
  18. package/dist/cjs/noise-suppression.d.ts.map +1 -0
  19. package/dist/cjs/noise-suppression.js +103 -0
  20. package/dist/cjs/noise-suppression.js.map +1 -0
  21. package/dist/cjs/processors.d.ts +34 -0
  22. package/dist/cjs/processors.d.ts.map +1 -0
  23. package/dist/cjs/processors.js +10 -0
  24. package/dist/cjs/processors.js.map +1 -0
  25. package/dist/cjs/quality.d.ts +7 -1
  26. package/dist/cjs/quality.d.ts.map +1 -1
  27. package/dist/cjs/quality.js +2 -1
  28. package/dist/cjs/quality.js.map +1 -1
  29. package/dist/cjs/video-effects.d.ts +93 -0
  30. package/dist/cjs/video-effects.d.ts.map +1 -0
  31. package/dist/cjs/video-effects.js +493 -0
  32. package/dist/cjs/video-effects.js.map +1 -0
  33. package/dist/esm/diagnostics.d.ts +1 -1
  34. package/dist/esm/diagnostics.js +1 -1
  35. package/dist/esm/effects-core.d.ts +95 -0
  36. package/dist/esm/effects-core.d.ts.map +1 -0
  37. package/dist/esm/effects-core.js +142 -0
  38. package/dist/esm/effects-core.js.map +1 -0
  39. package/dist/esm/effects-gl.d.ts +79 -0
  40. package/dist/esm/effects-gl.d.ts.map +1 -0
  41. package/dist/esm/effects-gl.js +347 -0
  42. package/dist/esm/effects-gl.js.map +1 -0
  43. package/dist/esm/index.d.ts +57 -0
  44. package/dist/esm/index.d.ts.map +1 -1
  45. package/dist/esm/index.js +278 -64
  46. package/dist/esm/index.js.map +1 -1
  47. package/dist/esm/noise-suppression.d.ts +44 -0
  48. package/dist/esm/noise-suppression.d.ts.map +1 -0
  49. package/dist/esm/noise-suppression.js +99 -0
  50. package/dist/esm/noise-suppression.js.map +1 -0
  51. package/dist/esm/processors.d.ts +34 -0
  52. package/dist/esm/processors.d.ts.map +1 -0
  53. package/dist/esm/processors.js +9 -0
  54. package/dist/esm/processors.js.map +1 -0
  55. package/dist/esm/quality.d.ts +7 -1
  56. package/dist/esm/quality.d.ts.map +1 -1
  57. package/dist/esm/quality.js +2 -1
  58. package/dist/esm/quality.js.map +1 -1
  59. package/dist/esm/video-effects.d.ts +93 -0
  60. package/dist/esm/video-effects.d.ts.map +1 -0
  61. package/dist/esm/video-effects.js +488 -0
  62. package/dist/esm/video-effects.js.map +1 -0
  63. package/package.json +31 -1
  64. package/src/diagnostics.ts +1 -1
  65. package/src/effects-core.ts +177 -0
  66. package/src/effects-gl.ts +384 -0
  67. package/src/index.ts +276 -63
  68. package/src/noise-suppression.ts +135 -0
  69. package/src/processors.ts +35 -0
  70. package/src/quality.ts +9 -2
  71. package/src/video-effects.ts +552 -0
@@ -0,0 +1,552 @@
1
+ /**
2
+ * Virtual background and beauty for the camera (docs/implementation-progress/RTC_PERF_PROGRESS.md P3-5): a blurred or
3
+ * replaced background and skin smoothing, as LiveKit's track processors, Agora's and ZEGOCLOUD's virtual background and
4
+ * beauty extensions, and Tencent TRTC's video effect plugin do -- in the browser, on the GPU.
5
+ *
6
+ * Imported on its own (`@voltkit-rtc/client/video-effects`), so an app that does not use it never ships it:
7
+ *
8
+ * import { createVideoEffects } from '@voltkit-rtc/client/video-effects';
9
+ * const effects = createVideoEffects({ background: 'blur', beauty: true });
10
+ * await client.setVideoProcessor(effects);
11
+ * await effects.update({ background: { image: '/office.jpg' } }); // live, no pause for viewers
12
+ *
13
+ * Finding the person takes Google's MediaPipe selfie segmenter: install `@mediapipe/tasks-vision@0.10.35` next to the
14
+ * SDK (an optional peer dependency, 0.10.35 exactly -- later versions report usage to Google). Its wasm (3 MB
15
+ * compressed) and the model (250 kB) load the first time a background effect is used: the wasm from jsDelivr at that
16
+ * version and the model from Google, unless you serve them yourself (`wasmPath`, `modelUrl`). Beauty alone needs none
17
+ * of it.
18
+ *
19
+ * Chrome and Edge process each camera frame as it arrives (insertable streams: smooth, and it keeps going in a
20
+ * background tab). Firefox and Safari draw from a hidden video on a worker's timer into a captured canvas -- what
21
+ * LiveKit, Twilio and Amazon Chime fall back to -- which a background tab can slow down.
22
+ */
23
+ import {
24
+ backgroundMode,
25
+ beautySettings,
26
+ blurLevel,
27
+ blurSigma,
28
+ coverFit,
29
+ MonotonicClock,
30
+ SegmentationPacer,
31
+ segmentationSize,
32
+ smoothMask,
33
+ type BackgroundImageSource,
34
+ type BackgroundSetting,
35
+ type BeautyOptions,
36
+ type BeautySettings,
37
+ } from './effects-core.js';
38
+ import { EffectsRenderer } from './effects-gl.js';
39
+ import type { VideoTrackProcessor } from './processors.js';
40
+
41
+ export type { BackgroundImageSource, BackgroundSetting, BeautyOptions, BeautySettings } from './effects-core.js';
42
+
43
+ /** The `@mediapipe/tasks-vision` version this SDK was tested with; the default wasm URL points at it. */
44
+ export const MEDIAPIPE_VERSION = '0.10.35';
45
+ const MEDIAPIPE_WASM = `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${MEDIAPIPE_VERSION}/wasm`;
46
+ /** Google's selfie segmenter for portrait and square pictures (phones), at a fixed version. */
47
+ export const DEFAULT_SEGMENTER_MODEL = 'https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/1/selfie_segmenter.tflite';
48
+ /**
49
+ * Its landscape version, for wide pictures (webcams): fed a 16:9 frame, the square model leaves patches of the room
50
+ * beside the head, the landscape one traces it cleanly (as LiveKit, Twilio, Chime and TRTC use for webcams).
51
+ */
52
+ export const DEFAULT_LANDSCAPE_MODEL = 'https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter_landscape/float16/1/selfie_segmenter_landscape.tflite';
53
+
54
+ export interface VideoEffectsOptions {
55
+ /** `'none'` (default), `'blur'`, or `{ image }`: a URL, Blob, image, canvas or ImageBitmap, fitted to cover. */
56
+ background?: BackgroundSetting;
57
+ /** Blur strength, 1 (light) to 10 (strong). Default 5. */
58
+ blur?: number;
59
+ /** Beauty: `true` for the defaults, or each of `smooth`, `brighten`, `redness`, `sharpen` (0-1). Off by default. */
60
+ beauty?: BeautyOptions | boolean | null;
61
+ /** A folder serving `vision_wasm_internal.{js,wasm}` and `vision_wasm_nosimd_internal.{js,wasm}` (from
62
+ * `node_modules/@mediapipe/tasks-vision/wasm`). Default: jsDelivr at MEDIAPIPE_VERSION. */
63
+ wasmPath?: string;
64
+ /** Where the segmentation model is served, for every picture. Default: DEFAULT_LANDSCAPE_MODEL for wide pictures,
65
+ * DEFAULT_SEGMENTER_MODEL for portrait and square ones. */
66
+ modelUrl?: string;
67
+ /** The most frames a second to process; the camera's rate by default. */
68
+ maxFrameRate?: number;
69
+ /**
70
+ * Told when this device cannot keep up even finding the person only every few frames (Agora's `onoverload`): turn
71
+ * the background off, or lower the camera's frame rate or size. Told again with `false` when it can.
72
+ */
73
+ onOverload?: (overloaded: boolean) => void;
74
+ }
75
+
76
+ /** What `update` can change while the effects run. */
77
+ export type VideoEffectsUpdate = Pick<VideoEffectsOptions, 'background' | 'blur' | 'beauty'>;
78
+
79
+ export interface VideoEffects extends VideoTrackProcessor {
80
+ /**
81
+ * Change the effects while they run: no new camera, no pause for viewers. Resolves once the change shows; a picture
82
+ * that cannot be loaded, or a segmenter that cannot start, rejects and leaves the effects as they were.
83
+ */
84
+ update(changes: VideoEffectsUpdate): Promise<void>;
85
+ /** The effects in force now. */
86
+ readonly settings: { background: 'none' | 'blur' | 'image'; blur: number; beauty: BeautySettings | null };
87
+ /** How hard the device works: the person is found every `segmentEvery` frames, in `segmentMs` on average. */
88
+ readonly stats: { segmentEvery: number; segmentMs: number; overloaded: boolean };
89
+ }
90
+
91
+ /** What finds the person: MediaPipe's ImageSegmenter, or a stand-in in tests. */
92
+ export interface PersonSegmenter {
93
+ /** Find the person in `input`; `use` gets the confidence (0-1) of each pixel being the person, at `input`'s size. */
94
+ segment(input: TexImageSource, timestampMs: number, use: (confidence: Float32Array) => void): void;
95
+ close(): void;
96
+ }
97
+
98
+ /** Stood in for by tests. */
99
+ export interface VideoEffectsDeps {
100
+ loadSegmenter(wasmPath: string, modelUrl: string): Promise<PersonSegmenter>;
101
+ /** How frames are taken and given back; chosen from the browser's features when absent. */
102
+ pump?: 'insertable' | 'canvas';
103
+ }
104
+
105
+ /** Whether this browser can run the effects (WebGL2, and a way to take and give back frames). */
106
+ export function isVideoEffectsSupported(): boolean {
107
+ if (typeof document === 'undefined' || typeof WebGL2RenderingContext === 'undefined') return false;
108
+ if (pumpKind() === null) return false;
109
+ try {
110
+ const gl = document.createElement('canvas').getContext('webgl2');
111
+ if (!gl) return false;
112
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
113
+ return true;
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+
119
+ type FrameGenerator = MediaStreamTrack & { writable: WritableStream<VideoFrame> };
120
+ type InsertableGlobals = {
121
+ MediaStreamTrackProcessor?: new (init: { track: MediaStreamTrack }) => { readable: ReadableStream<VideoFrame> };
122
+ MediaStreamTrackGenerator?: new (init: { kind: 'video' }) => FrameGenerator;
123
+ };
124
+
125
+ function pumpKind(): 'insertable' | 'canvas' | null {
126
+ const g = globalThis as unknown as InsertableGlobals;
127
+ if (typeof g.MediaStreamTrackProcessor === 'function' && typeof g.MediaStreamTrackGenerator === 'function' && typeof VideoFrame === 'function') return 'insertable';
128
+ if (typeof HTMLCanvasElement !== 'undefined' && typeof HTMLCanvasElement.prototype.captureStream === 'function') return 'canvas';
129
+ return null;
130
+ }
131
+
132
+ /** MediaPipe's selfie segmenter, on the GPU where it starts, else the CPU. */
133
+ async function loadMediaPipe(wasmPath: string, modelUrl: string): Promise<PersonSegmenter> {
134
+ const vision = await import('@mediapipe/tasks-vision');
135
+ const fileset = await vision.FilesetResolver.forVisionTasks(wasmPath);
136
+ const make = (delegate: 'GPU' | 'CPU') => vision.ImageSegmenter.createFromOptions(fileset, {
137
+ baseOptions: { modelAssetPath: modelUrl, delegate },
138
+ runningMode: 'VIDEO',
139
+ outputConfidenceMasks: true,
140
+ outputCategoryMask: false,
141
+ });
142
+ let segmenter: Awaited<ReturnType<typeof make>>;
143
+ try {
144
+ segmenter = await make('GPU');
145
+ } catch {
146
+ segmenter = await make('CPU');
147
+ }
148
+ return {
149
+ segment(input, timestampMs, use) {
150
+ segmenter.segmentForVideo(input, timestampMs, (result) => {
151
+ // The selfie segmenter's one mask: how sure it is that each pixel is the person. Only valid in here.
152
+ const mask = result.confidenceMasks?.[0];
153
+ if (mask) use(mask.getAsFloat32Array());
154
+ });
155
+ },
156
+ close() {
157
+ segmenter.close();
158
+ },
159
+ };
160
+ }
161
+
162
+ const browserDeps: VideoEffectsDeps = { loadSegmenter: loadMediaPipe };
163
+
164
+ /** The largest side a background picture is kept at, to spare the GPU's memory. */
165
+ const PICTURE_MAX = 1920;
166
+
167
+ interface Picture {
168
+ image: TexImageSource;
169
+ width: number;
170
+ height: number;
171
+ close(): void;
172
+ }
173
+
174
+ async function loadPicture(source: BackgroundImageSource): Promise<Picture> {
175
+ let input: ImageBitmapSource;
176
+ if (typeof source === 'string') {
177
+ const img = new Image();
178
+ img.crossOrigin = 'anonymous';
179
+ img.decoding = 'async';
180
+ img.src = source;
181
+ await img.decode();
182
+ input = img;
183
+ } else {
184
+ input = source as ImageBitmapSource;
185
+ }
186
+ let bitmap = await createImageBitmap(input);
187
+ const longest = Math.max(bitmap.width, bitmap.height);
188
+ if (longest > PICTURE_MAX) {
189
+ const scale = PICTURE_MAX / longest;
190
+ const smaller = await createImageBitmap(bitmap, { resizeWidth: Math.round(bitmap.width * scale), resizeHeight: Math.round(bitmap.height * scale), resizeQuality: 'high' });
191
+ bitmap.close();
192
+ bitmap = smaller;
193
+ }
194
+ const b = bitmap;
195
+ return { image: b, width: b.width, height: b.height, close: () => b.close() };
196
+ }
197
+
198
+ /** One camera track being processed. */
199
+ interface Pipeline {
200
+ output: MediaStreamTrack;
201
+ stop(): void;
202
+ }
203
+
204
+ type Draw = (input: TexImageSource & CanvasImageSource, width: number, height: number, frameIntervalMs: number) => void;
205
+
206
+ /** Chrome and Edge: every camera frame as it arrives, out through a generator track; no timer, no page rendering. */
207
+ function insertablePump(source: MediaStreamTrack, draw: Draw, canvas: HTMLCanvasElement | OffscreenCanvas, frameIntervalMs: number, minGapUs: number): Pipeline {
208
+ const g = globalThis as unknown as Required<InsertableGlobals>;
209
+ const reader = new g.MediaStreamTrackProcessor({ track: source }).readable.getReader();
210
+ const generator = new g.MediaStreamTrackGenerator({ kind: 'video' });
211
+ const writer = generator.writable.getWriter();
212
+ let stopped = false;
213
+ let lastOut = Number.NEGATIVE_INFINITY;
214
+ let failures = 0;
215
+ const stop = () => {
216
+ if (stopped) return;
217
+ stopped = true;
218
+ void reader.cancel().catch(() => undefined);
219
+ void writer.close().catch(() => undefined);
220
+ generator.stop();
221
+ };
222
+ void (async () => {
223
+ try {
224
+ for (;;) {
225
+ const { value: frame, done } = await reader.read();
226
+ if (done || !frame) return;
227
+ if (stopped || generator.readyState === 'ended') {
228
+ frame.close();
229
+ return;
230
+ }
231
+ // Paused (the camera is off), or sooner than maxFrameRate allows: nothing to do for this one.
232
+ if (!generator.enabled || frame.timestamp - lastOut < minGapUs) {
233
+ frame.close();
234
+ continue;
235
+ }
236
+ let out: VideoFrame | null = null;
237
+ try {
238
+ draw(frame, frame.displayWidth, frame.displayHeight, frameIntervalMs);
239
+ out = new VideoFrame(canvas, { timestamp: frame.timestamp });
240
+ lastOut = frame.timestamp;
241
+ failures = 0;
242
+ } catch (err) {
243
+ // A frame that cannot be drawn is dropped, never sent as it is: the background may be what is hidden.
244
+ if ((failures += 1) === 1) console.warn('video effects: a frame could not be processed', err);
245
+ } finally {
246
+ frame.close();
247
+ }
248
+ if (out) await writer.write(out);
249
+ }
250
+ } catch {
251
+ // The output was stopped, or the camera went.
252
+ } finally {
253
+ stop();
254
+ }
255
+ })();
256
+ return { output: generator, stop };
257
+ }
258
+
259
+ /** A timer that keeps time in a background tab: a worker's (LiveKit's FrameTicker), the page's if a CSP refuses it. */
260
+ function startTicker(ms: number, tick: () => void): () => void {
261
+ let interval: ReturnType<typeof setInterval> | null = null;
262
+ const onPage = () => {
263
+ if (interval === null) interval = setInterval(tick, ms);
264
+ };
265
+ let worker: Worker | null = null;
266
+ let url: string | null = null;
267
+ try {
268
+ url = URL.createObjectURL(new Blob(['let t=null;onmessage=(e)=>{clearInterval(t);t=e.data>0?setInterval(()=>postMessage(0),e.data):null;};'], { type: 'text/javascript' }));
269
+ worker = new Worker(url);
270
+ worker.onmessage = () => tick();
271
+ worker.onerror = () => {
272
+ worker?.terminate();
273
+ worker = null;
274
+ onPage();
275
+ };
276
+ worker.postMessage(ms);
277
+ } catch {
278
+ worker = null;
279
+ onPage();
280
+ }
281
+ return () => {
282
+ worker?.terminate();
283
+ worker = null;
284
+ if (interval !== null) clearInterval(interval);
285
+ interval = null;
286
+ if (url) URL.revokeObjectURL(url);
287
+ };
288
+ }
289
+
290
+ /** Firefox and Safari: a hidden video drawn on a worker's timer, the canvas captured as the output. */
291
+ function canvasPump(source: MediaStreamTrack, draw: Draw, canvas: HTMLCanvasElement, frameIntervalMs: number): Pipeline {
292
+ const video = document.createElement('video');
293
+ video.muted = true;
294
+ video.playsInline = true;
295
+ video.autoplay = true;
296
+ video.srcObject = new MediaStream([source]);
297
+ const play = () => { void video.play().catch(() => undefined); };
298
+ play();
299
+ const output = canvas.captureStream().getVideoTracks()[0];
300
+ if (!output) throw new Error('video effects: this browser gives no track from a canvas');
301
+ let stopped = false;
302
+ let lastTime = -1;
303
+ let failures = 0;
304
+ const stop = () => {
305
+ if (stopped) return;
306
+ stopped = true;
307
+ stopTicker();
308
+ video.pause();
309
+ video.srcObject = null;
310
+ output.stop();
311
+ };
312
+ const stopTicker = startTicker(frameIntervalMs, () => {
313
+ if (stopped) return;
314
+ if (output.readyState === 'ended' || source.readyState === 'ended') {
315
+ stop();
316
+ return;
317
+ }
318
+ // WebKit can refuse play() until later: keep asking.
319
+ if (video.paused) play();
320
+ if (!output.enabled || video.readyState < 2 || video.videoWidth === 0) return;
321
+ if (video.currentTime === lastTime) return;
322
+ lastTime = video.currentTime;
323
+ try {
324
+ draw(video, video.videoWidth, video.videoHeight, frameIntervalMs);
325
+ failures = 0;
326
+ } catch (err) {
327
+ if ((failures += 1) === 1) console.warn('video effects: a frame could not be processed', err);
328
+ }
329
+ });
330
+ return { output, stop };
331
+ }
332
+
333
+ /** Virtual background and beauty, for `client.setVideoProcessor()`. */
334
+ export function createVideoEffects(options: VideoEffectsOptions = {}, stand: Partial<VideoEffectsDeps> = {}): VideoEffects {
335
+ const deps: VideoEffectsDeps = { ...browserDeps, ...stand };
336
+ const wasmPath = options.wasmPath ?? MEDIAPIPE_WASM;
337
+ const modelFor = (width: number, height: number): string => options.modelUrl ?? (width > height ? DEFAULT_LANDSCAPE_MODEL : DEFAULT_SEGMENTER_MODEL);
338
+ const maxFrameRate = typeof options.maxFrameRate === 'number' && options.maxFrameRate > 0 ? options.maxFrameRate : null;
339
+ const state: { mode: 'none' | 'blur' | 'image'; blur: number; beauty: BeautySettings | null } = {
340
+ mode: 'none',
341
+ blur: blurLevel(options.blur),
342
+ beauty: beautySettings(options.beauty),
343
+ };
344
+ let picture: Picture | null = null;
345
+ // By model: one for wide pictures, one for tall ones, each loaded when first needed.
346
+ const segmenters = new Map<string, PersonSegmenter>();
347
+ const loading = new Map<string, Promise<PersonSegmenter>>();
348
+ // The camera's shape, for the model to load before it is seen; a webcam's until a camera is given.
349
+ let shape = { width: 1280, height: 720 };
350
+ let renderer: EffectsRenderer | null = null;
351
+ let pipeline: Pipeline | null = null;
352
+ let destroyed = false;
353
+ let overloaded = false;
354
+ const pacer = new SegmentationPacer();
355
+ const clock = new MonotonicClock();
356
+ // Per camera: the mask and how far along it is.
357
+ let maskReady = false;
358
+ let steady: Float32Array | null = null;
359
+ let maskBytes = new Uint8Array(0);
360
+ let frameIndex = 0;
361
+ let segCanvas: HTMLCanvasElement | OffscreenCanvas | null = null;
362
+ let segContext: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null = null;
363
+ let pictureUploaded: Picture | null = null;
364
+
365
+ const ensureSegmenter = (model: string): Promise<PersonSegmenter> => {
366
+ const ready = segmenters.get(model);
367
+ if (ready) return Promise.resolve(ready);
368
+ let pending = loading.get(model);
369
+ if (!pending) {
370
+ pending = deps.loadSegmenter(wasmPath, model).then(
371
+ (s) => {
372
+ loading.delete(model);
373
+ if (destroyed) {
374
+ s.close();
375
+ throw new Error('video effects: destroyed');
376
+ }
377
+ segmenters.set(model, s);
378
+ return s;
379
+ },
380
+ (err: unknown) => {
381
+ loading.delete(model); // tried again next time (a network blip)
382
+ throw err;
383
+ },
384
+ );
385
+ loading.set(model, pending);
386
+ }
387
+ return pending;
388
+ };
389
+
390
+ /** A fresh start for the mask: nothing behind the person shows until the next one is found. */
391
+ const restartMask = () => {
392
+ maskReady = false;
393
+ steady = null;
394
+ frameIndex = 0;
395
+ };
396
+
397
+ const segmentInto = (input: TexImageSource & CanvasImageSource, width: number, height: number, frameIntervalMs: number) => {
398
+ const model = modelFor(width, height);
399
+ let seg = segmenters.get(model);
400
+ if (!seg) {
401
+ // The camera turned (a phone rotated): the other model loads meanwhile, and the one there is goes on.
402
+ void ensureSegmenter(model).catch(() => undefined);
403
+ seg = segmenters.values().next().value;
404
+ }
405
+ if (!seg || !renderer) return;
406
+ const size = segmentationSize(width, height);
407
+ if (!segCanvas || segCanvas.width !== size.width || segCanvas.height !== size.height) {
408
+ segCanvas = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(size.width, size.height) : Object.assign(document.createElement('canvas'), size);
409
+ segContext = segCanvas.getContext('2d') as CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null;
410
+ maskBytes = new Uint8Array(size.width * size.height);
411
+ steady = null;
412
+ }
413
+ if (!segContext) return;
414
+ segContext.drawImage(input, 0, 0, size.width, size.height);
415
+ const started = performance.now();
416
+ seg.segment(segCanvas, clock.next(started), (confidence) => {
417
+ if (confidence.length !== size.width * size.height || !renderer) return;
418
+ steady = smoothMask(confidence, steady, maskBytes);
419
+ renderer.uploadMask(maskBytes, size.width, size.height);
420
+ maskReady = true;
421
+ });
422
+ const now = performance.now();
423
+ pacer.report(now - started, frameIntervalMs, now);
424
+ const over = pacer.overloaded(frameIntervalMs);
425
+ if (over !== overloaded) {
426
+ overloaded = over;
427
+ try { options.onOverload?.(over); } catch { /* the app's */ }
428
+ }
429
+ };
430
+
431
+ const draw: Draw = (input, width, height, frameIntervalMs) => {
432
+ const r = renderer;
433
+ if (!r || r.lost || !(width > 0 && height > 0)) return;
434
+ r.setSize(width, height);
435
+ r.uploadFrame(input);
436
+ const mode = state.mode;
437
+ if (mode !== 'none') {
438
+ if (pacer.shouldSegment(frameIndex)) segmentInto(input, width, height, frameIntervalMs);
439
+ frameIndex += 1;
440
+ }
441
+ if (mode === 'image' && picture && pictureUploaded !== picture) {
442
+ r.setPicture(picture.image, picture.width, picture.height);
443
+ pictureUploaded = picture;
444
+ } else if (mode !== 'image' && pictureUploaded) {
445
+ r.setPicture(null);
446
+ pictureUploaded = null;
447
+ }
448
+ r.render({
449
+ mode,
450
+ blurSigma: blurSigma(state.blur, r.size.blurHeight),
451
+ beauty: state.beauty,
452
+ maskReady,
453
+ cover: picture ? coverFit(picture.width, picture.height, width, height) : { sx: 1, sy: 1, ox: 0, oy: 0 },
454
+ });
455
+ };
456
+
457
+ const apply = async (changes: VideoEffectsUpdate): Promise<void> => {
458
+ if (destroyed) throw new Error('video effects: destroyed');
459
+ let mode = state.mode;
460
+ let nextPicture: Picture | null | undefined;
461
+ if ('background' in changes) {
462
+ mode = backgroundMode(changes.background);
463
+ // Loaded before anything changes: one that fails leaves the effects as they were.
464
+ if (mode === 'image') nextPicture = await loadPicture((changes.background as { image: BackgroundImageSource }).image);
465
+ if (mode !== 'none') {
466
+ try {
467
+ await ensureSegmenter(modelFor(shape.width, shape.height));
468
+ } catch (err) {
469
+ nextPicture?.close();
470
+ throw err;
471
+ }
472
+ }
473
+ }
474
+ if (destroyed) {
475
+ nextPicture?.close();
476
+ throw new Error('video effects: destroyed');
477
+ }
478
+ if ('blur' in changes) state.blur = blurLevel(changes.blur);
479
+ if ('beauty' in changes) state.beauty = beautySettings(changes.beauty);
480
+ if (mode !== state.mode) restartMask();
481
+ if (nextPicture !== undefined || mode !== 'image') {
482
+ const old = picture;
483
+ picture = nextPicture ?? null;
484
+ if (old && old !== picture) old.close();
485
+ }
486
+ state.mode = mode;
487
+ };
488
+
489
+ // The background asked for at creation starts loading now, so it is likely ready by the time the camera is.
490
+ let queue: Promise<void> = apply({ background: options.background ?? 'none' });
491
+ queue.catch(() => undefined);
492
+
493
+ const pumpChoice = deps.pump ?? pumpKind();
494
+
495
+ return {
496
+ name: 'video-effects',
497
+
498
+ async process(track: MediaStreamTrack): Promise<MediaStreamTrack> {
499
+ if (destroyed) throw new Error('video effects: destroyed');
500
+ if (!pumpChoice) throw new Error('video effects are not supported in this browser');
501
+ await queue; // the background asked for at creation: a failure is the SDK's to report
502
+ const settings = track.getSettings();
503
+ if (typeof settings.width === 'number' && typeof settings.height === 'number' && settings.width > 0 && settings.height > 0) {
504
+ shape = { width: settings.width, height: settings.height };
505
+ }
506
+ // The model for this camera's shape, before its first frame: a background shows nothing behind the person meanwhile.
507
+ if (state.mode !== 'none') await ensureSegmenter(modelFor(shape.width, shape.height));
508
+ pipeline?.stop();
509
+ pipeline = null;
510
+ if (!renderer) {
511
+ const canvas = pumpChoice === 'insertable' && typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(2, 2) : document.createElement('canvas');
512
+ renderer = new EffectsRenderer(canvas);
513
+ }
514
+ restartMask();
515
+ const cameraRate = typeof settings.frameRate === 'number' && settings.frameRate > 0 ? settings.frameRate : 30;
516
+ const rate = maxFrameRate ? Math.min(maxFrameRate, cameraRate) : cameraRate;
517
+ const frameIntervalMs = 1000 / rate;
518
+ pipeline = pumpChoice === 'insertable'
519
+ ? insertablePump(track, draw, renderer.canvas, frameIntervalMs, maxFrameRate ? (1e6 / maxFrameRate) * 0.8 : 0)
520
+ : canvasPump(track, draw, renderer.canvas as HTMLCanvasElement, frameIntervalMs);
521
+ return pipeline.output;
522
+ },
523
+
524
+ update(changes: VideoEffectsUpdate): Promise<void> {
525
+ // One change at a time, in the order asked.
526
+ const next = queue.catch(() => undefined).then(() => apply(changes));
527
+ queue = next.catch(() => undefined);
528
+ return next;
529
+ },
530
+
531
+ get settings() {
532
+ return { background: state.mode, blur: state.blur, beauty: state.beauty ? { ...state.beauty } : null };
533
+ },
534
+
535
+ get stats() {
536
+ return { segmentEvery: pacer.interval, segmentMs: Math.round(pacer.segmentMs * 10) / 10, overloaded };
537
+ },
538
+
539
+ destroy(): void {
540
+ if (destroyed) return;
541
+ destroyed = true;
542
+ pipeline?.stop();
543
+ pipeline = null;
544
+ for (const s of segmenters.values()) s.close();
545
+ segmenters.clear();
546
+ renderer?.dispose();
547
+ renderer = null;
548
+ picture?.close();
549
+ picture = null;
550
+ },
551
+ };
552
+ }