@voltkit-rtc/client 0.7.3 → 0.9.0

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 (129) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +346 -2
  3. package/dist/cjs/adaptive.d.ts +104 -0
  4. package/dist/cjs/adaptive.d.ts.map +1 -0
  5. package/dist/cjs/adaptive.js +263 -0
  6. package/dist/cjs/adaptive.js.map +1 -0
  7. package/dist/cjs/devices.d.ts +42 -0
  8. package/dist/cjs/devices.d.ts.map +1 -0
  9. package/dist/cjs/devices.js +56 -0
  10. package/dist/cjs/devices.js.map +1 -0
  11. package/dist/cjs/diagnostics.d.ts +65 -0
  12. package/dist/cjs/diagnostics.d.ts.map +1 -0
  13. package/dist/cjs/diagnostics.js +69 -0
  14. package/dist/cjs/diagnostics.js.map +1 -0
  15. package/dist/cjs/effects-core.d.ts +95 -0
  16. package/dist/cjs/effects-core.d.ts.map +1 -0
  17. package/dist/cjs/effects-core.js +154 -0
  18. package/dist/cjs/effects-core.js.map +1 -0
  19. package/dist/cjs/effects-gl.d.ts +79 -0
  20. package/dist/cjs/effects-gl.d.ts.map +1 -0
  21. package/dist/cjs/effects-gl.js +351 -0
  22. package/dist/cjs/effects-gl.js.map +1 -0
  23. package/dist/cjs/fallback.d.ts +81 -0
  24. package/dist/cjs/fallback.d.ts.map +1 -0
  25. package/dist/cjs/fallback.js +148 -0
  26. package/dist/cjs/fallback.js.map +1 -0
  27. package/dist/cjs/health.d.ts +70 -0
  28. package/dist/cjs/health.d.ts.map +1 -0
  29. package/dist/cjs/health.js +116 -0
  30. package/dist/cjs/health.js.map +1 -0
  31. package/dist/cjs/index.d.ts +396 -0
  32. package/dist/cjs/index.d.ts.map +1 -1
  33. package/dist/cjs/index.js +1367 -81
  34. package/dist/cjs/index.js.map +1 -1
  35. package/dist/cjs/link.d.ts +99 -0
  36. package/dist/cjs/link.d.ts.map +1 -0
  37. package/dist/cjs/link.js +219 -0
  38. package/dist/cjs/link.js.map +1 -0
  39. package/dist/cjs/noise-suppression.d.ts +44 -0
  40. package/dist/cjs/noise-suppression.d.ts.map +1 -0
  41. package/dist/cjs/noise-suppression.js +103 -0
  42. package/dist/cjs/noise-suppression.js.map +1 -0
  43. package/dist/cjs/preflight.d.ts +79 -0
  44. package/dist/cjs/preflight.d.ts.map +1 -0
  45. package/dist/cjs/preflight.js +159 -0
  46. package/dist/cjs/preflight.js.map +1 -0
  47. package/dist/cjs/processors.d.ts +34 -0
  48. package/dist/cjs/processors.d.ts.map +1 -0
  49. package/dist/cjs/processors.js +10 -0
  50. package/dist/cjs/processors.js.map +1 -0
  51. package/dist/cjs/speakers.d.ts +34 -0
  52. package/dist/cjs/speakers.d.ts.map +1 -0
  53. package/dist/cjs/speakers.js +71 -0
  54. package/dist/cjs/speakers.js.map +1 -0
  55. package/dist/cjs/video-effects.d.ts +93 -0
  56. package/dist/cjs/video-effects.d.ts.map +1 -0
  57. package/dist/cjs/video-effects.js +493 -0
  58. package/dist/cjs/video-effects.js.map +1 -0
  59. package/dist/esm/adaptive.d.ts +104 -0
  60. package/dist/esm/adaptive.d.ts.map +1 -0
  61. package/dist/esm/adaptive.js +256 -0
  62. package/dist/esm/adaptive.js.map +1 -0
  63. package/dist/esm/devices.d.ts +42 -0
  64. package/dist/esm/devices.d.ts.map +1 -0
  65. package/dist/esm/devices.js +50 -0
  66. package/dist/esm/devices.js.map +1 -0
  67. package/dist/esm/diagnostics.d.ts +65 -0
  68. package/dist/esm/diagnostics.d.ts.map +1 -0
  69. package/dist/esm/diagnostics.js +65 -0
  70. package/dist/esm/diagnostics.js.map +1 -0
  71. package/dist/esm/effects-core.d.ts +95 -0
  72. package/dist/esm/effects-core.d.ts.map +1 -0
  73. package/dist/esm/effects-core.js +142 -0
  74. package/dist/esm/effects-core.js.map +1 -0
  75. package/dist/esm/effects-gl.d.ts +79 -0
  76. package/dist/esm/effects-gl.d.ts.map +1 -0
  77. package/dist/esm/effects-gl.js +347 -0
  78. package/dist/esm/effects-gl.js.map +1 -0
  79. package/dist/esm/fallback.d.ts +81 -0
  80. package/dist/esm/fallback.d.ts.map +1 -0
  81. package/dist/esm/fallback.js +142 -0
  82. package/dist/esm/fallback.js.map +1 -0
  83. package/dist/esm/health.d.ts +70 -0
  84. package/dist/esm/health.d.ts.map +1 -0
  85. package/dist/esm/health.js +111 -0
  86. package/dist/esm/health.js.map +1 -0
  87. package/dist/esm/index.d.ts +396 -0
  88. package/dist/esm/index.d.ts.map +1 -1
  89. package/dist/esm/index.js +1365 -81
  90. package/dist/esm/index.js.map +1 -1
  91. package/dist/esm/link.d.ts +99 -0
  92. package/dist/esm/link.d.ts.map +1 -0
  93. package/dist/esm/link.js +214 -0
  94. package/dist/esm/link.js.map +1 -0
  95. package/dist/esm/noise-suppression.d.ts +44 -0
  96. package/dist/esm/noise-suppression.d.ts.map +1 -0
  97. package/dist/esm/noise-suppression.js +99 -0
  98. package/dist/esm/noise-suppression.js.map +1 -0
  99. package/dist/esm/preflight.d.ts +79 -0
  100. package/dist/esm/preflight.d.ts.map +1 -0
  101. package/dist/esm/preflight.js +153 -0
  102. package/dist/esm/preflight.js.map +1 -0
  103. package/dist/esm/processors.d.ts +34 -0
  104. package/dist/esm/processors.d.ts.map +1 -0
  105. package/dist/esm/processors.js +9 -0
  106. package/dist/esm/processors.js.map +1 -0
  107. package/dist/esm/speakers.d.ts +34 -0
  108. package/dist/esm/speakers.d.ts.map +1 -0
  109. package/dist/esm/speakers.js +67 -0
  110. package/dist/esm/speakers.js.map +1 -0
  111. package/dist/esm/video-effects.d.ts +93 -0
  112. package/dist/esm/video-effects.d.ts.map +1 -0
  113. package/dist/esm/video-effects.js +488 -0
  114. package/dist/esm/video-effects.js.map +1 -0
  115. package/package.json +31 -1
  116. package/src/adaptive.ts +295 -0
  117. package/src/devices.ts +70 -0
  118. package/src/diagnostics.ts +94 -0
  119. package/src/effects-core.ts +177 -0
  120. package/src/effects-gl.ts +384 -0
  121. package/src/fallback.ts +169 -0
  122. package/src/health.ts +127 -0
  123. package/src/index.ts +1364 -81
  124. package/src/link.ts +255 -0
  125. package/src/noise-suppression.ts +135 -0
  126. package/src/preflight.ts +191 -0
  127. package/src/processors.ts +35 -0
  128. package/src/speakers.ts +66 -0
  129. package/src/video-effects.ts +552 -0
@@ -0,0 +1,384 @@
1
+ /**
2
+ * The WebGL2 side of video effects (docs/implementation-progress/RTC_PERF_PROGRESS.md P3-5): the camera frame and the
3
+ * person mask in, the finished picture out on one canvas. Done on the GPU as LiveKit, Stream, Twilio and TRTC do:
4
+ *
5
+ * - **Blur** at a quarter of the size (cheap at any resolution), weighted by the mask so the person's own colours never
6
+ * bleed into the blur around them -- no halo (Stream's mask-weighted blur) -- in two separable Gaussian passes.
7
+ * - **Edges** follow the person's outline rather than the mask's coarse grid: the mask is sampled jointly with the
8
+ * frame's colours (a joint bilateral filter, as Stream and Twilio refine theirs).
9
+ * - **Background picture** fitted like `object-fit: cover`.
10
+ * - **Beauty** without a face model: skin found by its colour (YCbCr), smoothed with an edge-preserving filter so eyes
11
+ * and lips stay sharp, brightened in the midtones, a touch rosier, and detail off the skin sharpened.
12
+ *
13
+ * Every texture is kept in picture order (the first row is the top); only the last pass, to the canvas, flips.
14
+ */
15
+ import type { BeautySettings } from './effects-core.js';
16
+
17
+ const VERTEX = `#version 300 es
18
+ in vec2 position;
19
+ uniform float flipY;
20
+ out vec2 uv;
21
+ void main() {
22
+ uv = vec2(position.x * 0.5 + 0.5, flipY > 0.5 ? 0.5 - position.y * 0.5 : 0.5 + position.y * 0.5);
23
+ gl_Position = vec4(position, 0.0, 1.0);
24
+ }`;
25
+
26
+ /** The frame at a quarter size, premultiplied by how much of each pixel is background. */
27
+ const DOWNSAMPLE = `#version 300 es
28
+ precision mediump float;
29
+ in vec2 uv;
30
+ out vec4 color;
31
+ uniform sampler2D frame;
32
+ uniform sampler2D mask;
33
+ uniform float maskReady;
34
+ uniform vec2 edge;
35
+ void main() {
36
+ vec3 c = texture(frame, uv).rgb;
37
+ float person = maskReady > 0.5 ? smoothstep(edge.x, edge.y, texture(mask, uv).r) : 0.0;
38
+ float background = 1.0 - person;
39
+ color = vec4(c * background, background);
40
+ }`;
41
+
42
+ /** One direction of a Gaussian blur, on premultiplied colour. */
43
+ const BLUR = `#version 300 es
44
+ precision mediump float;
45
+ in vec2 uv;
46
+ out vec4 color;
47
+ uniform sampler2D source;
48
+ uniform vec2 direction;
49
+ uniform float sigma;
50
+ void main() {
51
+ vec4 sum = texture(source, uv);
52
+ float total = 1.0;
53
+ for (int i = 1; i <= 32; i++) {
54
+ float x = float(i);
55
+ if (x > sigma * 3.0) break;
56
+ float w = exp(-x * x / (2.0 * sigma * sigma));
57
+ sum += (texture(source, uv + direction * x) + texture(source, uv - direction * x)) * w;
58
+ total += 2.0 * w;
59
+ }
60
+ color = sum / total;
61
+ }`;
62
+
63
+ const COMPOSITE = `#version 300 es
64
+ precision highp float;
65
+ in vec2 uv;
66
+ out vec4 color;
67
+ uniform sampler2D frame;
68
+ uniform sampler2D mask;
69
+ uniform sampler2D blurred;
70
+ uniform sampler2D picture;
71
+ uniform int mode;
72
+ uniform float maskReady;
73
+ uniform vec2 edge;
74
+ uniform vec2 texel;
75
+ uniform vec2 maskTexel;
76
+ uniform vec4 cover;
77
+ uniform vec4 beauty;
78
+ uniform float beautyOn;
79
+ uniform float beautyRadius;
80
+
81
+ const vec2 RING[8] = vec2[8](vec2(1.0, 0.0), vec2(0.7071, 0.7071), vec2(0.0, 1.0), vec2(-0.7071, 0.7071),
82
+ vec2(-1.0, 0.0), vec2(-0.7071, -0.7071), vec2(0.0, -1.0), vec2(0.7071, -0.7071));
83
+
84
+ float skinOf(vec3 c) {
85
+ float y = dot(c, vec3(0.299, 0.587, 0.114));
86
+ float cb = 0.5 + (c.b - y) * 0.564;
87
+ float cr = 0.5 + (c.r - y) * 0.713;
88
+ float s = smoothstep(0.27, 0.31, cb) * (1.0 - smoothstep(0.49, 0.53, cb))
89
+ * smoothstep(0.51, 0.55, cr) * (1.0 - smoothstep(0.67, 0.71, cr));
90
+ return s * smoothstep(0.06, 0.15, y);
91
+ }
92
+
93
+ vec3 beautify(vec3 c0) {
94
+ vec3 sum = c0;
95
+ float total = 1.0;
96
+ for (int r = 1; r <= 2; r++) {
97
+ float radius = beautyRadius * float(r);
98
+ float near = r == 1 ? 0.8 : 0.5;
99
+ for (int i = 0; i < 8; i++) {
100
+ vec3 c = texture(frame, uv + RING[i] * radius * texel).rgb;
101
+ vec3 d = c - c0;
102
+ float w = near * exp(-dot(d, d) * 60.0);
103
+ sum += c * w;
104
+ total += w;
105
+ }
106
+ }
107
+ vec3 smoothed = sum / total;
108
+ float skin = skinOf(c0);
109
+ vec3 c = mix(c0, smoothed, beauty.x * skin);
110
+ c += (c0 - smoothed) * beauty.w * (1.0 - skin) * 1.5;
111
+ float lift = beauty.y * (0.35 + 0.65 * skin) * 0.5;
112
+ c += lift * c * (1.0 - c);
113
+ c = mix(c, c * vec3(1.06, 0.97, 0.98), beauty.z * skin);
114
+ return clamp(c, 0.0, 1.0);
115
+ }
116
+
117
+ float personAt(vec3 center) {
118
+ float sum = 0.0;
119
+ float total = 0.0;
120
+ for (int y = -1; y <= 1; y++) {
121
+ for (int x = -1; x <= 1; x++) {
122
+ vec2 o = vec2(float(x), float(y)) * maskTexel * 1.5;
123
+ vec3 d = texture(frame, uv + o).rgb - center;
124
+ float w = exp(-dot(d, d) * 40.0);
125
+ sum += texture(mask, uv + o).r * w;
126
+ total += w;
127
+ }
128
+ }
129
+ return smoothstep(edge.x, edge.y, sum / total);
130
+ }
131
+
132
+ void main() {
133
+ vec3 original = texture(frame, uv).rgb;
134
+ vec3 fg = beautyOn > 0.5 ? beautify(original) : original;
135
+ if (mode == 0) {
136
+ color = vec4(fg, 1.0);
137
+ return;
138
+ }
139
+ float person = maskReady > 0.5 ? personAt(original) : 0.0;
140
+ vec3 bg;
141
+ if (mode == 1) {
142
+ vec4 b = texture(blurred, uv);
143
+ bg = b.a > 0.02 ? b.rgb / b.a : fg;
144
+ } else {
145
+ bg = texture(picture, uv * cover.xy + cover.zw).rgb;
146
+ }
147
+ color = vec4(mix(bg, fg, person), 1.0);
148
+ }`;
149
+
150
+ export interface RenderSettings {
151
+ mode: 'none' | 'blur' | 'image';
152
+ /** Gaussian sigma in quarter-size texels. */
153
+ blurSigma: number;
154
+ beauty: BeautySettings | null;
155
+ /** False until the first mask: everything is treated as background, so nothing behind the person shows meanwhile. */
156
+ maskReady: boolean;
157
+ /** Where the image texture maps (coverFit). */
158
+ cover: { sx: number; sy: number; ox: number; oy: number };
159
+ }
160
+
161
+ /** Where the person's edge ramps, in mask confidence. */
162
+ const EDGE: [number, number] = [0.35, 0.7];
163
+
164
+ type Program = { program: WebGLProgram; uniforms: Map<string, WebGLUniformLocation | null> };
165
+
166
+ export class EffectsRenderer {
167
+ readonly canvas: HTMLCanvasElement | OffscreenCanvas;
168
+ private readonly gl: WebGL2RenderingContext;
169
+ private readonly downsample: Program;
170
+ private readonly blur: Program;
171
+ private readonly composite: Program;
172
+ private readonly frameTexture: WebGLTexture;
173
+ private readonly maskTexture: WebGLTexture;
174
+ private readonly pictureTexture: WebGLTexture;
175
+ private readonly blurTextures: [WebGLTexture, WebGLTexture];
176
+ private readonly blurBuffers: [WebGLFramebuffer, WebGLFramebuffer];
177
+ private readonly vertices: WebGLBuffer;
178
+ private readonly floatTargets: boolean;
179
+ private width = 0;
180
+ private height = 0;
181
+ private blurWidth = 0;
182
+ private blurHeight = 0;
183
+ private maskWidth = 1;
184
+ private maskHeight = 1;
185
+ private pictureSize: { width: number; height: number } | null = null;
186
+
187
+ constructor(canvas: HTMLCanvasElement | OffscreenCanvas) {
188
+ this.canvas = canvas;
189
+ const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false, stencil: false, premultipliedAlpha: false, desynchronized: true }) as WebGL2RenderingContext | null;
190
+ if (!gl) throw new Error('WebGL2 is not available');
191
+ this.gl = gl;
192
+ this.floatTargets = gl.getExtension('EXT_color_buffer_float') !== null || gl.getExtension('EXT_color_buffer_half_float') !== null;
193
+ this.downsample = this.program(DOWNSAMPLE, ['frame', 'mask', 'maskReady', 'edge', 'flipY']);
194
+ this.blur = this.program(BLUR, ['source', 'direction', 'sigma', 'flipY']);
195
+ this.composite = this.program(COMPOSITE, ['frame', 'mask', 'blurred', 'picture', 'mode', 'maskReady', 'edge', 'texel', 'maskTexel', 'cover', 'beauty', 'beautyOn', 'beautyRadius', 'flipY']);
196
+ this.vertices = gl.createBuffer()!;
197
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertices);
198
+ // One triangle covering the viewport.
199
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
200
+ this.frameTexture = this.texture();
201
+ this.maskTexture = this.texture();
202
+ this.pictureTexture = this.texture();
203
+ this.blurTextures = [this.texture(), this.texture()];
204
+ this.blurBuffers = [gl.createFramebuffer()!, gl.createFramebuffer()!];
205
+ // Until a mask arrives: one texel, person nowhere.
206
+ gl.bindTexture(gl.TEXTURE_2D, this.maskTexture);
207
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
208
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, 1, 1, 0, gl.RED, gl.UNSIGNED_BYTE, new Uint8Array([0]));
209
+ gl.bindTexture(gl.TEXTURE_2D, this.pictureTexture);
210
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]));
211
+ }
212
+
213
+ get lost(): boolean {
214
+ return this.gl.isContextLost();
215
+ }
216
+
217
+ /** The picture's size; the canvas and the blur follow it. */
218
+ setSize(width: number, height: number): void {
219
+ if (width === this.width && height === this.height) return;
220
+ this.width = width;
221
+ this.height = height;
222
+ this.canvas.width = width;
223
+ this.canvas.height = height;
224
+ this.blurWidth = Math.max(1, Math.round(width / 4));
225
+ this.blurHeight = Math.max(1, Math.round(height / 4));
226
+ const gl = this.gl;
227
+ for (let i = 0; i < 2; i += 1) {
228
+ gl.bindTexture(gl.TEXTURE_2D, this.blurTextures[i]);
229
+ if (this.floatTargets) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, this.blurWidth, this.blurHeight, 0, gl.RGBA, gl.HALF_FLOAT, null);
230
+ else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.blurWidth, this.blurHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
231
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.blurBuffers[i]);
232
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.blurTextures[i], 0);
233
+ }
234
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
235
+ }
236
+
237
+ get size(): { width: number; height: number; blurHeight: number } {
238
+ return { width: this.width, height: this.height, blurHeight: this.blurHeight };
239
+ }
240
+
241
+ /** The camera frame (a VideoFrame or a playing video). */
242
+ uploadFrame(source: TexImageSource): void {
243
+ const gl = this.gl;
244
+ gl.bindTexture(gl.TEXTURE_2D, this.frameTexture);
245
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
246
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
247
+ }
248
+
249
+ /** The person mask, one byte per pixel, picture order. */
250
+ uploadMask(data: Uint8Array, width: number, height: number): void {
251
+ const gl = this.gl;
252
+ gl.bindTexture(gl.TEXTURE_2D, this.maskTexture);
253
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
254
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
255
+ this.maskWidth = width;
256
+ this.maskHeight = height;
257
+ }
258
+
259
+ /** The background picture, or null to let it go. */
260
+ setPicture(image: TexImageSource | null, width = 1, height = 1): void {
261
+ const gl = this.gl;
262
+ gl.bindTexture(gl.TEXTURE_2D, this.pictureTexture);
263
+ if (image) {
264
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
265
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
266
+ this.pictureSize = { width, height };
267
+ } else {
268
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]));
269
+ this.pictureSize = null;
270
+ }
271
+ }
272
+
273
+ get picture(): { width: number; height: number } | null {
274
+ return this.pictureSize;
275
+ }
276
+
277
+ /** Draw the finished picture onto the canvas. */
278
+ render(settings: RenderSettings): void {
279
+ const gl = this.gl;
280
+ if (gl.isContextLost() || this.width === 0) return;
281
+ gl.disable(gl.BLEND);
282
+ gl.disable(gl.DEPTH_TEST);
283
+ if (settings.mode === 'blur') {
284
+ gl.viewport(0, 0, this.blurWidth, this.blurHeight);
285
+ this.pass(this.downsample, this.blurBuffers[0], 0, (u) => {
286
+ this.bindTexture(0, this.frameTexture, u.get('frame'));
287
+ this.bindTexture(1, this.maskTexture, u.get('mask'));
288
+ gl.uniform1f(u.get('maskReady')!, settings.maskReady ? 1 : 0);
289
+ gl.uniform2f(u.get('edge')!, EDGE[0], EDGE[1]);
290
+ });
291
+ const sigma = Math.min(settings.blurSigma, 10.5);
292
+ this.pass(this.blur, this.blurBuffers[1], 0, (u) => {
293
+ this.bindTexture(0, this.blurTextures[0], u.get('source'));
294
+ gl.uniform2f(u.get('direction')!, 1 / this.blurWidth, 0);
295
+ gl.uniform1f(u.get('sigma')!, sigma);
296
+ });
297
+ this.pass(this.blur, this.blurBuffers[0], 0, (u) => {
298
+ this.bindTexture(0, this.blurTextures[1], u.get('source'));
299
+ gl.uniform2f(u.get('direction')!, 0, 1 / this.blurHeight);
300
+ gl.uniform1f(u.get('sigma')!, sigma);
301
+ });
302
+ }
303
+ gl.viewport(0, 0, this.width, this.height);
304
+ this.pass(this.composite, null, 1, (u) => {
305
+ this.bindTexture(0, this.frameTexture, u.get('frame'));
306
+ this.bindTexture(1, this.maskTexture, u.get('mask'));
307
+ this.bindTexture(2, this.blurTextures[0], u.get('blurred'));
308
+ this.bindTexture(3, this.pictureTexture, u.get('picture'));
309
+ gl.uniform1i(u.get('mode')!, settings.mode === 'blur' ? 1 : settings.mode === 'image' ? 2 : 0);
310
+ gl.uniform1f(u.get('maskReady')!, settings.maskReady ? 1 : 0);
311
+ gl.uniform2f(u.get('edge')!, EDGE[0], EDGE[1]);
312
+ gl.uniform2f(u.get('texel')!, 1 / this.width, 1 / this.height);
313
+ gl.uniform2f(u.get('maskTexel')!, 1 / this.maskWidth, 1 / this.maskHeight);
314
+ gl.uniform4f(u.get('cover')!, settings.cover.sx, settings.cover.sy, settings.cover.ox, settings.cover.oy);
315
+ const b = settings.beauty;
316
+ gl.uniform4f(u.get('beauty')!, b?.smooth ?? 0, b?.brighten ?? 0, b?.redness ?? 0, b?.sharpen ?? 0);
317
+ gl.uniform1f(u.get('beautyOn')!, b ? 1 : 0);
318
+ // About 3 px at 720p: the skin's pores and blemishes, not its features.
319
+ gl.uniform1f(u.get('beautyRadius')!, Math.max(1.5, this.height / 240));
320
+ });
321
+ }
322
+
323
+ /** Let the GPU resources go. */
324
+ dispose(): void {
325
+ const gl = this.gl;
326
+ for (const t of [this.frameTexture, this.maskTexture, this.pictureTexture, ...this.blurTextures]) gl.deleteTexture(t);
327
+ for (const f of this.blurBuffers) gl.deleteFramebuffer(f);
328
+ gl.deleteBuffer(this.vertices);
329
+ for (const p of [this.downsample, this.blur, this.composite]) gl.deleteProgram(p.program);
330
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
331
+ }
332
+
333
+ private pass(p: Program, target: WebGLFramebuffer | null, flipY: number, setup: (u: Map<string, WebGLUniformLocation | null>) => void): void {
334
+ const gl = this.gl;
335
+ gl.bindFramebuffer(gl.FRAMEBUFFER, target);
336
+ gl.useProgram(p.program);
337
+ gl.uniform1f(p.uniforms.get('flipY')!, flipY);
338
+ setup(p.uniforms);
339
+ const at = gl.getAttribLocation(p.program, 'position');
340
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertices);
341
+ gl.enableVertexAttribArray(at);
342
+ gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0);
343
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
344
+ }
345
+
346
+ private bindTexture(unit: number, texture: WebGLTexture, location: WebGLUniformLocation | null | undefined): void {
347
+ const gl = this.gl;
348
+ gl.activeTexture(gl.TEXTURE0 + unit);
349
+ gl.bindTexture(gl.TEXTURE_2D, texture);
350
+ if (location) gl.uniform1i(location, unit);
351
+ }
352
+
353
+ private texture(): WebGLTexture {
354
+ const gl = this.gl;
355
+ const t = gl.createTexture()!;
356
+ gl.bindTexture(gl.TEXTURE_2D, t);
357
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
358
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
359
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
360
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
361
+ return t;
362
+ }
363
+
364
+ private program(fragment: string, names: string[]): Program {
365
+ const gl = this.gl;
366
+ const compile = (type: number, source: string): WebGLShader => {
367
+ const shader = gl.createShader(type)!;
368
+ gl.shaderSource(shader, source);
369
+ gl.compileShader(shader);
370
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) {
371
+ throw new Error(`video effects: a shader did not compile: ${gl.getShaderInfoLog(shader)}`);
372
+ }
373
+ return shader;
374
+ };
375
+ const program = gl.createProgram()!;
376
+ gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));
377
+ gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fragment));
378
+ gl.linkProgram(program);
379
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS) && !gl.isContextLost()) {
380
+ throw new Error(`video effects: a shader did not link: ${gl.getProgramInfoLog(program)}`);
381
+ }
382
+ return { program, uniforms: new Map(names.map((n) => [n, gl.getUniformLocation(program, n)])) };
383
+ }
384
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Audio-only fallback (docs/implementation-progress/RTC_PERF_PROGRESS.md H1).
3
+ *
4
+ * When this viewer's connection is so poor that even the sound breaks up, remote camera videos are paused at the
5
+ * server so what bandwidth there is goes to the audio, and they come back once the connection has recovered.
6
+ *
7
+ * - Agora's `setStreamFallbackOption(uid, AUDIO_ONLY)` drops to the low stream and then to audio only, and reports
8
+ * `stream-fallback` (fallback / recover).
9
+ * - Amazon Chime watches the audio it receives (`UnusableAudioWarningConnectionHealthPolicy`): about half of the
10
+ * expected packets missing over 15 one-second samples suggests stopping video, with a 60 s cool-down.
11
+ *
12
+ * This follows Chime's signal -- the audio actually received -- measured as RTP loss (sequence gaps) rather than
13
+ * packet counts, because Opus DTX sends almost nothing during silence and a count would read silence as loss.
14
+ * Extreme only: {@link FALLBACK_LOSS} of the audio lost over {@link FALLBACK_SAMPLES} samples, with at least
15
+ * {@link MIN_PACKETS} packets to judge by. Back after a hold ({@link FIRST_HOLD_MS}, doubled for each relapse within
16
+ * {@link RELAPSE_MS}, up to {@link MAX_HOLD_MS}) once the loss is under {@link RECOVER_LOSS} -- or nobody spoke
17
+ * enough to tell, in which case video comes back and a still-bad connection falls back again, holding longer.
18
+ *
19
+ * The SFU cutting a video for bandwidth by itself is reported separately, by the server (`reason: 'bandwidth'`).
20
+ * Pure: the decisions take counters and a clock.
21
+ */
22
+ import type { StatsEntry } from './stats.js';
23
+
24
+ /** How often the received audio is sampled while the fallback could be needed. */
25
+ export const PROTECT_SAMPLE_MS = 3000;
26
+ /** This share of the audio lost (RTP sequence gaps) over the window: fall back. */
27
+ export const FALLBACK_LOSS = 0.25;
28
+ /** Below this share lost over the recovery window: video may come back. */
29
+ export const RECOVER_LOSS = 0.05;
30
+ /** Samples judged for falling back (15 s at 3 s) -- at least 3 of them. */
31
+ export const FALLBACK_SAMPLES = 5;
32
+ /** Samples judged for coming back (12 s). */
33
+ export const RECOVER_SAMPLES = 4;
34
+ /** Fewer audio packets than this over the fallback window are too few to judge. */
35
+ export const MIN_PACKETS = 150;
36
+ /** Fewer than this over the recovery window: nobody spoke enough to tell. */
37
+ export const MIN_RECOVER_PACKETS = 30;
38
+ /** The first fallback lasts at least this long. */
39
+ export const FIRST_HOLD_MS = 20_000;
40
+ /** A relapse doubles the hold, up to this. */
41
+ export const MAX_HOLD_MS = 160_000;
42
+ /** Falling back again within this long of coming back is a relapse. */
43
+ export const RELAPSE_MS = 120_000;
44
+
45
+ export interface AudioCounters {
46
+ received: number;
47
+ lost: number;
48
+ }
49
+
50
+ const num = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0);
51
+
52
+ /** The received-audio counters of a receive transport's report, summed over its audio streams. */
53
+ export function readInboundAudio(report: Iterable<StatsEntry>): AudioCounters {
54
+ let received = 0;
55
+ let lost = 0;
56
+ for (const e of report) {
57
+ if (typeof e !== 'object' || e === null || e.type !== 'inbound-rtp') continue;
58
+ if (e.kind !== 'audio' && e.mediaType !== 'audio') continue;
59
+ received += num(e.packetsReceived);
60
+ lost += Math.max(0, num(e.packetsLost));
61
+ }
62
+ return { received, lost };
63
+ }
64
+
65
+ /**
66
+ * The sent-audio counters of a send transport's report: packets sent, and how many of them the server reported
67
+ * lost (its RTCP receiver reports). For the publisher side (Agora's setLocalPublishFallbackOption): `received` is what
68
+ * got through.
69
+ */
70
+ export function readOutboundAudio(report: Iterable<StatsEntry>): AudioCounters {
71
+ let sent = 0;
72
+ let lost = 0;
73
+ for (const e of report) {
74
+ if (typeof e !== 'object' || e === null) continue;
75
+ const audio = e.kind === 'audio' || e.mediaType === 'audio';
76
+ if (!audio) continue;
77
+ if (e.type === 'outbound-rtp') sent += num(e.packetsSent);
78
+ else if (e.type === 'remote-inbound-rtp') lost += Math.max(0, num(e.packetsLost));
79
+ }
80
+ return { received: Math.max(0, sent - lost), lost };
81
+ }
82
+
83
+ /** Decides when to fall back to audio only and when video may come back. */
84
+ export class AudioProtection {
85
+ private samples: AudioCounters[] = [];
86
+ private previous: AudioCounters | null = null;
87
+ private activeSince: number | null = null;
88
+ private hold = FIRST_HOLD_MS;
89
+ private recoveredAt: number | null = null;
90
+
91
+ constructor(
92
+ private readonly onChange: (active: boolean) => void,
93
+ private readonly now: () => number = Date.now,
94
+ ) {}
95
+
96
+ /** Whether remote camera videos are held back now. */
97
+ get active(): boolean {
98
+ return this.activeSince !== null;
99
+ }
100
+
101
+ /** How long the current (or next first) fallback holds, in ms. */
102
+ get holdMs(): number {
103
+ return this.hold;
104
+ }
105
+
106
+ /**
107
+ * One reading of the cumulative counters. They only go up on one transport; lower ones are a new transport, and
108
+ * judging starts over from them.
109
+ */
110
+ feed(counters: AudioCounters): void {
111
+ const before = this.previous;
112
+ this.previous = counters;
113
+ if (before === null || counters.received < before.received || counters.lost < before.lost) {
114
+ this.samples = [];
115
+ return;
116
+ }
117
+ this.samples.push({ received: counters.received - before.received, lost: counters.lost - before.lost });
118
+ if (this.samples.length > Math.max(FALLBACK_SAMPLES, RECOVER_SAMPLES)) this.samples.shift();
119
+
120
+ if (this.activeSince === null) {
121
+ const window = this.samples.slice(-FALLBACK_SAMPLES);
122
+ if (window.length < 3) return;
123
+ const { total, lost } = sum(window);
124
+ if (total >= MIN_PACKETS && lost / total >= FALLBACK_LOSS) this.activate();
125
+ return;
126
+ }
127
+ if (this.now() - this.activeSince < this.hold || this.samples.length < RECOVER_SAMPLES) return;
128
+ const { total, lost } = sum(this.samples.slice(-RECOVER_SAMPLES));
129
+ if (total < MIN_RECOVER_PACKETS || lost / total < RECOVER_LOSS) this.recover();
130
+ }
131
+
132
+ /** Come back now (the app turned the fallback off). */
133
+ release(): void {
134
+ if (this.activeSince !== null) this.recover();
135
+ }
136
+
137
+ /** The transports went away (reconnect, close): forget everything, without telling. */
138
+ reset(): void {
139
+ this.activeSince = null;
140
+ this.samples = [];
141
+ this.previous = null;
142
+ }
143
+
144
+ private activate(): void {
145
+ const now = this.now();
146
+ const relapse = this.recoveredAt !== null && now - this.recoveredAt < RELAPSE_MS;
147
+ this.hold = relapse ? Math.min(this.hold * 2, MAX_HOLD_MS) : FIRST_HOLD_MS;
148
+ this.activeSince = now;
149
+ this.samples = [];
150
+ this.onChange(true);
151
+ }
152
+
153
+ private recover(): void {
154
+ this.activeSince = null;
155
+ this.recoveredAt = this.now();
156
+ this.samples = [];
157
+ this.onChange(false);
158
+ }
159
+ }
160
+
161
+ function sum(samples: readonly AudioCounters[]): { total: number; lost: number } {
162
+ let total = 0;
163
+ let lost = 0;
164
+ for (const s of samples) {
165
+ total += s.received + s.lost;
166
+ lost += s.lost;
167
+ }
168
+ return { total, lost };
169
+ }
package/src/health.ts ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Media health warnings (docs/implementation-progress/RTC_PERF_PROGRESS.md K1).
3
+ *
4
+ * - Agora's `exception` event pairs each problem with its recovery: FRAMERATE_INPUT_TOO_LOW / _RECOVER (the camera
5
+ * delivers too few frames), AUDIO_INPUT_LEVEL_TOO_LOW / _RECOVER, ...
6
+ * - LiveKit's `AudioSilenceDetected`: a microphone that delivers nothing but silence (a hardware mute switch, a
7
+ * broken device) right after it starts.
8
+ * - LiveKit watches the track's `mute` event (the OS took the device: a phone call, another app) and reacts after 5 s.
9
+ *
10
+ * Each warning is reported once when it starts (`active: true`) and once when it clears (`active: false`).
11
+ * Pure: the decisions take samples.
12
+ */
13
+
14
+ export type MediaWarningCode =
15
+ /** The microphone is on but delivers exact digital silence: a mute switch, a broken or wrongly chosen device. */
16
+ | 'mic-silent'
17
+ /** The camera delivers far fewer frames than asked: usually a dark room (the camera exposes longer), or a busy device. */
18
+ | 'camera-fps-low'
19
+ /** The system took the camera from this page for now (a phone call, another app, a locked screen). */
20
+ | 'camera-interrupted'
21
+ /** The system took the microphone (a phone call, another app). */
22
+ | 'mic-interrupted';
23
+
24
+ export interface MediaWarning {
25
+ code: MediaWarningCode;
26
+ /** true when it starts, false when it clears. */
27
+ active: boolean;
28
+ }
29
+
30
+ /** How often the published camera and microphone are sampled while someone listens. */
31
+ export const HEALTH_SAMPLE_MS = 2000;
32
+ /** Samples of exact silence before mic-silent (6 s). */
33
+ export const SILENT_SAMPLES = 3;
34
+ /** Below this the level counts as exact digital silence (a real room's noise floor is well above it). */
35
+ export const SILENCE_LEVEL = 0.0001;
36
+ /** Fewer frames than this per second, when 24 or more were asked, is camera-fps-low. */
37
+ export const LOW_FPS = 15;
38
+ /** Samples below LOW_FPS before warning (6 s); samples at RECOVERED_FPS or more before clearing. */
39
+ export const LOW_FPS_SAMPLES = 3;
40
+ export const RECOVERED_FPS = 20;
41
+ export const RECOVER_SAMPLES = 2;
42
+ /** A system mute shorter than this is a glitch, not an interruption. */
43
+ export const INTERRUPTED_AFTER_MS = 2000;
44
+
45
+ /** One reading of the published devices. null: not published (or nothing measured). */
46
+ export interface HealthSample {
47
+ /** The microphone's level, while it is on. */
48
+ micLevel: number | null;
49
+ /** The frames per second the camera delivers, while it is on, and what was asked. */
50
+ cameraFps: number | null;
51
+ askedFps: number;
52
+ }
53
+
54
+ /** Decides mic-silent and camera-fps-low from samples. */
55
+ export class HealthDecisions {
56
+ private silent = 0;
57
+ private lowFps = 0;
58
+ private goodFps = 0;
59
+ private readonly activeNow = new Set<MediaWarningCode>();
60
+
61
+ constructor(private readonly report: (warning: MediaWarning) => void) {}
62
+
63
+ isActive(code: MediaWarningCode): boolean {
64
+ return this.activeNow.has(code);
65
+ }
66
+
67
+ feed(sample: HealthSample): void {
68
+ // mic-silent: exact silence held; any sound clears it. Off or unpublished: not a warning.
69
+ if (sample.micLevel === null) {
70
+ this.silent = 0;
71
+ this.set('mic-silent', false);
72
+ } else if (sample.micLevel <= SILENCE_LEVEL) {
73
+ this.silent += 1;
74
+ if (this.silent >= SILENT_SAMPLES) this.set('mic-silent', true);
75
+ } else {
76
+ this.silent = 0;
77
+ this.set('mic-silent', false);
78
+ }
79
+
80
+ // camera-fps-low: only when a smooth rate was asked; cleared once it holds again.
81
+ if (sample.cameraFps === null || sample.askedFps < 24) {
82
+ this.lowFps = 0;
83
+ this.goodFps = 0;
84
+ this.set('camera-fps-low', false);
85
+ } else if (sample.cameraFps < LOW_FPS) {
86
+ this.goodFps = 0;
87
+ this.lowFps += 1;
88
+ if (this.lowFps >= LOW_FPS_SAMPLES) this.set('camera-fps-low', true);
89
+ } else {
90
+ this.lowFps = 0;
91
+ if (sample.cameraFps >= RECOVERED_FPS) this.goodFps += 1;
92
+ if (this.goodFps >= RECOVER_SAMPLES) this.set('camera-fps-low', false);
93
+ }
94
+ }
95
+
96
+ /** A system interruption started or ended (decided by the caller's timer). */
97
+ interrupted(code: 'camera-interrupted' | 'mic-interrupted', active: boolean): void {
98
+ this.set(code, active);
99
+ }
100
+
101
+ /** Everything clears (unpublished, closed): each active warning is reported cleared. */
102
+ clearAll(): void {
103
+ for (const code of [...this.activeNow]) this.set(code, false);
104
+ this.silent = 0;
105
+ this.lowFps = 0;
106
+ this.goodFps = 0;
107
+ }
108
+
109
+ private set(code: MediaWarningCode, active: boolean): void {
110
+ if (this.activeNow.has(code) === active) return;
111
+ if (active) this.activeNow.add(code);
112
+ else this.activeNow.delete(code);
113
+ this.report({ code, active });
114
+ }
115
+ }
116
+
117
+ /** The microphone level and camera frame rate from a producer's statistics (media-source). */
118
+ export function readMediaSource(report: Iterable<Record<string, unknown>>): { level: number | null; fps: number | null } {
119
+ let level: number | null = null;
120
+ let fps: number | null = null;
121
+ for (const s of report) {
122
+ if (s.type !== 'media-source') continue;
123
+ if (typeof s.audioLevel === 'number') level = s.audioLevel;
124
+ if (typeof s.framesPerSecond === 'number') fps = s.framesPerSecond;
125
+ }
126
+ return { level, fps };
127
+ }