mediascale-sdk 1.0.10 → 1.0.12

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.
@@ -98,13 +98,14 @@ client.setRecordingStage([
98
98
  | Field | Meaning |
99
99
  | --- | --- |
100
100
  | `id` | Stable peer id for that person (use the same id you already use in your app; when they publish webcam, the SDK matches the tile by this id / publisher id) |
101
- | `name` | Display name on the avatar tile |
101
+ | `name` | Display name on the avatar / video tile and its name pill |
102
102
  | `local` | `true` for this browser’s own tile |
103
103
 
104
104
  Rules:
105
105
 
106
106
  - Call `setRecordingStage` on **add to stage**, **remove from stage**, and when names change — keep it identical to what participants see.
107
- - Everyone in the list gets an **avatar** until their webcam is published; then that tile becomes **video**.
107
+ - Everyone in the list gets an **avatar** until their webcam is published; then that tile becomes **video**. The same `name` is drawn on the bottom-left name pill.
108
+ - At most **six** people are drawn on the canvas (list order); audio for everyone else is still mixed.
108
109
  - Pass `[]` to clear the stage list; you normally keep at least the people currently on stage.
109
110
  - `onStageChanged(people)` is optional if you only care about driving the recorder from your own stage state.
110
111
 
@@ -122,7 +123,7 @@ Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file
122
123
  6. **Record** (host) starts automatically when enabled on the token / `createClient`, or from the toolbar via `startRecording()` / `stopRecording()`. You can toggle any time; the final file includes every segment and mirrors the live stage layout.
123
124
  7. **End** leaves the session and saves the recording if this person was recording.
124
125
 
125
- `recording` defaults to **false**. Set `createClient({ recording: true })` **or** put `recording: true` on the host JWT when the host should already be recording when they join (Stream Control “Enable recording” does this). Chunks start **immediately** on connect / `startRecording()` — mic and camera are not required. Until video is live, the recording canvas shows the same host placeholder as the live stage (magenta background, avatar letter, name).
126
+ `recording` defaults to **false**. Set `createClient({ recording: true })` **or** put `recording: true` on the host JWT when the host should already be recording when they join (Stream Control “Enable recording” does this). Chunks start **immediately** on connect / `startRecording()` — mic and camera are not required. Until video is live, the recording canvas shows the host placeholder (magenta field, circular letter avatar, bottom-left **name pill**).
126
127
 
127
128
  The room must run in the browser. `app/page.js`
128
129
 
@@ -215,7 +216,7 @@ await client.end(); // combines every segment into one file
215
216
 
216
217
  | Function | What it does |
217
218
  | --- | --- |
218
- | `createClient({ endpoint, sessionId, token, recording, iceServers, publishLimits, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. Optional `publishLimits: { cameraBps, screenBps }` overrides portal join caps. |
219
+ | `createClient({ endpoint, sessionId, token, recording, recordingCanvasBackground, iceServers, publishLimits, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. Optional `recordingCanvasBackground` (CSS color, default `#2563eb`) is the base for the radial + wave canvas backdrop and the local/presenter accent border. Optional `publishLimits: { cameraBps, screenBps }` overrides portal join caps. |
219
220
  | `connect()` | Checks the token and joins the session. If recording is enabled for a **host**, recording starts immediately in the background (same as `startRecording()`). Join does not wait for capture to finish preparing. |
220
221
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
221
222
  | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
@@ -233,7 +234,7 @@ await client.end(); // combines every segment into one file
233
234
  | `startRecording()` | Starts recording for this person (or resumes after `stopRecording()`). Chunks upload immediately — mic/camera not required. Empty stage uses the host placeholder tile until real video is published. Also used when the host left and a cohost should continue the same file. |
234
235
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
235
236
  | `setRecordingCrop(source, crop)` | Crops a video source in the recording layout. `crop` is `{ x, y, w, h }` in 0..1 (same as subscriber whiteboard crop). Pass `null` to clear. |
236
- | `setRecordingStage(people)` | **Required for stage-accurate recording.** Who appears on the recording stage: `[{ id, name, local? }]`. Avatars until that peer’s webcam arrives. See [Recording must match the live stage](#recording-must-match-the-live-stage). |
237
+ | `setRecordingStage(people)` | **Required for stage-accurate recording.** Who appears on the recording stage: `[{ id, name, local? }]` (max six on canvas). Avatars + name pills until that peer’s webcam arrives. See [Recording must match the live stage](#recording-must-match-the-live-stage). |
237
238
  | `getPeerId()` | Socket peer id for this browser after `connect()`. |
238
239
  | `getPublishLimits()` | Current `{ cameraBps, screenBps }` used for outgoing video encode caps. |
239
240
  | `getUserList()` / `updateSelf(...)` / `stageAction(...)` | Optional portal roster helpers used by the sample meet UI. Skip these if your app already manages users and stage on its own. |
@@ -295,7 +296,7 @@ Publish any `MediaStreamTrack` under your own id. Subscribers get that same id a
295
296
 
296
297
  Reserved ids (use the dedicated APIs instead): `webcam`, `mic`, `screen`.
297
298
 
298
- Custom **video** sources (for example `whiteboard`) use the large featured layout slot in the recording compositor, like screen share.
299
+ Custom **video** sources (for example `whiteboard`) use the large featured layout slot in the recording compositor, like screen share (cameras stack from the top in the side column; up to six).
299
300
 
300
301
  ### Whiteboard example
301
302
 
@@ -357,8 +358,8 @@ client.setRecordingCrop("whiteboard", null); // clear
357
358
  ### What gets recorded
358
359
 
359
360
  - Chunks upload as soon as recording starts — **mic and camera are not required**.
360
- - With no live video, the canvas matches the live empty stage: magenta radial background, circular avatar with the host’s first letter, and a `Name (You)` label. The recording keeps going on that placeholder until real media appears.
361
- - When webcam, screen, or a featured custom video (for example whiteboard) is published, those tiles replace the placeholder in the layout (up to four cameras; screen/custom video takes the main area).
361
+ - With no live video, the canvas shows the empty-stage placeholder: magenta radial field, circular letter avatar, and a bottom-left **name pill** (display name from the host JWT / stage). Recording continues on that placeholder until real media appears.
362
+ - When webcam, screen, or a featured custom video (for example whiteboard) is published, those tiles replace the placeholder (see [Recording layout](#recording-layout) below).
362
363
  - Local + remote mics (and screen audio) are mixed when available. If the browser leaves `AudioContext` suspended, silence is recorded until the first click/key in the tab unlocks audio mixing.
363
364
  - `stopRecording()` only pauses. It does not upload a finished file. `startRecording()` afterward opens a new segment under the same recording id.
364
365
  - `end()` (or idle finalize when everybody has left) combines every segment into **one** playable file.
@@ -366,6 +367,48 @@ client.setRecordingCrop("whiteboard", null); // clear
366
367
  - The file keeps going when another person calls `startRecording()` after a handoff. Ask them to start before the previous recorder calls `end()`.
367
368
  - If everybody leaves, the recording is still saved after a few minutes of silence.
368
369
 
370
+ ### Recording layout
371
+
372
+ Canvas is **1280×720**. Video tiles and audio follow these rules:
373
+
374
+ | Case | Layout |
375
+ | --- | --- |
376
+ | Single camera or avatar (no screen / featured video) | **Full-bleed** — tile fills the canvas. No borders. Name + mic pill still drawn. |
377
+ | Two or more cameras (no screen) | **Flush mosaic** — zero margins/gaps between tiles, edge-to-edge, no borders. 3 cams → one row; otherwise 2- or 3-column pack. |
378
+ | Screen share or featured custom video (e.g. whiteboard) | Screen fills the left (~80%) with **contain** (no crop — blue letterbox top/bottom as needed). Up to **six** cameras in a right rail, **vertically centered**, **16:9** height (not stretched). Zero gaps. Extra stage video beyond six is omitted from the canvas. |
379
+ | Audio | **Uncapped** — every mic and screen-audio track is mixed even if that person is not among the six video tiles. |
380
+
381
+ **Name pills**
382
+
383
+ - Every camera / avatar tile gets a bottom-left pill with **name + mic status** (green signal bars when live, red muted mic when muted), same as the live stage UI.
384
+ - Label comes from `setRecordingStage` `name`, else the track `displayName`, else the local host JWT name (`Guest` / `Host` as fallback). Presenter gets `(Presenter)` on the pill.
385
+ - The pill is drawn even while the first video frame is still loading (dark tile + name).
386
+ - The large screen / whiteboard pane does **not** get a name pill.
387
+
388
+ Use `setRecordingStage([{ id, name, local? }, ...])` so avatar tiles and name pills match the live stage. Without it, only live tracks appear (plus a single host placeholder when nobody is publishing).
389
+
390
+ ### Recording canvas background
391
+
392
+ The canvas behind multi-tile / screen layouts defaults to `#2563eb`. Pass any CSS color on `createClient`; the SDK paints a **radial gradient with soft wave glows** from that color:
393
+
394
+ ```js
395
+ const client = createClient({
396
+ endpoint,
397
+ sessionId,
398
+ token,
399
+ recording: true,
400
+ // Base color for the radial + wave canvas background.
401
+ // Default: "#2563eb"
402
+ recordingCanvasBackground: "#6d28d9",
403
+ });
404
+ ```
405
+
406
+ | Option | Default | Meaning |
407
+ | --- | --- | --- |
408
+ | `recordingCanvasBackground` | `#2563eb` | Base CSS color for the recording canvas gradient / wave backdrop and the local/presenter accent border (multi-tile layouts). |
409
+
410
+ Set this once at `createClient`. It applies to both the worker compositor and the foreground canvas fallback. On a **single full-bleed** camera/avatar tile the background is covered by the tile itself.
411
+
369
412
  ### Background-safe compositing
370
413
 
371
414
  Recording prefers a **worker / OffscreenCanvas** compositor so frames keep flowing when the tab is backgrounded. If the browser cannot probe that path, it falls back to the foreground canvas compositor.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.10",
3
+ "version": "1.0.12",
4
4
  "description": "Mediascale React/browser SDK for live sessions, WebRTC publish/subscribe, and recording",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -29,6 +29,12 @@ function normalizePublishLimits(raw = {}) {
29
29
  };
30
30
  }
31
31
 
32
+ /** CSS color for the recording canvas fill. Empty / invalid → #2563eb. */
33
+ function normalizeCanvasBackground(raw) {
34
+ const color = String(raw ?? "").trim();
35
+ return color || "#2563eb";
36
+ }
37
+
32
38
  function readToken(token) {
33
39
  const body = String(token || "").split(".")[0];
34
40
  if (!body) throw new Error("token is required");
@@ -97,6 +103,8 @@ export function createClient(options = {}) {
97
103
  // Explicit option wins; otherwise honor recording flag embedded in the host token.
98
104
  const recording = options.recording === true
99
105
  || (options.recording !== false && claims.recording === true && claims.role === "host");
106
+ // Main recording canvas fill (letterbox / empty areas). Defaults to #2563eb.
107
+ const recordingCanvasBackground = normalizeCanvasBackground(options.recordingCanvasBackground);
100
108
 
101
109
  const displayName = String(claims.name || "Guest").slice(0, 40);
102
110
  // createClient({ publishLimits }) wins over portal join values when set.
@@ -115,6 +123,8 @@ export function createClient(options = {}) {
115
123
  let subscribed = false;
116
124
  let recorder = null;
117
125
  let startingRecorder = null;
126
+ /** Sticky id for stop/start segments; replaced after a take is finalized/failed. */
127
+ let activeRecordingId = null;
118
128
  let selfPeerId = null;
119
129
  const locals = new Map();
120
130
  const tiles = new Map();
@@ -125,6 +135,8 @@ export function createClient(options = {}) {
125
135
  /** When set, parent-provided stage list wins over roster-derived stageById. */
126
136
  let stageOverride = null;
127
137
  let lastStageSig = "";
138
+ /** Integration debug: log current recording stage every 5s. */
139
+ let stageDebugTimer = null;
128
140
  const pending = [];
129
141
  let readyPromise = null;
130
142
  let settleReady = null;
@@ -155,14 +167,33 @@ export function createClient(options = {}) {
155
167
  return [...stageById.values()];
156
168
  }
157
169
 
170
+ function logRecordingStage(reason) {
171
+ const people = stagePeopleForRecording();
172
+ console.log("[mediascale] recording stage", {
173
+ reason,
174
+ source: stageOverride ? "setRecordingStage" : "roster",
175
+ count: people.length,
176
+ people: people.map((p) => ({ id: p.id, name: p.name, local: Boolean(p.local) })),
177
+ });
178
+ }
179
+
158
180
  function emitStageChanged() {
159
181
  const people = stagePeopleForRecording();
160
182
  const sig = people.map((p) => `${p.id}|${p.name}|${p.local ? 1 : 0}`).join(";");
161
183
  if (sig === lastStageSig) return;
162
184
  lastStageSig = sig;
185
+ // Integration: confirm setRecordingStage / roster stage updates reach the SDK recorder.
186
+ logRecordingStage("changed");
163
187
  onStageChanged(people);
164
188
  }
165
189
 
190
+ if (typeof setInterval === "function") {
191
+ stageDebugTimer = setInterval(() => {
192
+ if (closed) return;
193
+ logRecordingStage("poll-5s");
194
+ }, 5000);
195
+ }
196
+
166
197
  function ingestRosterUsers(users) {
167
198
  if (!Array.isArray(users)) return;
168
199
  stageById.clear();
@@ -497,6 +528,23 @@ export function createClient(options = {}) {
497
528
  }
498
529
  }
499
530
 
531
+ async function ensureRecorderAffinity() {
532
+ const webinarId = recordingWebinarId(sessionId);
533
+ try {
534
+ const response = await fetch(
535
+ `${endpoint}/recorder/api/v1/affinity?webinarId=${encodeURIComponent(webinarId)}`,
536
+ { credentials: "include" },
537
+ );
538
+ if (!response.ok) return;
539
+ const body = await response.json().catch(() => null);
540
+ if (body?.peer && typeof document !== "undefined") {
541
+ document.cookie = `ms_recorder=${encodeURIComponent(body.peer)}; Path=/; Max-Age=86400; SameSite=Lax`;
542
+ }
543
+ } catch {
544
+ /* gateway may still route to the seed recorder */
545
+ }
546
+ }
547
+
500
548
  async function connect() {
501
549
  if (readyPromise) return readyPromise;
502
550
  readyPromise = (async () => {
@@ -882,6 +930,44 @@ export function createClient(options = {}) {
882
930
  onRecording(next.capturing ? "recording" : "armed");
883
931
  }
884
932
 
933
+ async function openRecorder(recordingId) {
934
+ await ensureRecorderAffinity();
935
+ await emit(socket, "claimRecording", { recordingId });
936
+ if (closed || recorder) return;
937
+ const next = new CanvasRecorder({
938
+ webinarId: recordingWebinarId(sessionId),
939
+ webinarName: sessionId,
940
+ recordingId,
941
+ endpoint,
942
+ token,
943
+ selfName: displayName,
944
+ canvasBackground: recordingCanvasBackground,
945
+ // Chunks start immediately; empty stage uses the same host placeholder as live UI.
946
+ onCaptureChange: () => notifyRecording(next),
947
+ onFailure: (error) => {
948
+ if (recorder !== next) return;
949
+ recorder = null;
950
+ onRecording("stopped");
951
+ onError(error);
952
+ },
953
+ });
954
+ recorder = next;
955
+ next.wanted = true;
956
+ notifyRecording(next);
957
+ for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
958
+ next.sync(tracksForRecording(), stagePeopleForRecording());
959
+ try {
960
+ await next.start();
961
+ } catch (error) {
962
+ if (recorder === next) recorder = null;
963
+ onRecording("stopped");
964
+ throw error instanceof Error ? error : new Error(String(error));
965
+ }
966
+ if (recorder !== next) return;
967
+ activeRecordingId = recordingId;
968
+ notifyRecording(next);
969
+ }
970
+
885
971
  async function startRecording() {
886
972
  if (closed) throw new Error("The session has ended");
887
973
  if (!sendTransport) await connect();
@@ -893,39 +979,18 @@ export function createClient(options = {}) {
893
979
  }
894
980
  if (startingRecorder) return startingRecorder;
895
981
  startingRecorder = (async () => {
896
- const recordingId = await recordingIdFor(sessionId);
897
- await emit(socket, "claimRecording", { recordingId });
898
- if (closed || recorder) return;
899
- const next = new CanvasRecorder({
900
- webinarId: recordingWebinarId(sessionId),
901
- webinarName: sessionId,
902
- recordingId,
903
- endpoint,
904
- token,
905
- selfName: displayName,
906
- // Chunks start immediately; empty stage uses the same host placeholder as live UI.
907
- onCaptureChange: () => notifyRecording(next),
908
- onFailure: (error) => {
909
- if (recorder !== next) return;
910
- recorder = null;
911
- onRecording("stopped");
912
- onError(error);
913
- },
914
- });
915
- recorder = next;
916
- next.wanted = true;
917
- notifyRecording(next);
918
- for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
919
- next.sync(tracksForRecording(), stagePeopleForRecording());
982
+ // Prefer the session's stable id (handoff). If that take already finalized/failed,
983
+ // mint a new UUID so the host can record again in the same room.
984
+ let recordingId = activeRecordingId || await recordingIdFor(sessionId);
920
985
  try {
921
- await next.start();
986
+ await openRecorder(recordingId);
922
987
  } catch (error) {
923
- if (recorder === next) recorder = null;
924
- onRecording("stopped");
925
- throw error instanceof Error ? error : new Error(String(error));
988
+ const message = error instanceof Error ? error.message : String(error);
989
+ if (!/recording is already finished/i.test(message)) throw error;
990
+ recordingId = crypto.randomUUID();
991
+ activeRecordingId = recordingId;
992
+ await openRecorder(recordingId);
926
993
  }
927
- if (recorder !== next) return;
928
- notifyRecording(next);
929
994
  })();
930
995
  try {
931
996
  await startingRecorder;
@@ -948,11 +1013,16 @@ export function createClient(options = {}) {
948
1013
  async function end(options = {}) {
949
1014
  if (closed) return;
950
1015
  closed = true;
1016
+ if (stageDebugTimer) {
1017
+ clearInterval(stageDebugTimer);
1018
+ stageDebugTimer = null;
1019
+ }
951
1020
  settleReady?.(new Error("Ended"));
952
1021
  // Finalize only on explicit stop-session / finalize. Browser close uses disconnect handoff.
953
1022
  const forceFinalize = options.finalize === true || options.endSession === true;
954
1023
  const current = recorder;
955
1024
  recorder = null;
1025
+ if (forceFinalize) activeRecordingId = null;
956
1026
  try {
957
1027
  if (current) {
958
1028
  let handoff = false;
@@ -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, onError = () => {} }) {
33
+ export async function createWorkerCompositor({ width, height, fps, background = "#2563eb", 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, onError = ()
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 });
43
+ const ready = await ask({ type: "init", standard: true, width, height, fps, background });
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, onError = ()
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, writable: output.writable }, [output.writable]);
55
+ await ask({ type: "init", width, height, fps, background, 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();
@@ -83,16 +83,29 @@ export async function createWorkerCompositor({ width, height, fps, onError = ()
83
83
  const keys = new Set(desired.map((source) => source.key));
84
84
  for (const [key, entry] of owned) if (!keys.has(key)) { release(entry); owned.delete(key); }
85
85
  const transfer = [];
86
- const updates = desired.map(({ key, track, rect, crop }) => {
86
+ const updates = desired.map((source) => {
87
+ const { key, track, rect, crop, label, accent, radius, muted, fit, fillStyle } = source;
88
+ const chrome = {
89
+ key,
90
+ rect,
91
+ crop: crop || null,
92
+ label: label || "",
93
+ accent: Boolean(accent),
94
+ radius: radius == null ? 0 : radius,
95
+ muted: Boolean(muted),
96
+ fit: fit === "contain" ? "contain" : "cover",
97
+ ...(fillStyle ? { fillStyle } : {}),
98
+ };
87
99
  const previous = owned.get(key);
88
- if (previous?.original === track) return { key, rect, crop: crop || null };
100
+ if (previous?.original === track) return chrome;
89
101
  if (previous) release(previous);
102
+ if (!track) return chrome;
90
103
  const clone = track.clone();
91
104
  owned.set(key, { clone, original: track });
92
- if (standard) { transfer.push(clone); return { key, rect, crop: crop || null, track: clone }; }
105
+ if (standard) { transfer.push(clone); return { ...chrome, track: clone }; }
93
106
  const readable = new MediaStreamTrackProcessor({ track: clone, maxBufferSize: 1 }).readable;
94
107
  transfer.push(readable);
95
- return { key, rect, crop: crop || null, readable };
108
+ return { ...chrome, readable };
96
109
  });
97
110
  worker.postMessage({ type: "sources", sources: updates }, transfer);
98
111
  };
@@ -1,12 +1,264 @@
1
+ /** Parse `#rgb` / `#rrggbb` / `rgb()` / `rgba()` into `{ r, g, b }`. */
2
+ export function parseCssColor(input) {
3
+ const raw = String(input || "").trim();
4
+ if (!raw) return null;
5
+ const hex = raw.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
6
+ if (hex) {
7
+ const h = hex[1];
8
+ const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
9
+ return {
10
+ r: Number.parseInt(full.slice(0, 2), 16),
11
+ g: Number.parseInt(full.slice(2, 4), 16),
12
+ b: Number.parseInt(full.slice(4, 6), 16),
13
+ };
14
+ }
15
+ const rgb = raw.match(/^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);
16
+ if (rgb) {
17
+ return {
18
+ r: Math.round(Number(rgb[1])),
19
+ g: Math.round(Number(rgb[2])),
20
+ b: Math.round(Number(rgb[3])),
21
+ };
22
+ }
23
+ return null;
24
+ }
25
+
26
+ function shadeRgb({ r, g, b }, factor) {
27
+ return {
28
+ r: Math.round(Math.min(255, Math.max(0, r * factor))),
29
+ g: Math.round(Math.min(255, Math.max(0, g * factor))),
30
+ b: Math.round(Math.min(255, Math.max(0, b * factor))),
31
+ };
32
+ }
33
+
34
+ function cssRgb({ r, g, b }, alpha = 1) {
35
+ if (alpha >= 1) return `rgb(${r}, ${g}, ${b})`;
36
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
37
+ }
38
+
39
+ function softBlob(ctx, cx, cy, rx, ry, color, alpha) {
40
+ const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, Math.max(rx, ry));
41
+ g.addColorStop(0, cssRgb(color, alpha));
42
+ g.addColorStop(0.55, cssRgb(color, alpha * 0.35));
43
+ g.addColorStop(1, cssRgb(color, 0));
44
+ ctx.fillStyle = g;
45
+ ctx.beginPath();
46
+ ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);
47
+ ctx.fill();
48
+ }
49
+
50
+ /**
51
+ * Brand canvas backdrop: deep radial field + soft corner waves from `color`.
52
+ */
53
+ export function fillRadialBackground(ctx, x, y, w, h, color = "#2563eb") {
54
+ const base = parseCssColor(color) || { r: 37, g: 99, b: 235 };
55
+ const deep = shadeRgb(base, 0.28);
56
+ const mid = shadeRgb(base, 0.72);
57
+ const glow = shadeRgb(base, 1.35);
58
+ const cx = x + w / 2;
59
+ const cy = y + h / 2;
60
+
61
+ ctx.fillStyle = cssRgb(deep);
62
+ ctx.fillRect(x, y, w, h);
63
+
64
+ const field = ctx.createRadialGradient(cx, cy - h * 0.08, 0, cx, cy, Math.max(w, h) * 0.9);
65
+ field.addColorStop(0, cssRgb(glow, 0.42));
66
+ field.addColorStop(0.4, cssRgb(mid, 0.55));
67
+ field.addColorStop(1, cssRgb(deep, 1));
68
+ ctx.fillStyle = field;
69
+ ctx.fillRect(x, y, w, h);
70
+
71
+ // Soft wave-like glows (top-left / bottom-right), matching the reference stage look.
72
+ softBlob(ctx, x + w * 0.18, y + h * 0.1, w * 0.42, h * 0.32, glow, 0.38);
73
+ softBlob(ctx, x + w * 0.82, y + h * 0.88, w * 0.4, h * 0.3, glow, 0.3);
74
+ softBlob(ctx, x + w * 0.7, y + h * 0.18, w * 0.28, h * 0.22, mid, 0.22);
75
+ }
76
+
77
+ export function roundedRectPath(ctx, x, y, w, h, radius) {
78
+ const r = Math.max(0, Math.min(radius, w / 2, h / 2));
79
+ ctx.beginPath();
80
+ ctx.moveTo(x + r, y);
81
+ ctx.arcTo(x + w, y, x + w, y + h, r);
82
+ ctx.arcTo(x + w, y + h, x, y + h, r);
83
+ ctx.arcTo(x, y + h, x, y, r);
84
+ ctx.arcTo(x, y, x + w, y, r);
85
+ ctx.closePath();
86
+ }
87
+
88
+ /** Neon magenta presenter ring — matches the live stage / webinar UI. */
89
+ export const PRESENTER_ACCENT = "#e879f9";
90
+
91
+ function drawSignalBars(ctx, left, cy, iconSize) {
92
+ const barW = Math.max(2, Math.round(iconSize * 0.18));
93
+ const gap = Math.max(1.5, Math.round(iconSize * 0.12));
94
+ const heights = [0.45, 0.7, 1];
95
+ ctx.fillStyle = "#22c55e";
96
+ for (let i = 0; i < 3; i += 1) {
97
+ const h = iconSize * heights[i];
98
+ const x = left + i * (barW + gap);
99
+ const y = cy - h / 2;
100
+ ctx.beginPath();
101
+ roundedRectPath(ctx, x, y, barW, h, barW / 2);
102
+ ctx.fill();
103
+ }
104
+ }
105
+
106
+ function drawMicMuted(ctx, cx, cy, iconSize) {
107
+ const r = iconSize * 0.22;
108
+ ctx.strokeStyle = "#f43f5e";
109
+ ctx.fillStyle = "#f43f5e";
110
+ ctx.lineWidth = Math.max(1.5, iconSize * 0.1);
111
+ ctx.lineCap = "round";
112
+ // Mic capsule
113
+ ctx.beginPath();
114
+ ctx.moveTo(cx - r, cy - iconSize * 0.05);
115
+ ctx.quadraticCurveTo(cx - r, cy - iconSize * 0.38, cx, cy - iconSize * 0.38);
116
+ ctx.quadraticCurveTo(cx + r, cy - iconSize * 0.38, cx + r, cy - iconSize * 0.05);
117
+ ctx.lineTo(cx + r, cy + iconSize * 0.02);
118
+ ctx.quadraticCurveTo(cx + r, cy + iconSize * 0.22, cx, cy + iconSize * 0.22);
119
+ ctx.quadraticCurveTo(cx - r, cy + iconSize * 0.22, cx - r, cy + iconSize * 0.02);
120
+ ctx.closePath();
121
+ ctx.fill();
122
+ // Stem + base
123
+ ctx.beginPath();
124
+ ctx.arc(cx, cy + iconSize * 0.05, iconSize * 0.28, 0.15 * Math.PI, 0.85 * Math.PI);
125
+ ctx.stroke();
126
+ ctx.beginPath();
127
+ ctx.moveTo(cx, cy + iconSize * 0.32);
128
+ ctx.lineTo(cx, cy + iconSize * 0.42);
129
+ ctx.moveTo(cx - iconSize * 0.16, cy + iconSize * 0.42);
130
+ ctx.lineTo(cx + iconSize * 0.16, cy + iconSize * 0.42);
131
+ ctx.stroke();
132
+ // Slash
133
+ ctx.beginPath();
134
+ ctx.moveTo(cx - iconSize * 0.32, cy + iconSize * 0.38);
135
+ ctx.lineTo(cx + iconSize * 0.32, cy - iconSize * 0.38);
136
+ ctx.stroke();
137
+ }
138
+
139
+ /**
140
+ * Bottom-left name pill matching the live stage UI:
141
+ * dark pill + green signal bars (live) or red muted mic + optional "(Presenter)".
142
+ */
143
+ export function drawNamePill(ctx, x, y, w, h, label, { presenter = false, muted = false } = {}) {
144
+ let text = String(label || "").trim().slice(0, 40);
145
+ if (!text) return;
146
+ if (presenter && !/\(\s*presenter\s*\)/i.test(text)) {
147
+ text = `${text.slice(0, 28)} (Presenter)`;
148
+ }
149
+ const padX = Math.max(10, Math.round(Math.min(w, h) * 0.035));
150
+ const padY = Math.max(8, Math.round(Math.min(w, h) * 0.03));
151
+ const namePx = Math.round(Math.min(Math.max(Math.min(w, h) * 0.08, 11), 15));
152
+ const iconSize = Math.round(namePx * 1.15);
153
+ ctx.save();
154
+ ctx.font = `600 ${namePx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
155
+ ctx.textAlign = "left";
156
+ ctx.textBaseline = "middle";
157
+ const textW = ctx.measureText(text).width;
158
+ const iconGap = Math.round(iconSize * 0.45);
159
+ const pillH = Math.max(iconSize + padY * 0.7, namePx + padY);
160
+ const contentW = iconSize + iconGap + textW;
161
+ const pillW = Math.min(w - padX * 2, contentW + padX * 1.5);
162
+ const pillX = x + padX;
163
+ const pillY = y + h - padY - pillH;
164
+ const radius = pillH / 2;
165
+ roundedRectPath(ctx, pillX, pillY, pillW, pillH, radius);
166
+ ctx.fillStyle = "rgba(15, 23, 42, 0.72)";
167
+ ctx.fill();
168
+
169
+ const cy = pillY + pillH / 2;
170
+ const iconLeft = pillX + padX * 0.55;
171
+ if (presenter || !muted) {
172
+ drawSignalBars(ctx, iconLeft, cy, iconSize);
173
+ } else {
174
+ drawMicMuted(ctx, iconLeft + iconSize / 2, cy, iconSize);
175
+ }
176
+ ctx.fillStyle = "#ffffff";
177
+ const textX = iconLeft + iconSize + iconGap;
178
+ ctx.fillText(text, textX, cy + 0.5, Math.max(8, pillW - (textX - pillX) - padX * 0.5));
179
+ ctx.restore();
180
+ }
181
+
182
+ export function strokeTileBorder(ctx, x, y, w, h, radius, { accent = false, accentColor = PRESENTER_ACCENT } = {}) {
183
+ // Recording layout is flush (no borders). Accent only affects the name pill.
184
+ if (!(radius > 0)) return;
185
+ const base = parseCssColor(accentColor) || { r: 232, g: 121, b: 249 };
186
+ ctx.save();
187
+ roundedRectPath(ctx, x + 0.5, y + 0.5, w - 1, h - 1, radius);
188
+ if (accent) {
189
+ ctx.strokeStyle = cssRgb(shadeRgb(base, 1.05));
190
+ ctx.lineWidth = 3;
191
+ ctx.shadowColor = cssRgb(base, 0.95);
192
+ ctx.shadowBlur = 14;
193
+ } else {
194
+ ctx.strokeStyle = "rgba(255, 255, 255, 0.45)";
195
+ ctx.lineWidth = 1.5;
196
+ ctx.shadowBlur = 0;
197
+ }
198
+ ctx.stroke();
199
+ ctx.restore();
200
+ }
201
+
202
+ /**
203
+ * Draw a video/image source into a tile (flush by default) + name/mic pill.
204
+ * `fit: "cover"` fills the rect (cameras). `fit: "contain"` letterboxes inside
205
+ * the rect (screenshare — no cropping; bars use `fillStyle`, typically brand blue).
206
+ * `source` may be an HTMLVideoElement or VideoFrame-like canvas image source.
207
+ */
208
+ export function paintRoundedTile(ctx, {
209
+ source,
210
+ rect,
211
+ sx = 0,
212
+ sy = 0,
213
+ sw,
214
+ sh,
215
+ label = "",
216
+ accent = false,
217
+ accentColor = PRESENTER_ACCENT,
218
+ radius = 0,
219
+ fillStyle = "#0f172a",
220
+ muted = false,
221
+ fit = "cover",
222
+ }) {
223
+ const { x, y, w, h } = rect;
224
+ ctx.save();
225
+ if (radius > 0) {
226
+ roundedRectPath(ctx, x, y, w, h, radius);
227
+ ctx.clip();
228
+ } else {
229
+ ctx.beginPath();
230
+ ctx.rect(x, y, w, h);
231
+ ctx.clip();
232
+ }
233
+ ctx.fillStyle = fillStyle;
234
+ ctx.fillRect(x, y, w, h);
235
+ if (source && sw > 0 && sh > 0) {
236
+ const scale = fit === "contain"
237
+ ? Math.min(w / sw, h / sh)
238
+ : Math.max(w / sw, h / sh);
239
+ const dw = sw * scale;
240
+ const dh = sh * scale;
241
+ const prev = ctx.imageSmoothingEnabled;
242
+ ctx.imageSmoothingEnabled = scale < 0.98;
243
+ ctx.drawImage(source, sx, sy, sw, sh, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);
244
+ ctx.imageSmoothingEnabled = prev;
245
+ }
246
+ ctx.restore();
247
+ if (radius > 0) strokeTileBorder(ctx, x, y, w, h, radius, { accent, accentColor });
248
+ if (label) drawNamePill(ctx, x, y, w, h, label, { presenter: accent, muted });
249
+ }
250
+
1
251
  /** Owns at most one input frame per source and one output write. */
2
252
  export class FrameCompositor {
3
253
  constructor({ canvas, ctx = canvas.getContext("2d"), writer, fps = 15,
254
+ background = "#2563eb",
4
255
  now = () => performance.now(), makeFrame = (surface, init) => new VideoFrame(surface, init),
5
256
  onError = () => {} }) {
6
257
  this.canvas = canvas;
7
258
  this.ctx = ctx;
8
259
  this.writer = writer;
9
260
  this.interval = 1000 / fps;
261
+ this.background = String(background || "").trim() || "#2563eb";
10
262
  this.now = now;
11
263
  this.makeFrame = makeFrame;
12
264
  this.onError = onError;
@@ -51,11 +303,34 @@ export class FrameCompositor {
51
303
  flush() {
52
304
  const now = this.now();
53
305
  if (!this.active || !this.dirty || this.writing || now - this.lastDraw < this.interval) return;
54
- this.ctx.fillStyle = "#000";
55
- this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
56
- for (const { key, rect, crop } of this.sources) {
306
+ fillRadialBackground(this.ctx, 0, 0, this.canvas.width, this.canvas.height, this.background);
307
+ for (const source of this.sources) {
308
+ const { key, rect, crop, label, accent, radius, muted, fit, fillStyle } = source;
57
309
  const frame = this.frames.get(key);
58
- if (!frame) continue;
310
+ if (!rect) continue;
311
+ const tileRadius = radius == null ? 0 : radius;
312
+ const chrome = {
313
+ label: label || "",
314
+ accent: Boolean(accent),
315
+ accentColor: PRESENTER_ACCENT,
316
+ radius: tileRadius,
317
+ muted: Boolean(muted),
318
+ fillStyle: fillStyle || "#0f172a",
319
+ fit: fit === "contain" ? "contain" : "cover",
320
+ };
321
+ if (!frame) {
322
+ // Still show the name pill while the first video frame is arriving.
323
+ if (chrome.label) {
324
+ paintRoundedTile(this.ctx, {
325
+ source: null,
326
+ rect,
327
+ sw: 0,
328
+ sh: 0,
329
+ ...chrome,
330
+ });
331
+ }
332
+ continue;
333
+ }
59
334
  const width = frame.displayWidth || frame.codedWidth || rect.w;
60
335
  const height = frame.displayHeight || frame.codedHeight || rect.h;
61
336
  let sx = 0;
@@ -70,11 +345,15 @@ export class FrameCompositor {
70
345
  sh = c.h * height;
71
346
  if (sw <= 1 || sh <= 1) continue;
72
347
  }
73
- // Contain: preserve aspect ratio (letterbox/pillarbox inside the slot).
74
- const scale = Math.min(rect.w / sw, rect.h / sh);
75
- const w = sw * scale;
76
- const h = sh * scale;
77
- this.ctx.drawImage(frame, sx, sy, sw, sh, rect.x + (rect.w - w) / 2, rect.y + (rect.h - h) / 2, w, h);
348
+ paintRoundedTile(this.ctx, {
349
+ source: frame,
350
+ rect,
351
+ sx,
352
+ sy,
353
+ sw,
354
+ sh,
355
+ ...chrome,
356
+ });
78
357
  }
79
358
  this.timestamp = Math.max(this.timestamp + 1, Math.round((now - this.startedAt) * 1000));
80
359
  const frame = this.makeFrame(this.canvas, { timestamp: this.timestamp });
@@ -46,7 +46,7 @@ self.onmessage = async ({ data }) => {
46
46
  track = generator.track;
47
47
  } else writer = data.writable.getWriter();
48
48
  const canvas = new OffscreenCanvas(data.width, data.height);
49
- compositor = new FrameCompositor({ canvas, writer, fps: data.fps, onError: error });
49
+ compositor = new FrameCompositor({ canvas, writer, fps: data.fps, background: data.background, onError: error });
50
50
  // Native input frames drive rendering. This tick only flushes a final dirty frame.
51
51
  tick = setInterval(() => compositor.flush(), Math.round(1000 / data.fps));
52
52
  postMessage({ requestId: data.requestId, track }, track ? [track] : []);
@@ -69,7 +69,17 @@ self.onmessage = async ({ data }) => {
69
69
  } else if (data.type === "sources") {
70
70
  const keys = new Set(data.sources.map((source) => source.key));
71
71
  for (const key of readers.keys()) if (!keys.has(key)) remove(key);
72
- compositor.setSources(data.sources.map(({ key, rect, crop }) => ({ key, rect, crop: crop || null })));
72
+ compositor.setSources(data.sources.map(({ key, rect, crop, label, accent, radius, muted, fit, fillStyle }) => ({
73
+ key,
74
+ rect,
75
+ crop: crop || null,
76
+ label: label || "",
77
+ accent: Boolean(accent),
78
+ radius: radius == null ? 0 : radius,
79
+ muted: Boolean(muted),
80
+ fit: fit === "contain" ? "contain" : "cover",
81
+ ...(fillStyle ? { fillStyle } : {}),
82
+ })));
73
83
  for (const source of data.sources) {
74
84
  if (!source.readable && !source.track) continue;
75
85
  remove(source.key);
package/src/record.js CHANGED
@@ -1,13 +1,29 @@
1
1
  import { createWorkerCompositor } from "./record-compositor.js";
2
- export { FrameCompositor } from "./record-frame-compositor.js";
2
+ import {
3
+ fillRadialBackground,
4
+ paintRoundedTile,
5
+ drawNamePill,
6
+ strokeTileBorder,
7
+ roundedRectPath,
8
+ PRESENTER_ACCENT,
9
+ } from "./record-frame-compositor.js";
10
+ export { FrameCompositor, fillRadialBackground, PRESENTER_ACCENT } from "./record-frame-compositor.js";
3
11
 
4
12
  const W = 1280;
5
13
  const H = 720;
6
- const COL = 240;
7
- const PAD = 8;
8
- const GAP = 8;
14
+ /** Right rail width with screenshare (~20%). Camera tiles keep 16:9 — not stretched to full height. */
15
+ const COL = Math.round(W * 0.2);
16
+ /** Flush mosaic: no outer margin and no gutters between tiles. */
17
+ const PAD = 0;
18
+ const GAP = 0;
19
+ /** Recording tiles are square-edged (no borders / radius). */
20
+ const TILE_RADIUS = 0;
21
+ /** Side-rail camera aspect (width / height). */
22
+ const SIDE_CAM_ASPECT = 16 / 9;
9
23
  const FPS = 15;
10
24
  const SLICE_MS = 5000;
25
+ /** Hard cap for on-canvas camera / avatar tiles (host included). Audio is uncapped. */
26
+ const MAX_STAGE_CAMERAS = 6;
11
27
  /** Higher bitrate keeps sharp avatar/text edges; 2 Mbps made placeholders look blurry. */
12
28
  const BITRATE = 4_500_000;
13
29
  const mime = "video/webm;codecs=vp8,opus";
@@ -18,34 +34,51 @@ export function recordingWebinarId(channelId) {
18
34
  return cleaned || "webinar";
19
35
  }
20
36
 
21
- /** Equal tiles, or one screenshare with cameras stacked in a 240px column. Up to four cameras. */
37
+ /** Equal flush tiles, or screenshare + cameras stacked from the top (proportionate height). Up to 6 cameras. */
22
38
  export function layoutSlots(cameras, screen) {
39
+ const n = Math.max(0, Math.min(MAX_STAGE_CAMERAS, Number(cameras) || 0));
40
+ // One tile only — fill the canvas so recordingCanvasBackground is not visible as a border.
41
+ if (screen && n === 0) {
42
+ return { screen: { x: 0, y: 0, w: W, h: H }, cameras: [] };
43
+ }
44
+ if (!screen && n === 1) {
45
+ return { cameras: [{ x: 0, y: 0, w: W, h: H }] };
46
+ }
23
47
  if (screen) {
24
- const mainW = W - COL - PAD * 2 - GAP;
25
- const mainH = H - PAD * 2;
26
- const n = Math.max(cameras, 1);
27
- const cellH = Math.floor((mainH - GAP * (n - 1)) / n);
48
+ const mainW = W - COL;
49
+ // Keep 16:9 side tiles; shrink only when the stack would overflow the canvas.
50
+ let tileH = Math.max(1, Math.round(COL / SIDE_CAM_ASPECT));
51
+ if (n > 0 && tileH * n > H) {
52
+ tileH = Math.max(1, Math.floor(H / n));
53
+ }
54
+ const stackH = n * tileH;
55
+ const y0 = Math.max(0, Math.floor((H - stackH) / 2));
28
56
  return {
29
- screen: { x: PAD, y: PAD, w: mainW, h: mainH },
30
- cameras: Array.from({ length: cameras }, (_, i) => ({
31
- x: PAD + mainW + GAP,
32
- y: PAD + i * (cellH + GAP),
57
+ screen: { x: 0, y: 0, w: mainW, h: H },
58
+ cameras: Array.from({ length: n }, (_, i) => ({
59
+ x: mainW,
60
+ y: y0 + i * tileH,
33
61
  w: COL,
34
- h: cellH,
62
+ h: tileH,
35
63
  })),
36
64
  };
37
65
  }
38
- const cols = cameras <= 1 ? 1 : 2;
39
- const rows = cameras <= 2 ? 1 : 2;
40
- const cellW = Math.floor((W - PAD * 2 - GAP * (cols - 1)) / cols);
41
- const cellH = Math.floor((H - PAD * 2 - GAP * (rows - 1)) / rows);
66
+ // Gallery: 3 cams → one row; otherwise pack 2 or 3 columns. Zero gaps, edge-to-edge.
67
+ const cols = n <= 3 ? n : n <= 4 ? 2 : 3;
68
+ const rows = Math.max(1, Math.ceil(n / cols));
69
+ const cellW = Math.floor(W / cols);
70
+ const cellH = Math.floor(H / rows);
42
71
  return {
43
- cameras: Array.from({ length: cameras }, (_, i) => ({
44
- x: PAD + (i % cols) * (cellW + GAP),
45
- y: PAD + Math.floor(i / cols) * (cellH + GAP),
46
- w: cellW,
47
- h: cellH,
48
- })),
72
+ cameras: Array.from({ length: n }, (_, i) => {
73
+ const col = i % cols;
74
+ const row = Math.floor(i / cols);
75
+ const x = col * cellW;
76
+ const y = row * cellH;
77
+ // Give leftover pixels to the last column / row so the mosaic reaches the canvas edge.
78
+ const w = col === cols - 1 ? W - x : cellW;
79
+ const h = row === rows - 1 ? H - y : cellH;
80
+ return { x, y, w, h };
81
+ }),
49
82
  };
50
83
  }
51
84
 
@@ -73,6 +106,7 @@ export function tracksFromTiles(tiles) {
73
106
  if (!item?.stream) continue;
74
107
  const participantKey = item.local ? "local" : (item.publisherId || item.displayName || item.producerId);
75
108
  const crop = normalizeVideoCrop(item.crop);
109
+ const displayName = String(item.displayName || "").trim().slice(0, 40);
76
110
  for (const track of item.stream.getTracks()) {
77
111
  if (track.readyState === "ended") continue;
78
112
  const source = item.source === "screen" && track.kind === "audio" ? "screen-audio" : item.source;
@@ -82,6 +116,7 @@ export function tracksFromTiles(tiles) {
82
116
  kind: track.kind,
83
117
  isLocal: Boolean(item.local),
84
118
  track,
119
+ ...(displayName ? { displayName } : {}),
85
120
  ...(crop && track.kind === "video" ? { crop } : {}),
86
121
  });
87
122
  }
@@ -89,6 +124,27 @@ export function tracksFromTiles(tiles) {
89
124
  return out;
90
125
  }
91
126
 
127
+ function resolveTileLabel(slot, selfName) {
128
+ const fromSlot = String(slot?.displayName || "").trim();
129
+ if (fromSlot) return fromSlot.slice(0, 40);
130
+ if (slot?.isLocal) return String(selfName || "Host").slice(0, 40);
131
+ const key = String(slot?.participantKey || "").trim();
132
+ if (key && key !== "local") return key.slice(0, 40);
133
+ return "Guest";
134
+ }
135
+
136
+ function hasLiveMic(slot, mics) {
137
+ if (!mics || typeof mics.has !== "function") return false;
138
+ if (slot?.isLocal) return mics.has("local-mic");
139
+ const key = String(slot?.participantKey || "").trim();
140
+ if (!key) return false;
141
+ return mics.has(`${key}|mic`);
142
+ }
143
+
144
+ function isPresenterSlot(slot, label) {
145
+ return Boolean(slot?.isLocal) || /presenter/i.test(String(label || ""));
146
+ }
147
+
92
148
  /** Screen share and custom video (e.g. whiteboard) use the large featured slot. */
93
149
  function isFeaturedVideoSource(source) {
94
150
  return source === "screen" || (source && source !== "webcam");
@@ -113,7 +169,7 @@ export class CanvasRecorder {
113
169
  return typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mime);
114
170
  }
115
171
 
116
- constructor({ webinarId, webinarName, recordingId, endpoint, token, selfName, onCaptureChange, onFailure }) {
172
+ constructor({ webinarId, webinarName, recordingId, endpoint, token, selfName, canvasBackground, onCaptureChange, onFailure }) {
117
173
  this.webinarId = webinarId;
118
174
  this.webinarName = webinarName || webinarId;
119
175
  this.recordingId = recordingId;
@@ -122,6 +178,7 @@ export class CanvasRecorder {
122
178
  this.stagePeople = null;
123
179
  this.token = token || "";
124
180
  this.selfName = String(selfName || "Host").slice(0, 40);
181
+ this.canvasBackground = String(canvasBackground || "").trim() || "#2563eb";
125
182
  this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
126
183
  this.onFailure = typeof onFailure === "function" ? onFailure : () => {};
127
184
  this.segment = 0;
@@ -188,9 +245,18 @@ export class CanvasRecorder {
188
245
  try {
189
246
  // Start chunks immediately (placeholder stage + silence until real media appears).
190
247
  await this.prepare(this.audio);
191
- if (this.finishing) return;
248
+ if (this.finishing) {
249
+ markReady();
250
+ return;
251
+ }
192
252
  await this.updateCapture();
193
- if (this.finishing) return;
253
+ if (this.finishing) {
254
+ markReady();
255
+ return;
256
+ }
257
+ // Resolve start() only after the first segment opens (or prepare finishes when paused),
258
+ // so "recording is already finished" and similar errors reach startRecording().
259
+ markReady();
194
260
  await this.untilStop;
195
261
  } catch (err) {
196
262
  fail(err);
@@ -205,11 +271,9 @@ export class CanvasRecorder {
205
271
  this.teardown();
206
272
  return;
207
273
  }
208
- markReady();
209
274
  await run();
210
275
  });
211
276
  } else {
212
- markReady();
213
277
  void run();
214
278
  }
215
279
  await running;
@@ -358,6 +422,7 @@ export class CanvasRecorder {
358
422
  async api(method, path, body) {
359
423
  const res = await fetch(this.url(path), {
360
424
  method,
425
+ credentials: "include",
361
426
  headers: this.authHeaders({ "content-type": "application/json" }),
362
427
  body: body === undefined ? "{}" : JSON.stringify(body),
363
428
  });
@@ -387,11 +452,17 @@ export class CanvasRecorder {
387
452
  this.clock.connect(silence);
388
453
  silence.connect(this.dest);
389
454
  this.clock.start();
390
- const { compositor, reason } = await createWorkerCompositor({ width: W, height: H, fps: FPS, onError: (failure) => {
391
- this.compositorFailure = failure;
392
- window.dispatchEvent(new CustomEvent("mediascale:recording-error", { detail: { message: failure.message } }));
393
- void this.setWanted(false).catch(() => {});
394
- } });
455
+ const { compositor, reason } = await createWorkerCompositor({
456
+ width: W,
457
+ height: H,
458
+ fps: FPS,
459
+ background: this.canvasBackground,
460
+ onError: (failure) => {
461
+ this.compositorFailure = failure;
462
+ window.dispatchEvent(new CustomEvent("mediascale:recording-error", { detail: { message: failure.message } }));
463
+ void this.setWanted(false).catch(() => {});
464
+ },
465
+ });
395
466
  if (this.finishing) { compositor?.close(); return; }
396
467
  this.compositor = compositor;
397
468
  let video = compositor?.track;
@@ -400,8 +471,7 @@ export class CanvasRecorder {
400
471
  this.canvas.width = W;
401
472
  this.canvas.height = H;
402
473
  this.ctx = this.canvas.getContext("2d");
403
- this.ctx.fillStyle = "#000";
404
- this.ctx.fillRect(0, 0, W, H);
474
+ fillRadialBackground(this.ctx, 0, 0, W, H, this.canvasBackground);
405
475
  const url = URL.createObjectURL(new Blob([`let tick; onmessage = ({data}) => { clearInterval(tick); if (data) tick = setInterval(() => postMessage(0), ${Math.round(1000 / FPS)}); };`], { type: "text/javascript" }));
406
476
  const worker = new Worker(url);
407
477
  worker.onmessage = () => this.draw();
@@ -539,6 +609,7 @@ export class CanvasRecorder {
539
609
  isLocal: item.isLocal,
540
610
  participantKey: item.participantKey,
541
611
  source: item.source,
612
+ displayName: String(item.displayName || "").trim().slice(0, 40),
542
613
  order: this.orderOf(key),
543
614
  video: this.compositor ? null : this.videoFor(key, item.track),
544
615
  track: item.track,
@@ -548,7 +619,7 @@ export class CanvasRecorder {
548
619
  }
549
620
  const screen = [...screens.values()].find((slot) => slot.isLocal)
550
621
  ?? [...screens.values()].sort((a, b) => a.order - b.order)[0];
551
- const maxCams = screen ? 3 : 4;
622
+ const maxCams = MAX_STAGE_CAMERAS;
552
623
  const stage = Array.isArray(this.stagePeople) ? this.stagePeople : null;
553
624
  let chosen = [];
554
625
  const keepPlaceholders = new Set();
@@ -602,7 +673,12 @@ export class CanvasRecorder {
602
673
  const remotes = [...cameras.values()]
603
674
  .filter((slot) => !slot.isLocal)
604
675
  .sort((a, b) => a.order - b.order);
605
- chosen = (localCam ? [localCam, ...remotes] : remotes).slice(0, maxCams);
676
+ chosen = (localCam ? [localCam, ...remotes] : remotes)
677
+ .slice(0, maxCams)
678
+ .map((slot) => ({
679
+ ...slot,
680
+ displayName: resolveTileLabel(slot, this.selfName),
681
+ }));
606
682
  if (chosen.length === 0) {
607
683
  const name = this.selfName || "Host";
608
684
  const phKey = "placeholder|local";
@@ -621,16 +697,51 @@ export class CanvasRecorder {
621
697
  });
622
698
  }
623
699
  }
700
+ // Attach mic / presenter chrome onto camera slots for both compositor paths.
701
+ chosen = chosen.map((slot) => {
702
+ const label = resolveTileLabel(slot, this.selfName);
703
+ return {
704
+ ...slot,
705
+ displayName: label,
706
+ micMuted: !hasLiveMic(slot, mics),
707
+ presenter: isPresenterSlot(slot, label),
708
+ };
709
+ });
624
710
  this.prunePlaceholders(keepPlaceholders);
625
711
  this.slots = screen ? [screen, ...chosen] : chosen;
626
712
  if (this.compositor) {
627
713
  const layout = layoutSlots(chosen.length, Boolean(screen));
628
714
  this.compositor.setSources([
629
- ...(screen ? [{ key: screen.key, track: screen.track, rect: layout.screen, crop: screen.crop || null }] : []),
630
- ...chosen.map((slot, index) => ({ key: slot.key, track: slot.track, rect: layout.cameras[index], crop: null })),
715
+ ...(screen ? [{
716
+ key: screen.key,
717
+ track: screen.track,
718
+ rect: layout.screen,
719
+ crop: null,
720
+ label: "",
721
+ accent: false,
722
+ muted: false,
723
+ // Letterbox screenshare (no crop); bars use brand canvas blue.
724
+ fit: "contain",
725
+ fillStyle: this.canvasBackground || "#2563eb",
726
+ }] : []),
727
+ ...chosen.map((slot, index) => {
728
+ const rect = layout.cameras[index];
729
+ return {
730
+ key: slot.key,
731
+ track: slot.track,
732
+ rect,
733
+ crop: null,
734
+ label: slot.displayName,
735
+ // Presenter flag drives the name-pill label only (no tile borders).
736
+ accent: Boolean(slot.presenter),
737
+ radius: TILE_RADIUS,
738
+ muted: Boolean(slot.micMuted),
739
+ fit: "cover",
740
+ };
741
+ }),
631
742
  ]);
632
743
  }
633
- // Mix every mic (and screen audio). Overflow cameras stay off-layout but audible.
744
+ // Mix every mic (and screen audio). Video layout caps at MAX_STAGE_CAMERAS; audio has no cap.
634
745
  this.mixAudio(chosen, screen, mics, screenAudio);
635
746
  const liveKeys = new Set(this.slots.filter((slot) => slot.video).map((slot) => slot.key));
636
747
  for (const key of [...this.videos.keys()]) {
@@ -660,7 +771,8 @@ export class CanvasRecorder {
660
771
  const track = stream.getVideoTracks()[0];
661
772
  entry = { track, canvas, name, isLocal, redraw: null, timer: null };
662
773
  entry.redraw = () => {
663
- drawStagePlaceholder(ctx, 0, 0, canvas.width, canvas.height, entry.name, entry.isLocal);
774
+ // Full-frame synthetic track: avatar only. Tile chrome/name are drawn on the layout rect.
775
+ drawStagePlaceholder(ctx, 0, 0, canvas.width, canvas.height, entry.name, false, "#2563eb", { chrome: false });
664
776
  track.requestFrame?.();
665
777
  };
666
778
  entry.timer = setInterval(entry.redraw, Math.round(1000 / FPS));
@@ -750,25 +862,38 @@ export class CanvasRecorder {
750
862
  const cameras = this.slots.filter((slot) => slot.kind === "camera");
751
863
  const screen = this.slots.find((slot) => slot.kind === "screen");
752
864
  const layout = layoutSlots(cameras.length, Boolean(screen));
753
- this.ctx.fillStyle = "#000";
754
- this.ctx.fillRect(0, 0, W, H);
755
- if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen, screen.crop);
865
+ fillRadialBackground(this.ctx, 0, 0, W, H, this.canvasBackground);
866
+ if (screen && layout.screen) {
867
+ paint(this.ctx, screen.video, layout.screen, null, {
868
+ label: "",
869
+ accent: false,
870
+ accentColor: this.canvasBackground,
871
+ fit: "contain",
872
+ fillStyle: this.canvasBackground || "#2563eb",
873
+ });
874
+ }
756
875
  cameras.forEach((slot, index) => {
757
876
  const rect = layout.cameras[index];
758
877
  if (!rect) return;
878
+ const label = resolveTileLabel(slot, this.selfName);
879
+ const accent = slot.presenter != null ? Boolean(slot.presenter) : isPresenterSlot(slot, label);
880
+ const radius = TILE_RADIUS;
881
+ const muted = slot.micMuted != null ? Boolean(slot.micMuted) : false;
759
882
  if (slot.placeholder) {
760
- drawStagePlaceholder(
761
- this.ctx,
762
- rect.x,
763
- rect.y,
764
- rect.w,
765
- rect.h,
766
- slot.displayName || this.selfName,
767
- Boolean(slot.isLocal),
768
- );
883
+ drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, label, accent, PRESENTER_ACCENT, {
884
+ chrome: true,
885
+ radius,
886
+ muted,
887
+ });
769
888
  return;
770
889
  }
771
- paint(this.ctx, slot.video, rect, null);
890
+ paint(this.ctx, slot.video, rect, null, {
891
+ label,
892
+ accent,
893
+ accentColor: PRESENTER_ACCENT,
894
+ radius,
895
+ muted,
896
+ });
772
897
  });
773
898
  this.capture?.requestFrame();
774
899
  }
@@ -817,6 +942,7 @@ export class CanvasRecorder {
817
942
  const checksum = await sha256(row.blob);
818
943
  const res = await fetch(this.url(`/api/chunks/${this.recordingId}/${row.segment}/${row.seq}`), {
819
944
  method: "PUT",
945
+ credentials: "include",
820
946
  headers: this.authHeaders({ "content-type": "application/octet-stream", "x-checksum": checksum }),
821
947
  body: row.blob,
822
948
  });
@@ -833,6 +959,7 @@ export class CanvasRecorder {
833
959
  const durationMs = Date.now() - this.startedAt;
834
960
  fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
835
961
  method: "POST",
962
+ credentials: "include",
836
963
  headers: this.authHeaders({ "content-type": "application/json" }),
837
964
  body: JSON.stringify({ durationMs, force: true }),
838
965
  keepalive: true,
@@ -849,6 +976,7 @@ export class CanvasRecorder {
849
976
  for (let round = 0; round < 3; round += 1) {
850
977
  const res = await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
851
978
  method: "POST",
979
+ credentials: "include",
852
980
  headers: this.authHeaders({ "content-type": "application/json" }),
853
981
  body: JSON.stringify({ durationMs }),
854
982
  });
@@ -865,6 +993,7 @@ export class CanvasRecorder {
865
993
  if (!still) {
866
994
  await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
867
995
  method: "POST",
996
+ credentials: "include",
868
997
  headers: this.authHeaders({ "content-type": "application/json" }),
869
998
  body: JSON.stringify({ durationMs, force: true }),
870
999
  });
@@ -873,6 +1002,7 @@ export class CanvasRecorder {
873
1002
  }
874
1003
  await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
875
1004
  method: "POST",
1005
+ credentials: "include",
876
1006
  headers: this.authHeaders({ "content-type": "application/json" }),
877
1007
  body: JSON.stringify({ durationMs, force: true }),
878
1008
  });
@@ -924,12 +1054,19 @@ function placeholderLetter(name) {
924
1054
  }
925
1055
 
926
1056
  /**
927
- * Empty-stage tile for the recording canvas:
928
- * maroon radial field, solid #e30096 name round (no border), white initial, name top-left.
1057
+ * Empty-stage tile: magenta avatar field. With chrome: rounded border + name pill (signal / mute icons).
929
1058
  */
930
- function drawStagePlaceholder(ctx, x, y, w, h, name, _isLocal) {
1059
+ function drawStagePlaceholder(ctx, x, y, w, h, name, accent = false, accentColor = PRESENTER_ACCENT, options = {}) {
1060
+ const chrome = options.chrome !== false;
1061
+ const corner = options.radius ?? TILE_RADIUS;
1062
+ const muted = Boolean(options.muted);
931
1063
  const cx = Math.round(x + w / 2);
932
1064
  const cy = Math.round(y + h / 2);
1065
+ ctx.save();
1066
+ if (chrome && corner > 0) {
1067
+ roundedRectPath(ctx, x, y, w, h, corner);
1068
+ ctx.clip();
1069
+ }
933
1070
  const span = Math.max(w, h) * 0.75;
934
1071
  const field = ctx.createRadialGradient(cx, cy, 0, cx, cy, span);
935
1072
  field.addColorStop(0, "rgb(152, 62, 107)");
@@ -938,40 +1075,56 @@ function drawStagePlaceholder(ctx, x, y, w, h, name, _isLocal) {
938
1075
  ctx.fillStyle = field;
939
1076
  ctx.fillRect(x, y, w, h);
940
1077
 
941
- const diameter = Math.round(Math.min(128, Math.max(88, Math.min(w, h) * 0.18)));
942
- const radius = diameter / 2;
1078
+ const diameter = Math.round(Math.min(128, Math.max(72, Math.min(w, h) * 0.28)));
1079
+ const avatarR = diameter / 2;
943
1080
  ctx.beginPath();
944
- ctx.arc(cx, cy, radius, 0, Math.PI * 2);
1081
+ ctx.arc(cx, cy, avatarR, 0, Math.PI * 2);
945
1082
  ctx.fillStyle = "#e30096";
946
1083
  ctx.fill();
947
1084
 
948
- const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 28), 45));
1085
+ const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 22), 45));
949
1086
  ctx.fillStyle = "#ffffff";
950
1087
  ctx.font = `600 ${letterPx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
951
1088
  ctx.textAlign = "center";
952
1089
  ctx.textBaseline = "middle";
953
1090
  ctx.fillText(placeholderLetter(name), cx, cy + 1);
1091
+ ctx.restore();
954
1092
 
955
- const label = String(name || "Host").slice(0, 40);
956
- const padX = Math.max(14, Math.round(w * 0.016));
957
- const padY = Math.max(14, Math.round(h * 0.024));
958
- const namePx = Math.round(Math.min(Math.max(h * 0.028, 14), 18));
959
- ctx.textAlign = "left";
960
- ctx.textBaseline = "top";
961
- ctx.font = `500 ${namePx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
962
- ctx.fillStyle = "#ffffff";
963
- ctx.fillText(label, x + padX, y + padY);
1093
+ if (!chrome) return;
1094
+ if (corner > 0) strokeTileBorder(ctx, x, y, w, h, corner, { accent, accentColor });
1095
+ drawNamePill(ctx, x, y, w, h, name, { presenter: accent, muted });
964
1096
  }
965
1097
 
966
- function paint(ctx, video, rect, crop) {
967
- ctx.fillStyle = "#000";
968
- ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
969
- if (!video || video.readyState < 2 || !video.videoWidth) return;
1098
+ function paint(ctx, video, rect, crop, options = {}) {
1099
+ const label = options.label || "";
1100
+ const accent = Boolean(options.accent);
1101
+ const accentColor = options.accentColor || PRESENTER_ACCENT;
1102
+ const radius = options.radius ?? TILE_RADIUS;
1103
+ const muted = Boolean(options.muted);
1104
+ const fit = options.fit === "contain" ? "contain" : "cover";
1105
+ const fillStyle = options.fillStyle || "#0f172a";
1106
+ if (!video || video.readyState < 2 || !video.videoWidth) {
1107
+ paintRoundedTile(ctx, {
1108
+ source: null,
1109
+ rect,
1110
+ sw: 0,
1111
+ sh: 0,
1112
+ label,
1113
+ accent,
1114
+ accentColor,
1115
+ radius,
1116
+ muted,
1117
+ fit,
1118
+ fillStyle,
1119
+ });
1120
+ return;
1121
+ }
970
1122
  let sx = 0;
971
1123
  let sy = 0;
972
1124
  let sw = video.videoWidth;
973
1125
  let sh = video.videoHeight;
974
- const cropNorm = normalizeVideoCrop(crop);
1126
+ // Screenshare uses contain (no crop). Camera tiles may still honor a stage crop.
1127
+ const cropNorm = fit === "contain" ? null : normalizeVideoCrop(crop);
975
1128
  if (cropNorm) {
976
1129
  sx = cropNorm.x * video.videoWidth;
977
1130
  sy = cropNorm.y * video.videoHeight;
@@ -979,14 +1132,21 @@ function paint(ctx, video, rect, crop) {
979
1132
  sh = cropNorm.h * video.videoHeight;
980
1133
  if (sw <= 1 || sh <= 1) return;
981
1134
  }
982
- // Contain (not stretch): keep source aspect ratio inside the destination slot.
983
- const scale = Math.min(rect.w / sw, rect.h / sh);
984
- const dw = sw * scale;
985
- const dh = sh * scale;
986
- const prev = ctx.imageSmoothingEnabled;
987
- ctx.imageSmoothingEnabled = scale < 0.98;
988
- ctx.drawImage(video, sx, sy, sw, sh, rect.x + (rect.w - dw) / 2, rect.y + (rect.h - dh) / 2, dw, dh);
989
- ctx.imageSmoothingEnabled = prev;
1135
+ paintRoundedTile(ctx, {
1136
+ source: video,
1137
+ rect,
1138
+ sx,
1139
+ sy,
1140
+ sw,
1141
+ sh,
1142
+ label,
1143
+ accent,
1144
+ accentColor,
1145
+ radius,
1146
+ muted,
1147
+ fit,
1148
+ fillStyle,
1149
+ });
990
1150
  }
991
1151
 
992
1152
  function sleep(ms) {