mediascale-sdk 1.0.13 → 1.0.15

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.
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Gradient specs shared by the recording / RTMP canvas and the host app's own view.
3
+ *
4
+ * Accepted inputs (all structured-clone safe, so they can be posted to the worker):
5
+ * "#0A0036" plain color (legacy glow backdrop for the stage)
6
+ * "linear-gradient(135deg, #1e1b4b 0%, #0f172a 100%)" CSS syntax (angle / `to right` / `to top left` …)
7
+ * "radial-gradient(circle at 30% 20%, #6d28d9, #0b0620 70%)"
8
+ * { type: "linear", angle: 135, stops: ["#1e1b4b", "#0f172a"] }
9
+ * { type: "radial", shape: "ellipse", at: [50, 50], stops: [{ color: "#6d28d9", offset: 0 }, …] }
10
+ * { type: "solid", color: "#111827" }
11
+ *
12
+ * Canvas geometry follows CSS, so passing the same string to a DOM `background` and to the
13
+ * SDK renders the same picture.
14
+ */
15
+
16
+ const SIDE_KEYWORDS = { top: [0, -1], bottom: [0, 1], left: [-1, 0], right: [1, 0] };
17
+ const POSITION_KEYWORDS = { left: 0, top: 0, center: 50, right: 100, bottom: 100 };
18
+ const RADIAL_SIZES = new Set(["closest-side", "closest-corner", "farthest-side", "farthest-corner"]);
19
+ const MAX_STOPS = 16;
20
+
21
+ /** Split on top-level commas (ignores commas inside rgb(...) etc.). */
22
+ function splitTopLevel(text, separator = ",") {
23
+ const parts = [];
24
+ let depth = 0;
25
+ let current = "";
26
+ for (const ch of text) {
27
+ if (ch === "(") depth += 1;
28
+ else if (ch === ")") depth = Math.max(0, depth - 1);
29
+ if (depth === 0 && (separator === " " ? /\s/.test(ch) : ch === separator)) {
30
+ if (current.trim()) parts.push(current.trim());
31
+ current = "";
32
+ continue;
33
+ }
34
+ current += ch;
35
+ }
36
+ if (current.trim()) parts.push(current.trim());
37
+ return parts;
38
+ }
39
+
40
+ function parseAngle(token) {
41
+ const match = String(token).trim().match(/^(-?[\d.]+)(deg|turn|rad|grad)$/i);
42
+ if (!match) return null;
43
+ const n = Number(match[1]);
44
+ if (!Number.isFinite(n)) return null;
45
+ const unit = match[2].toLowerCase();
46
+ if (unit === "turn") return n * 360;
47
+ if (unit === "rad") return (n * 180) / Math.PI;
48
+ if (unit === "grad") return n * 0.9;
49
+ return n;
50
+ }
51
+
52
+ function parseStop(raw) {
53
+ if (typeof raw === "string") {
54
+ const tokens = splitTopLevel(raw, " ");
55
+ let offset = null;
56
+ if (tokens.length > 1 && /^-?[\d.]+%$/.test(tokens[tokens.length - 1])) {
57
+ offset = Number(tokens.pop().slice(0, -1)) / 100;
58
+ }
59
+ // A second position ("red 10% 20%") or px lengths are dropped; the color stays.
60
+ while (tokens.length > 1 && /^-?[\d.]+(%|px)?$/.test(tokens[tokens.length - 1])) tokens.pop();
61
+ const color = tokens.join(" ").trim();
62
+ return color ? { color, offset } : null;
63
+ }
64
+ if (raw && typeof raw === "object" && raw.color) {
65
+ const n = Number(raw.offset ?? raw.position);
66
+ let offset = Number.isFinite(n) ? n : null;
67
+ if (offset != null && offset > 1) offset /= 100; // 0–100 accepted too
68
+ return { color: String(raw.color).trim(), offset };
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** CSS rules: first stop defaults to 0, last to 1, gaps interpolate, offsets never go backwards. */
74
+ function resolveStops(rawStops) {
75
+ const stops = (Array.isArray(rawStops) ? rawStops : []).map(parseStop).filter(Boolean).slice(0, MAX_STOPS);
76
+ if (!stops.length) return null;
77
+ if (stops.length === 1) stops.push({ ...stops[0], offset: null });
78
+ if (stops[0].offset == null) stops[0].offset = 0;
79
+ if (stops[stops.length - 1].offset == null) stops[stops.length - 1].offset = 1;
80
+ let last = 0;
81
+ for (let i = 0; i < stops.length; i += 1) {
82
+ if (stops[i].offset == null) {
83
+ let j = i;
84
+ while (stops[j].offset == null) j += 1;
85
+ const from = stops[i - 1].offset;
86
+ const step = (stops[j].offset - from) / (j - i + 1);
87
+ for (let k = i; k < j; k += 1) stops[k].offset = from + step * (k - i + 1);
88
+ }
89
+ stops[i].offset = Math.min(1, Math.max(last, stops[i].offset));
90
+ last = stops[i].offset;
91
+ }
92
+ return stops.map(({ color, offset }) => ({ color, offset }));
93
+ }
94
+
95
+ function parseLinearHead(head) {
96
+ const angle = parseAngle(head);
97
+ if (angle != null) return { angle };
98
+ const to = String(head).trim().toLowerCase().match(/^to\s+(.+)$/);
99
+ if (!to) return null;
100
+ let dx = 0;
101
+ let dy = 0;
102
+ for (const word of to[1].split(/\s+/)) {
103
+ const side = SIDE_KEYWORDS[word];
104
+ if (!side) return null;
105
+ dx += side[0];
106
+ dy += side[1];
107
+ }
108
+ return { to: [Math.sign(dx), Math.sign(dy)] };
109
+ }
110
+
111
+ function parsePosition(text) {
112
+ const tokens = String(text || "").trim().toLowerCase().split(/\s+/).filter(Boolean);
113
+ const values = [];
114
+ let x = null;
115
+ let y = null;
116
+ for (const token of tokens) {
117
+ if (token === "left" || token === "right") x = POSITION_KEYWORDS[token];
118
+ else if (token === "top" || token === "bottom") y = POSITION_KEYWORDS[token];
119
+ else if (token === "center") values.push(50);
120
+ else if (/^-?[\d.]+%$/.test(token)) values.push(Number(token.slice(0, -1)));
121
+ }
122
+ if (x == null) x = values.length ? values.shift() : 50;
123
+ if (y == null) y = values.length ? values.shift() : 50;
124
+ return [x, y];
125
+ }
126
+
127
+ function parseRadialHead(head) {
128
+ const text = String(head).trim().toLowerCase();
129
+ if (!/(circle|ellipse|closest|farthest|\bat\b)/.test(text)) return null;
130
+ const [shapePart, atPart] = text.split(/\bat\b/);
131
+ const words = shapePart.trim().split(/\s+/).filter(Boolean);
132
+ return {
133
+ shape: words.includes("circle") ? "circle" : "ellipse",
134
+ size: words.find((word) => RADIAL_SIZES.has(word)) || "farthest-corner",
135
+ at: atPart != null ? parsePosition(atPart) : [50, 50],
136
+ };
137
+ }
138
+
139
+ function parseCss(text) {
140
+ const match = text.match(/^(repeating-)?(linear|radial)-gradient\(([\s\S]*)\)$/i);
141
+ if (!match || match[1]) return null;
142
+ const type = match[2].toLowerCase();
143
+ const args = splitTopLevel(match[3]);
144
+ if (!args.length) return null;
145
+ if (type === "linear") {
146
+ const head = parseLinearHead(args[0]);
147
+ const stops = resolveStops(head ? args.slice(1) : args);
148
+ if (!stops) return null;
149
+ return { type, angle: head?.angle ?? 180, to: head?.to || null, stops };
150
+ }
151
+ const head = parseRadialHead(args[0]);
152
+ const stops = resolveStops(head ? args.slice(1) : args);
153
+ if (!stops) return null;
154
+ return { type, shape: head?.shape || "ellipse", size: head?.size || "farthest-corner", at: head?.at || [50, 50], stops };
155
+ }
156
+
157
+ /**
158
+ * Normalize any accepted input. Returns null when it is empty / not understood.
159
+ * `{ type: "color" }` marks a plain color (the stage keeps its legacy glow look for it).
160
+ */
161
+ export function normalizeGradient(input) {
162
+ if (input == null || input === "") return null;
163
+ if (typeof input === "string") {
164
+ const text = input.trim();
165
+ if (!text) return null;
166
+ if (/gradient\(/i.test(text)) return parseCss(text);
167
+ return { type: "color", color: text };
168
+ }
169
+ if (typeof input !== "object") return null;
170
+ if (input.css) return normalizeGradient(String(input.css));
171
+ const type = String(input.type || "linear").toLowerCase();
172
+ if (type === "solid" || type === "color") {
173
+ const color = String(input.color || "").trim();
174
+ return color ? { type: type === "solid" ? "solid" : "color", color } : null;
175
+ }
176
+ const stops = resolveStops(input.stops || input.colors);
177
+ if (!stops) return null;
178
+ if (type === "radial") {
179
+ const at = Array.isArray(input.at) ? input.at : (typeof input.at === "string" ? parsePosition(input.at) : [50, 50]);
180
+ return {
181
+ type,
182
+ shape: input.shape === "circle" ? "circle" : "ellipse",
183
+ size: RADIAL_SIZES.has(input.size) ? input.size : "farthest-corner",
184
+ at: [Number(at[0]) || 0, Number(at[1]) || 0],
185
+ stops,
186
+ };
187
+ }
188
+ if (type !== "linear") return null;
189
+ const head = typeof input.direction === "string" ? parseLinearHead(input.direction) : null;
190
+ const angle = Number(input.angle);
191
+ return { type: "linear", angle: Number.isFinite(angle) ? angle : (head?.angle ?? 180), to: head?.to || null, stops };
192
+ }
193
+
194
+ /** CSS `background` value for a gradient input, for the host app's own DOM view. */
195
+ export function gradientToCss(input) {
196
+ const spec = normalizeGradient(input);
197
+ if (!spec) return "";
198
+ if (spec.type === "color" || spec.type === "solid") return spec.color;
199
+ const stops = spec.stops.map((stop) => `${stop.color} ${Math.round(stop.offset * 1000) / 10}%`).join(", ");
200
+ if (spec.type === "linear") {
201
+ const head = spec.to
202
+ ? `to ${[spec.to[1] < 0 ? "top" : spec.to[1] > 0 ? "bottom" : "", spec.to[0] < 0 ? "left" : spec.to[0] > 0 ? "right" : ""].filter(Boolean).join(" ")}`
203
+ : `${spec.angle}deg`;
204
+ return `linear-gradient(${head}, ${stops})`;
205
+ }
206
+ return `radial-gradient(${spec.shape} ${spec.size} at ${spec.at[0]}% ${spec.at[1]}%, ${stops})`;
207
+ }
208
+
209
+ function addStops(gradient, stops) {
210
+ for (const stop of stops) gradient.addColorStop(stop.offset, stop.color);
211
+ }
212
+
213
+ function linearAngle(spec, w, h) {
214
+ if (!spec.to) return (spec.angle * Math.PI) / 180;
215
+ const [sx, sy] = spec.to;
216
+ // Corners (CSS "magic corners"): the 50% line runs through the two other corners.
217
+ const dx = sx && sy ? sx * h : sx;
218
+ const dy = sx && sy ? sy * w : sy;
219
+ return Math.atan2(dx, -dy);
220
+ }
221
+
222
+ function radialRadii(spec, w, h) {
223
+ const cx = (spec.at[0] / 100) * w;
224
+ const cy = (spec.at[1] / 100) * h;
225
+ const sideX = [Math.abs(cx), Math.abs(w - cx)];
226
+ const sideY = [Math.abs(cy), Math.abs(h - cy)];
227
+ const closeX = Math.min(...sideX);
228
+ const closeY = Math.min(...sideY);
229
+ const farX = Math.max(...sideX);
230
+ const farY = Math.max(...sideY);
231
+ if (spec.shape === "circle") {
232
+ if (spec.size === "closest-side") return [Math.min(closeX, closeY), Math.min(closeX, closeY)];
233
+ if (spec.size === "farthest-side") return [Math.max(farX, farY), Math.max(farX, farY)];
234
+ const r = spec.size === "closest-corner" ? Math.hypot(closeX, closeY) : Math.hypot(farX, farY);
235
+ return [r, r];
236
+ }
237
+ if (spec.size === "closest-side") return [closeX, closeY];
238
+ if (spec.size === "farthest-side") return [farX, farY];
239
+ // Ellipse through a corner keeps the side ratio: radius = side · √2.
240
+ return spec.size === "closest-corner" ? [closeX * Math.SQRT2, closeY * Math.SQRT2] : [farX * Math.SQRT2, farY * Math.SQRT2];
241
+ }
242
+
243
+ /**
244
+ * Fill a rect with a normalized gradient spec. Returns false when nothing was drawn
245
+ * (invalid color, unknown spec) so callers can fall back.
246
+ */
247
+ export function fillGradient(ctx, x, y, w, h, spec) {
248
+ if (!spec || w <= 0 || h <= 0) return false;
249
+ try {
250
+ if (spec.type === "color" || spec.type === "solid") {
251
+ ctx.fillStyle = spec.color;
252
+ ctx.fillRect(x, y, w, h);
253
+ return true;
254
+ }
255
+ if (spec.type === "linear") {
256
+ const a = linearAngle(spec, w, h);
257
+ const dirX = Math.sin(a);
258
+ const dirY = -Math.cos(a);
259
+ const half = (Math.abs(w * dirX) + Math.abs(h * dirY)) / 2;
260
+ const cx = x + w / 2;
261
+ const cy = y + h / 2;
262
+ const gradient = ctx.createLinearGradient(cx - dirX * half, cy - dirY * half, cx + dirX * half, cy + dirY * half);
263
+ addStops(gradient, spec.stops);
264
+ ctx.fillStyle = gradient;
265
+ ctx.fillRect(x, y, w, h);
266
+ return true;
267
+ }
268
+ if (spec.type === "radial") {
269
+ const [rx, ry] = radialRadii(spec, w, h);
270
+ const r = Math.max(rx, 0.5);
271
+ const ratio = Math.max(ry, 0.5) / r;
272
+ const cx = x + (spec.at[0] / 100) * w;
273
+ const cy = y + (spec.at[1] / 100) * h;
274
+ ctx.save();
275
+ ctx.translate(cx, cy);
276
+ ctx.scale(1, ratio);
277
+ const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, r);
278
+ addStops(gradient, spec.stops);
279
+ ctx.fillStyle = gradient;
280
+ ctx.fillRect(x - cx, (y - cy) / ratio, w, h / ratio);
281
+ ctx.restore();
282
+ return true;
283
+ }
284
+ } catch {
285
+ // Invalid color string in a stop: caller falls back to the default look.
286
+ }
287
+ return false;
288
+ }
289
+
290
+ function hashName(name) {
291
+ const s = String(name || "").trim().toLowerCase();
292
+ let hash = 0;
293
+ for (let i = 0; i < s.length; i += 1) hash = (hash * 31 + s.charCodeAt(i)) >>> 0;
294
+ return hash;
295
+ }
296
+
297
+ /** Default camera-off tile gradients (same name → same tone). */
298
+ export const DEFAULT_AVATAR_BACKGROUNDS = [
299
+ "radial-gradient(circle at 50% 50%, #c430a8 0%, #8a2276 55%, #3a0a46 100%)", // magenta
300
+ "radial-gradient(circle at 50% 50%, #6e5fc8 0%, #4f4490 55%, #1e1850 100%)", // indigo
301
+ "radial-gradient(circle at 50% 50%, #b4a546 0%, #827732 55%, #373212 100%)", // olive
302
+ "radial-gradient(circle at 50% 50%, #aa2d46 0%, #7a2032 55%, #370c1c 100%)", // burgundy
303
+ "radial-gradient(circle at 50% 50%, #328c96 0%, #24656c 55%, #0f2d37 100%)", // teal
304
+ "radial-gradient(circle at 50% 50%, #c86e32 0%, #904f24 55%, #3c1e0f 100%)", // amber
305
+ ];
306
+
307
+ /**
308
+ * Pick the camera-off gradient for a participant: one spec for everyone, or a list
309
+ * indexed by a stable name hash. Use the same call in your UI to match the recording.
310
+ */
311
+ export function avatarBackgroundFor(name, avatarBackground = null) {
312
+ const list = Array.isArray(avatarBackground)
313
+ ? avatarBackground.filter((item) => normalizeGradient(item))
314
+ : (normalizeGradient(avatarBackground) ? [avatarBackground] : DEFAULT_AVATAR_BACKGROUNDS);
315
+ const pool = list.length ? list : DEFAULT_AVATAR_BACKGROUNDS;
316
+ return pool[hashName(name) % pool.length];
317
+ }
package/src/index.js CHANGED
@@ -1,4 +1,18 @@
1
1
  export { createClient } from "./client.js";
2
2
  export { FrameCompositor } from "./record-frame-compositor.js";
3
3
  export { DEFAULT_RECORDING_FPS } from "./record.js";
4
- export { DEFAULT_RTMP_FPS, DEFAULT_RTMP_BITRATE } from "./live.js";
4
+ export {
5
+ avatarBackgroundFor,
6
+ gradientToCss,
7
+ normalizeGradient,
8
+ DEFAULT_AVATAR_BACKGROUNDS,
9
+ } from "./gradient.js";
10
+ export {
11
+ DEFAULT_RTMP_FPS,
12
+ DEFAULT_RTMP_BITRATE,
13
+ DEFAULT_RTMP_RESOLUTION,
14
+ DEFAULT_RTMP_KEYFRAME_INTERVAL,
15
+ MAX_RTMP_BITRATE,
16
+ RTMP_RESOLUTIONS,
17
+ normalizeRtmpResolution,
18
+ } from "./live.js";
package/src/live.js CHANGED
@@ -1,9 +1,74 @@
1
- import { CanvasRecorder, clampFps } from "./record.js";
1
+ import { CanvasRecorder, clampFps, stageOutputSize } from "./record.js";
2
2
 
3
3
  /** Default live (RTMP) frame rate. Override with createClient({ rtmpFps }). */
4
4
  export const DEFAULT_RTMP_FPS = 30;
5
+ /** Hard cap for the live (RTMP) video bitrate: 2500 kbps. */
6
+ export const MAX_RTMP_BITRATE = 2_500_000;
7
+ export const MIN_RTMP_BITRATE = 300_000;
5
8
  /** Default live (RTMP) video bitrate in bps. Override with createClient({ rtmpBitrate }). */
6
- export const DEFAULT_RTMP_BITRATE = 2_500_000;
9
+ export const DEFAULT_RTMP_BITRATE = MAX_RTMP_BITRATE;
10
+ /** Named live output presets (16:9). Any custom `WxH` works too — see normalizeRtmpResolution. */
11
+ export const RTMP_RESOLUTIONS = {
12
+ "480p": { width: 854, height: 480 },
13
+ "540p": { width: 960, height: 540 },
14
+ "720p": { width: 1280, height: 720 },
15
+ "1080p": { width: 1920, height: 1080 },
16
+ };
17
+ /** 1080p keeps screen-share text sharp; 2.5 Mbps is enough because shared screens are mostly static. */
18
+ export const DEFAULT_RTMP_RESOLUTION = "1080p";
19
+ /** Keyframe (GOP) interval in seconds. Platforms want 2 s (YouTube accepts up to 4 s). */
20
+ export const DEFAULT_RTMP_KEYFRAME_INTERVAL = 2;
21
+ const MIN_RTMP_KEYFRAME_INTERVAL = 1;
22
+ const MAX_RTMP_KEYFRAME_INTERVAL = 10;
23
+
24
+ /**
25
+ * Resolve any resolution input to an encodable size:
26
+ * "1080p" / "720p" (presets), "1600x900" / "1080x1920" (custom, portrait ok),
27
+ * 720 / "720" (height, 16:9), { width, height }.
28
+ * The aspect ratio is kept; size is clamped to ≤ 1920 on the long edge and ≤ 1920×1080
29
+ * pixels so the browser compositor + encoder stay light. Returns { width, height, label }.
30
+ */
31
+ export function normalizeRtmpResolution(value, fallback = DEFAULT_RTMP_RESOLUTION) {
32
+ const fromFallback = () => (fallback && typeof fallback === "object" && fallback.width
33
+ ? fallback
34
+ : normalizeRtmpResolution(RTMP_RESOLUTIONS[fallback] ? fallback : DEFAULT_RTMP_RESOLUTION, null));
35
+ if (value == null || value === "") return fromFallback();
36
+ let size = null;
37
+ if (typeof value === "object") {
38
+ const width = Number(value.width);
39
+ const height = Number(value.height);
40
+ if (height > 0) size = width > 0 ? { width, height } : { height };
41
+ } else {
42
+ const text = String(value).trim().toLowerCase();
43
+ const preset = RTMP_RESOLUTIONS[text];
44
+ const custom = text.match(/^(\d{2,5})\s*[x×*:]\s*(\d{2,5})$/);
45
+ const height = text.match(/^(\d{2,5})p?$/);
46
+ if (preset) size = { ...preset };
47
+ else if (custom) size = { width: Number(custom[1]), height: Number(custom[2]) };
48
+ else if (height) size = { height: Number(height[1]) };
49
+ }
50
+ if (!size) return fromFallback();
51
+ const out = stageOutputSize(size);
52
+ const label = Object.keys(RTMP_RESOLUTIONS)
53
+ .find((key) => RTMP_RESOLUTIONS[key].width === out.width && RTMP_RESOLUTIONS[key].height === out.height)
54
+ || `${out.width}x${out.height}`;
55
+ return { width: out.width, height: out.height, label };
56
+ }
57
+
58
+ /** Bitrate in bps (values under 10 000 are read as kbps), clamped to 300–2500 kbps. */
59
+ export function clampRtmpBitrate(value, fallback = DEFAULT_RTMP_BITRATE) {
60
+ let n = Number(value);
61
+ if (!Number.isFinite(n) || n <= 0) return fallback;
62
+ if (n < 10_000) n *= 1000;
63
+ return Math.max(MIN_RTMP_BITRATE, Math.min(MAX_RTMP_BITRATE, Math.round(n)));
64
+ }
65
+
66
+ /** Keyframe interval in seconds, clamped to 1–10. */
67
+ export function clampRtmpKeyframeInterval(value, fallback = DEFAULT_RTMP_KEYFRAME_INTERVAL) {
68
+ const n = Number(value);
69
+ if (!Number.isFinite(n) || n <= 0) return fallback;
70
+ return Math.max(MIN_RTMP_KEYFRAME_INTERVAL, Math.min(MAX_RTMP_KEYFRAME_INTERVAL, Math.round(n * 10) / 10));
71
+ }
7
72
 
8
73
  /**
9
74
  * Stage compositor for RTMP live streaming.
@@ -21,7 +86,7 @@ export class LiveCompositor extends CanvasRecorder {
21
86
  && typeof AudioContext !== "undefined";
22
87
  }
23
88
 
24
- constructor({ fps = DEFAULT_RTMP_FPS, selfName, canvasBackground, onFailure } = {}) {
89
+ constructor({ fps = DEFAULT_RTMP_FPS, resolution = DEFAULT_RTMP_RESOLUTION, selfName, canvasBackground, avatarBackground, onFailure } = {}) {
25
90
  const id = `live-${Math.random().toString(36).slice(2, 10)}`;
26
91
  super({
27
92
  webinarId: id,
@@ -31,8 +96,10 @@ export class LiveCompositor extends CanvasRecorder {
31
96
  token: "",
32
97
  selfName,
33
98
  canvasBackground,
99
+ avatarBackground,
34
100
  onFailure,
35
101
  fps: clampFps(fps, DEFAULT_RTMP_FPS),
102
+ outputSize: normalizeRtmpResolution(resolution),
36
103
  });
37
104
  this.eventPrefix = "live";
38
105
  // RTMP platforms expect a constant frame rate even when the stage is static.
@@ -30,7 +30,7 @@ function bounded(promise, timeoutMs) {
30
30
  }
31
31
 
32
32
  /** Probe real frame transfer before selecting the background-capable compositor. */
33
- export async function createWorkerCompositor({ width, height, fps, background = "#0A0036", steady = false, onError = () => {} }) {
33
+ export async function createWorkerCompositor({ width, height, scale = 1, fps, background = "#0A0036", avatarBackground = null, steady = false, onError = () => {} }) {
34
34
  let worker, output, probeInput, probeClone, outputProbe, reader, inputWriter, probeFrame;
35
35
  const deadline = Date.now() + 3000;
36
36
  const remaining = () => Math.max(1, deadline - Date.now());
@@ -40,7 +40,7 @@ export async function createWorkerCompositor({ width, height, fps, background =
40
40
  worker = new Worker(new URL("./record-worker.js", import.meta.url), { type: "module" });
41
41
  const { standard } = await ask({ type: "capabilities" });
42
42
  if (standard) {
43
- const ready = await ask({ type: "init", standard: true, width, height, fps, background, steady });
43
+ const ready = await ask({ type: "init", standard: true, width, height, scale, fps, background, avatarBackground, steady });
44
44
  output = ready.track;
45
45
  const canvas = document.createElement("canvas");
46
46
  canvas.width = canvas.height = 2;
@@ -52,7 +52,7 @@ export async function createWorkerCompositor({ width, height, fps, background =
52
52
  } else {
53
53
  if (typeof MediaStreamTrackProcessor !== "function" || typeof MediaStreamTrackGenerator !== "function") throw new Error("Native recording track processor/generator are unavailable");
54
54
  output = new MediaStreamTrackGenerator({ kind: "video" });
55
- await ask({ type: "init", width, height, fps, background, steady, writable: output.writable }, [output.writable]);
55
+ await ask({ type: "init", width, height, scale, fps, background, avatarBackground, steady, writable: output.writable }, [output.writable]);
56
56
  outputProbe = output.clone();
57
57
  reader = new MediaStreamTrackProcessor({ track: outputProbe, maxBufferSize: 1 }).readable.getReader();
58
58
  const received = reader.read();
@@ -84,7 +84,7 @@ export async function createWorkerCompositor({ width, height, fps, background =
84
84
  for (const [key, entry] of owned) if (!keys.has(key)) { release(entry); owned.delete(key); }
85
85
  const transfer = [];
86
86
  const updates = desired.map((source) => {
87
- const { key, track, rect, crop, label, accent, radius, muted, fit, fillStyle } = source;
87
+ const { key, track, rect, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground: avatar } = source;
88
88
  const chrome = {
89
89
  key,
90
90
  rect,
@@ -95,6 +95,8 @@ export async function createWorkerCompositor({ width, height, fps, background =
95
95
  muted: Boolean(muted),
96
96
  fit: fit === "contain" ? "contain" : "cover",
97
97
  ...(fillStyle ? { fillStyle } : {}),
98
+ placeholder: Boolean(placeholder),
99
+ avatarBackground: avatar || null,
98
100
  };
99
101
  const previous = owned.get(key);
100
102
  if (previous?.original === track) return chrome;
@@ -118,6 +120,10 @@ export async function createWorkerCompositor({ width, height, fps, background =
118
120
  sources = next;
119
121
  try { sync(); } catch (failure) { onError(failure); }
120
122
  },
123
+ setAppearance({ background: nextBackground, avatarBackground: nextAvatar } = {}) {
124
+ if (closed) return;
125
+ worker.postMessage({ type: "appearance", background: nextBackground, avatarBackground: nextAvatar });
126
+ },
121
127
  setActive(next) {
122
128
  if (closed || active === next) return;
123
129
  active = next;