mediascale-sdk 1.0.6 → 1.0.8

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.
@@ -1,4 +1,4 @@
1
- # Use the SDK in Next.js
1
+ # Use the SDK in Next.js ( v1.0.6 )
2
2
 
3
3
  One address talks to Mediascale. The default is `http://localhost:8080`.
4
4
 
@@ -59,7 +59,7 @@ export async function POST(request) {
59
59
  }
60
60
  ```
61
61
 
62
- `role` is `host` or `audience`. Both can publish. Only the host should drive recording in the UI.
62
+ `role` is `host` or `audience` for the SDK/portal token. Only the host should drive recording in the UI.
63
63
 
64
64
  Token claims the SDK reads:
65
65
 
@@ -71,16 +71,55 @@ Token claims the SDK reads:
71
71
  | `recording` | When `true` on a **host** token, auto-start recording on `connect()` unless `createClient({ recording: false })` |
72
72
  | `exp` | Expiry as a Unix timestamp in **milliseconds** |
73
73
 
74
+ ### Sample stage roles (meet UI)
75
+
76
+ The sample room keeps JWT `host` / `audience` for auth, and adds a **stage role** in the demo UI: `host`, `co-host`, `speaker`, `participant`.
77
+
78
+ - **Host** (and co-host) see every participant and can **Make Speaker**, **Make co-host**, or **Block**.
79
+ - **Participants** see only people on stage (speakers / host / co-host).
80
+ - Only host, co-host, and speaker may publish camera, mic, screen, or whiteboard.
81
+
82
+ Webinar / product apps usually already manage join, leave, and stage membership on their side. You do **not** need the SDK roster callbacks (`onUserJoined`, `onUserLeft`, etc.) for that. What you **do** need for recording parity is below.
83
+
84
+ ### Recording must match the live stage
85
+
86
+ The recorder only knows about **published media** unless you tell it who is on stage. If a speaker is on stage without a camera, participants see their avatar — the recording must show that same avatar until video starts.
87
+
88
+ Whenever your stage layout changes (someone promoted, demoted, or leaves stage), push the same people you show in the live UI:
89
+
90
+ ```js
91
+ // Same order / membership as the participant stage tiles.
92
+ client.setRecordingStage([
93
+ { id: hostPeerId, name: "Alex", local: true },
94
+ { id: speakerPeerId, name: "Rakesh", local: false },
95
+ ]);
96
+ ```
97
+
98
+ | Field | Meaning |
99
+ | --- | --- |
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 |
102
+ | `local` | `true` for this browser’s own tile |
103
+
104
+ Rules:
105
+
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**.
108
+ - Pass `[]` to clear the stage list; you normally keep at least the people currently on stage.
109
+ - `onStageChanged(people)` is optional if you only care about driving the recorder from your own stage state.
110
+
111
+ Without `setRecordingStage`, recording falls back to live tracks only (plus a single host placeholder when nobody is publishing) — so off-stage speakers without video will be **missing** from the file.
112
+
74
113
  ## 2. Copy the room page
75
114
 
76
115
  Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file are the steps.
77
116
 
78
117
  1. **Join** asks your server for a token, then calls `connect()` and `subscribe()`. The camera, microphone, and screen stay off.
79
- 2. **Camera** calls `startCamera()` or `stopCamera()`. Optionally pass your own live video track, or call `replaceCameraTrack(track)` to hot-swap devices without unpublishing.
118
+ 2. **Camera** calls `startCamera()` or `stopCamera()` (sample: only when on stage as host/co-host/speaker). Optionally pass your own live video track, or call `replaceCameraTrack(track)` to hot-swap devices without unpublishing.
80
119
  3. **Mic** calls `startMicrophone()` or `stopMicrophone()` (and `replaceMicrophoneTrack` to switch devices smoothly).
81
120
  4. **Screen** calls `startScreenShare()` or `stopScreenShare()`.
82
121
  5. **Custom stream** (optional) — see [Custom streams](#custom-streams) (`startCustomStream` / `stopCustomStream`), for example a whiteboard tab capture.
83
- 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.
122
+ 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.
84
123
  7. **End** leaves the session and saves the recording if this person was recording.
85
124
 
86
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).
@@ -173,6 +212,10 @@ await client.end(); // combines every segment into one file
173
212
  | `stop()` | Turns off the camera and the microphone. The screen share stays on. |
174
213
  | `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. |
175
214
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
215
+ | `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. |
216
+ | `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). |
217
+ | `getPeerId()` | Socket peer id for this browser after `connect()`. |
218
+ | `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. |
176
219
  | `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
177
220
  | `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
178
221
 
@@ -190,6 +233,8 @@ Pass these to `createClient`.
190
233
  | `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
191
234
  | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
192
235
  | `onActiveSpeaker({ peerId, displayName, producerId, local })` | Fires when the loudest mic in the room changes. `peerId` is `null` when nobody is speaking. `local` is true when it is this browser. Requires `ACTIVE_SPEAKER_DETECTION=true` on the origin SFU and portal. |
236
+ | `onStageChanged(people)` | Optional. Fires when the recording stage list changes after `setRecordingStage` (or sample roster updates). |
237
+ | `onUserList` / `onUserJoined` / `onUserLeft` / `onUserUpdated` / `onUserBlocked` | Optional portal roster events for the sample meet UI. Not required if your webinar app manages join/leave/stage itself — use `setRecordingStage` instead. |
193
238
 
194
239
  ## Active speaker
195
240
 
@@ -269,6 +314,13 @@ const client = createClient({
269
314
 
270
315
  Optional: broadcast the publisher’s whiteboard DOM bounds (normalized `x,y,w,h` vs the viewport) over your own channel so viewers can crop the full-tab capture to only the whiteboard area. See the sample app for that pattern.
271
316
 
317
+ Pass the same crop into the recorder so the recording file matches what subscribers see (not the full browser tab):
318
+
319
+ ```js
320
+ client.setRecordingCrop("whiteboard", { x, y, w, h }); // 0..1 vs captured frame
321
+ client.setRecordingCrop("whiteboard", null); // clear
322
+ ```
323
+
272
324
  ## Recording
273
325
 
274
326
  ### When it starts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
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
@@ -1,6 +1,6 @@
1
1
  import { Device } from "mediasoup-client";
2
2
  import { io } from "socket.io-client";
3
- import { CanvasRecorder, recordingWebinarId, tracksFromTiles } from "./record.js";
3
+ import { CanvasRecorder, normalizeVideoCrop, recordingWebinarId, tracksFromTiles } from "./record.js";
4
4
 
5
5
  const SIZES = {
6
6
  "480p": { width: 854, height: 480 },
@@ -65,6 +65,12 @@ export function createClient(options = {}) {
65
65
  const onError = options.onError || (() => {});
66
66
  const onRecording = options.onRecording || (() => {});
67
67
  const onActiveSpeaker = options.onActiveSpeaker || (() => {});
68
+ const onUserJoined = options.onUserJoined || (() => {});
69
+ const onUserLeft = options.onUserLeft || (() => {});
70
+ const onUserUpdated = options.onUserUpdated || (() => {});
71
+ const onUserList = options.onUserList || (() => {});
72
+ const onUserBlocked = options.onUserBlocked || (() => {});
73
+ const onStageChanged = options.onStageChanged || (() => {});
68
74
 
69
75
  if (!sessionId) throw new Error("sessionId is required");
70
76
  if (!token) throw new Error("token is required");
@@ -87,10 +93,82 @@ export function createClient(options = {}) {
87
93
  let selfPeerId = null;
88
94
  const locals = new Map();
89
95
  const tiles = new Map();
96
+ /** source id → normalized crop for recording compositor (e.g. whiteboard). */
97
+ const recordingCrops = new Map();
98
+ /** peerId → { id, name, local } for people currently on stage (from roster or setRecordingStage). */
99
+ const stageById = new Map();
100
+ /** When set, parent-provided stage list wins over roster-derived stageById. */
101
+ let stageOverride = null;
102
+ let lastStageSig = "";
90
103
  const pending = [];
91
104
  let readyPromise = null;
92
105
  let settleReady = null;
93
106
 
107
+ function userOnStage(user) {
108
+ if (!user) return false;
109
+ if (user.onStage != null) return Boolean(user.onStage);
110
+ const role = String(user.stageRole || "").trim().toLowerCase();
111
+ return role === "host" || role === "co-host" || role === "speaker";
112
+ }
113
+
114
+ function normalizeStagePerson(person) {
115
+ if (!person) return null;
116
+ const id = String(person.id || "").trim();
117
+ const name = String(person.name || "Guest").trim().slice(0, 40) || "Guest";
118
+ if (!id && !name) return null;
119
+ return {
120
+ id,
121
+ name,
122
+ local: Boolean(person.local) || Boolean(id && selfPeerId && id === selfPeerId),
123
+ };
124
+ }
125
+
126
+ function stagePeopleForRecording() {
127
+ if (stageOverride) return stageOverride;
128
+ return [...stageById.values()];
129
+ }
130
+
131
+ function emitStageChanged() {
132
+ const people = stagePeopleForRecording();
133
+ const sig = people.map((p) => `${p.id}|${p.name}|${p.local ? 1 : 0}`).join(";");
134
+ if (sig === lastStageSig) return;
135
+ lastStageSig = sig;
136
+ onStageChanged(people);
137
+ }
138
+
139
+ function ingestRosterUsers(users) {
140
+ if (!Array.isArray(users)) return;
141
+ stageById.clear();
142
+ for (const user of users) {
143
+ if (!userOnStage(user)) continue;
144
+ const person = normalizeStagePerson(user);
145
+ if (!person?.id) continue;
146
+ stageById.set(person.id, person);
147
+ }
148
+ emitStageChanged();
149
+ syncRecording();
150
+ }
151
+
152
+ function ingestRosterUser(user) {
153
+ if (!user?.id) return;
154
+ if (userOnStage(user)) {
155
+ const person = normalizeStagePerson(user);
156
+ if (person?.id) stageById.set(person.id, person);
157
+ } else {
158
+ stageById.delete(String(user.id));
159
+ }
160
+ emitStageChanged();
161
+ syncRecording();
162
+ }
163
+
164
+ function removeRosterUser(user) {
165
+ const id = String(user?.id || "").trim();
166
+ if (!id) return;
167
+ if (!stageById.delete(id)) return;
168
+ emitStageChanged();
169
+ syncRecording();
170
+ }
171
+
94
172
  function clientHints() {
95
173
  if (typeof navigator === "undefined") return {};
96
174
  const ua = String(navigator.userAgent || "");
@@ -100,8 +178,59 @@ export function createClient(options = {}) {
100
178
  return { userAgent: ua, mobile, desktop: !mobile, chrome };
101
179
  }
102
180
 
181
+ function tracksForRecording() {
182
+ const tracks = tracksFromTiles([...tiles.values()]);
183
+ for (const item of tracks) {
184
+ if (item.kind !== "video") continue;
185
+ const crop = recordingCrops.get(item.source);
186
+ if (crop) item.crop = crop;
187
+ }
188
+ return tracks;
189
+ }
190
+
103
191
  function syncRecording() {
104
- recorder?.sync(tracksFromTiles([...tiles.values()]));
192
+ recorder?.sync(tracksForRecording(), stagePeopleForRecording());
193
+ }
194
+
195
+ /**
196
+ * Tell the recorder who belongs on stage (same tiles participants see).
197
+ * Each person is `{ id, name, local? }`. When they publish webcam, that tile becomes video.
198
+ * Pass `null` to fall back to the socket roster; pass `[]` for an empty stage.
199
+ */
200
+ function setRecordingStage(people) {
201
+ if (people == null) {
202
+ stageOverride = null;
203
+ } else {
204
+ const next = [];
205
+ const seen = new Set();
206
+ for (const raw of Array.isArray(people) ? people : []) {
207
+ const person = normalizeStagePerson(raw);
208
+ if (!person) continue;
209
+ const key = person.id || `name:${person.name.toLowerCase()}`;
210
+ if (seen.has(key)) continue;
211
+ seen.add(key);
212
+ next.push(person);
213
+ }
214
+ stageOverride = next;
215
+ }
216
+ emitStageChanged();
217
+ syncRecording();
218
+ }
219
+
220
+ /**
221
+ * Crop a video source in the recording layout (same `{ x, y, w, h }` 0..1 bounds the
222
+ * sample app uses for subscriber whiteboard CSS crop). Pass null to clear.
223
+ */
224
+ function setRecordingCrop(source, crop) {
225
+ const id = String(source || "").trim();
226
+ if (!id) return;
227
+ const next = normalizeVideoCrop(crop);
228
+ if (!next) recordingCrops.delete(id);
229
+ else recordingCrops.set(id, next);
230
+ if (recorder) {
231
+ recorder.setVideoCrop(id, next);
232
+ syncRecording();
233
+ }
105
234
  }
106
235
 
107
236
  async function consume(params) {
@@ -277,6 +406,24 @@ export function createClient(options = {}) {
277
406
  local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
278
407
  });
279
408
  });
409
+ socket.on("userJoined", (user) => {
410
+ if (closed) return;
411
+ ingestRosterUser(user);
412
+ onUserJoined(user);
413
+ });
414
+ socket.on("userLeft", (user) => {
415
+ if (closed) return;
416
+ removeRosterUser(user);
417
+ onUserLeft(user);
418
+ });
419
+ socket.on("userUpdated", (user) => {
420
+ if (closed) return;
421
+ ingestRosterUser(user);
422
+ onUserUpdated(user);
423
+ });
424
+ socket.on("userBlocked", (payload) => {
425
+ if (!closed) onUserBlocked(payload || {});
426
+ });
280
427
  socket.on("connect", async () => {
281
428
  try {
282
429
  if (closed) return;
@@ -289,6 +436,10 @@ export function createClient(options = {}) {
289
436
  });
290
437
  selfPeerId = joined.peerId || null;
291
438
  iceServers = iceOverride || joined.iceServers || [];
439
+ if (Array.isArray(joined.users)) {
440
+ ingestRosterUsers(joined.users);
441
+ onUserList(joined.users);
442
+ }
292
443
  device = new Device();
293
444
  await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
294
445
 
@@ -327,6 +478,16 @@ export function createClient(options = {}) {
327
478
  });
328
479
  const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
329
480
  for (const params of started.consumers || []) await play(params);
481
+ // Fresh roster after ready (covers anyone who joined during transport setup).
482
+ try {
483
+ const list = await emit(socket, "getUserList", {});
484
+ if (Array.isArray(list?.users)) {
485
+ ingestRosterUsers(list.users);
486
+ onUserList(list.users);
487
+ }
488
+ } catch {
489
+ /* roster optional if portal is older */
490
+ }
330
491
  if (joined.waiting) onStatus("Please wait, we will connect you soon");
331
492
  else onStatus("Ready");
332
493
  if (closed) return;
@@ -346,6 +507,40 @@ export function createClient(options = {}) {
346
507
  return readyPromise;
347
508
  }
348
509
 
510
+ async function getUserList() {
511
+ await connect();
512
+ if (!socket?.connected) throw new Error("Not connected");
513
+ const result = await emit(socket, "getUserList", {});
514
+ if (result?.error) throw new Error(result.error);
515
+ const users = Array.isArray(result?.users) ? result.users : [];
516
+ ingestRosterUsers(users);
517
+ onUserList(users);
518
+ return users;
519
+ }
520
+
521
+ async function updateSelf(patch = {}) {
522
+ await connect();
523
+ if (!socket?.connected) throw new Error("Not connected");
524
+ const result = await emit(socket, "updateSelf", patch);
525
+ if (result?.error) throw new Error(result.error);
526
+ return result?.user || null;
527
+ }
528
+
529
+ async function stageAction(action, targetId) {
530
+ await connect();
531
+ if (!socket?.connected) throw new Error("Not connected");
532
+ const result = await emit(socket, "stageAction", { action, targetId });
533
+ if (result?.error) throw new Error(result.error);
534
+ if (Array.isArray(result?.users)) {
535
+ ingestRosterUsers(result.users);
536
+ onUserList(result.users);
537
+ } else if (result?.user) {
538
+ ingestRosterUser(result.user);
539
+ onUserUpdated(result.user);
540
+ }
541
+ return result;
542
+ }
543
+
349
544
  async function startCamera({ cameraId, resolution, track } = {}) {
350
545
  if (track !== undefined) requireLiveTrack(track, "video");
351
546
  await connect();
@@ -568,7 +763,8 @@ export function createClient(options = {}) {
568
763
  recorder = next;
569
764
  next.wanted = true;
570
765
  notifyRecording(next);
571
- next.sync(tracksFromTiles([...tiles.values()]));
766
+ for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
767
+ next.sync(tracksForRecording(), stagePeopleForRecording());
572
768
  try {
573
769
  await next.start();
574
770
  } catch (error) {
@@ -666,6 +862,12 @@ export function createClient(options = {}) {
666
862
  subscribe: guard(subscribe),
667
863
  startRecording: guard(startRecording),
668
864
  stopRecording: guard(stopRecording),
865
+ setRecordingCrop,
866
+ setRecordingStage,
867
+ getUserList: guard(getUserList),
868
+ updateSelf: guard(updateSelf),
869
+ stageAction: guard(stageAction),
870
+ getPeerId: () => selfPeerId,
669
871
  end: guard(end),
670
872
  listDevices: guard(listDevices),
671
873
  };
@@ -83,16 +83,16 @@ 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 }) => {
86
+ const updates = desired.map(({ key, track, rect, crop }) => {
87
87
  const previous = owned.get(key);
88
- if (previous?.original === track) return { key, rect };
88
+ if (previous?.original === track) return { key, rect, crop: crop || null };
89
89
  if (previous) release(previous);
90
90
  const clone = track.clone();
91
91
  owned.set(key, { clone, original: track });
92
- if (standard) { transfer.push(clone); return { key, rect, track: clone }; }
92
+ if (standard) { transfer.push(clone); return { key, rect, crop: crop || null, track: clone }; }
93
93
  const readable = new MediaStreamTrackProcessor({ track: clone, maxBufferSize: 1 }).readable;
94
94
  transfer.push(readable);
95
- return { key, rect, readable };
95
+ return { key, rect, crop: crop || null, readable };
96
96
  });
97
97
  worker.postMessage({ type: "sources", sources: updates }, transfer);
98
98
  };
@@ -53,14 +53,28 @@ export class FrameCompositor {
53
53
  if (!this.active || !this.dirty || this.writing || now - this.lastDraw < this.interval) return;
54
54
  this.ctx.fillStyle = "#000";
55
55
  this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
56
- for (const { key, rect } of this.sources) {
56
+ for (const { key, rect, crop } of this.sources) {
57
57
  const frame = this.frames.get(key);
58
58
  if (!frame) continue;
59
59
  const width = frame.displayWidth || frame.codedWidth || rect.w;
60
60
  const height = frame.displayHeight || frame.codedHeight || rect.h;
61
- const scale = Math.min(rect.w / width, rect.h / height);
62
- const w = width * scale, h = height * scale;
63
- this.ctx.drawImage(frame, rect.x + (rect.w - w) / 2, rect.y + (rect.h - h) / 2, w, h);
61
+ let sx = 0;
62
+ let sy = 0;
63
+ let sw = width;
64
+ let sh = height;
65
+ const c = crop && crop.w > 0 && crop.h > 0 ? crop : null;
66
+ if (c) {
67
+ sx = c.x * width;
68
+ sy = c.y * height;
69
+ sw = c.w * width;
70
+ sh = c.h * height;
71
+ if (sw <= 1 || sh <= 1) continue;
72
+ }
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);
64
78
  }
65
79
  this.timestamp = Math.max(this.timestamp + 1, Math.round((now - this.startedAt) * 1000));
66
80
  const frame = this.makeFrame(this.canvas, { timestamp: this.timestamp });
@@ -69,7 +69,7 @@ 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 }) => ({ key, rect })));
72
+ compositor.setSources(data.sources.map(({ key, rect, crop }) => ({ key, rect, crop: crop || null })));
73
73
  for (const source of data.sources) {
74
74
  if (!source.readable && !source.track) continue;
75
75
  remove(source.key);
package/src/record.js CHANGED
@@ -8,7 +8,8 @@ const PAD = 8;
8
8
  const GAP = 8;
9
9
  const FPS = 15;
10
10
  const SLICE_MS = 5000;
11
- const BITRATE = 2_000_000;
11
+ /** Higher bitrate keeps sharp avatar/text edges; 2 Mbps made placeholders look blurry. */
12
+ const BITRATE = 4_500_000;
12
13
  const mime = "video/webm;codecs=vp8,opus";
13
14
 
14
15
  /** Channel ids become a single path segment. The original text stays the webinar name. */
@@ -48,12 +49,30 @@ export function layoutSlots(cameras, screen) {
48
49
  };
49
50
  }
50
51
 
52
+ /** Normalized viewport crop `{ x, y, w, h }` in 0..1 (same as sample presence / subscriber CSS crop). */
53
+ export function normalizeVideoCrop(raw) {
54
+ if (!raw || typeof raw !== "object") return null;
55
+ const x = Number(raw.x);
56
+ const y = Number(raw.y);
57
+ const w = Number(raw.w);
58
+ const h = Number(raw.h);
59
+ if (![x, y, w, h].every((n) => Number.isFinite(n))) return null;
60
+ if (w <= 0 || h <= 0) return null;
61
+ return {
62
+ x: Math.min(1, Math.max(0, x)),
63
+ y: Math.min(1, Math.max(0, y)),
64
+ w: Math.min(1, Math.max(0.01, w)),
65
+ h: Math.min(1, Math.max(0.01, h)),
66
+ };
67
+ }
68
+
51
69
  /** One entry per mediasoup track the stage is showing. */
52
70
  export function tracksFromTiles(tiles) {
53
71
  const out = [];
54
72
  for (const item of tiles) {
55
73
  if (!item?.stream) continue;
56
74
  const participantKey = item.local ? "local" : (item.publisherId || item.displayName || item.producerId);
75
+ const crop = normalizeVideoCrop(item.crop);
57
76
  for (const track of item.stream.getTracks()) {
58
77
  if (track.readyState === "ended") continue;
59
78
  const source = item.source === "screen" && track.kind === "audio" ? "screen-audio" : item.source;
@@ -63,6 +82,7 @@ export function tracksFromTiles(tiles) {
63
82
  kind: track.kind,
64
83
  isLocal: Boolean(item.local),
65
84
  track,
85
+ ...(crop && track.kind === "video" ? { crop } : {}),
66
86
  });
67
87
  }
68
88
  }
@@ -98,6 +118,8 @@ export class CanvasRecorder {
98
118
  this.webinarName = webinarName || webinarId;
99
119
  this.recordingId = recordingId;
100
120
  this.endpoint = String(endpoint || "").replace(/\/+$/, "");
121
+ /** @type {{ id: string, name: string, local?: boolean }[] | null} */
122
+ this.stagePeople = null;
101
123
  this.token = token || "";
102
124
  this.selfName = String(selfName || "Host").slice(0, 40);
103
125
  this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
@@ -112,6 +134,8 @@ export class CanvasRecorder {
112
134
  this.videos = new Map();
113
135
  this.audioNodes = new Map();
114
136
  this.placeholderSources = new Map();
137
+ /** source id → normalized crop for featured video (e.g. whiteboard tab capture). */
138
+ this.videoCrops = new Map();
115
139
  this.tries = new Map();
116
140
  this.chain = Promise.resolve();
117
141
  this.pendingStores = new Set();
@@ -210,12 +234,47 @@ export class CanvasRecorder {
210
234
  for (const type of events) window.addEventListener(type, unlock, true);
211
235
  }
212
236
 
213
- sync(tracks) {
237
+ /**
238
+ * @param {object[]} tracks live mediasoup tracks
239
+ * @param {{ id?: string, name?: string, local?: boolean }[] | null} [stagePeople]
240
+ * People who should appear on the recording stage (avatar until their webcam arrives).
241
+ * Pass null/omit to keep the previous list; pass [] to clear.
242
+ */
243
+ sync(tracks, stagePeople) {
214
244
  this.tracks = tracks || [];
245
+ if (stagePeople !== undefined) {
246
+ this.stagePeople = Array.isArray(stagePeople)
247
+ ? stagePeople
248
+ .map((person) => ({
249
+ id: String(person?.id || "").trim(),
250
+ name: String(person?.name || "Guest").trim().slice(0, 40) || "Guest",
251
+ local: Boolean(person?.local),
252
+ }))
253
+ .filter((person) => person.id || person.name)
254
+ : null;
255
+ }
256
+ for (const item of this.tracks) {
257
+ if (item?.kind !== "video" || !item.source) continue;
258
+ const crop = normalizeVideoCrop(item.crop);
259
+ if (crop) this.videoCrops.set(item.source, crop);
260
+ }
215
261
  if (this.prepared) this.retile();
216
262
  void this.updateCapture();
217
263
  }
218
264
 
265
+ /**
266
+ * Crop a published video source when compositing (same normalized bounds as the sample
267
+ * subscriber whiteboard crop: `{ x, y, w, h }` relative to the full captured frame).
268
+ */
269
+ setVideoCrop(source, crop) {
270
+ const id = String(source || "").trim();
271
+ if (!id) return;
272
+ const next = normalizeVideoCrop(crop);
273
+ if (!next) this.videoCrops.delete(id);
274
+ else this.videoCrops.set(id, next);
275
+ if (this.prepared) this.retile();
276
+ }
277
+
219
278
  updateCapture() {
220
279
  const run = this.captureGate.then(async () => {
221
280
  if (this.finishing || !this.prepared) return;
@@ -470,50 +529,103 @@ export class CanvasRecorder {
470
529
  if (!featured && item.source !== "webcam") continue;
471
530
  const kind = featured ? "screen" : "camera";
472
531
  const key = `${item.participantKey}|${kind}`;
532
+ const crop = normalizeVideoCrop(item.crop) || this.videoCrops.get(item.source) || null;
533
+ if (crop) this.videoCrops.set(item.source, crop);
473
534
  const slot = {
474
535
  key,
475
536
  kind,
476
537
  isLocal: item.isLocal,
477
538
  participantKey: item.participantKey,
539
+ source: item.source,
478
540
  order: this.orderOf(key),
479
541
  video: this.compositor ? null : this.videoFor(key, item.track),
480
542
  track: item.track,
543
+ crop: featured ? crop : null,
481
544
  };
482
545
  (kind === "screen" ? screens : cameras).set(key, slot);
483
546
  }
484
- // Up to 4 camera tiles: prefer local host first, then earliest remotes.
485
- const localCam = [...cameras.values()].find((slot) => slot.isLocal);
486
- const remotes = [...cameras.values()]
487
- .filter((slot) => !slot.isLocal)
488
- .sort((a, b) => a.order - b.order);
489
- const chosen = (localCam ? [localCam, ...remotes] : remotes).slice(0, 4);
490
547
  const screen = [...screens.values()].find((slot) => slot.isLocal)
491
548
  ?? [...screens.values()].sort((a, b) => a.order - b.order)[0];
492
- // Match live stage: empty stage (or screen with no cameras) keeps the host placeholder tile.
493
- if (chosen.length === 0) {
494
- const name = this.selfName || "Host";
495
- const key = "local|camera|placeholder";
496
- const track = this.ensurePlaceholderTrack(name, true);
497
- chosen.push({
498
- key,
499
- kind: "camera",
500
- isLocal: true,
501
- participantKey: "local",
502
- order: this.orderOf(key),
503
- video: this.compositor ? null : this.videoFor(key, track),
504
- track,
505
- placeholder: true,
506
- displayName: name,
507
- });
549
+ const maxCams = screen ? 3 : 4;
550
+ const stage = Array.isArray(this.stagePeople) ? this.stagePeople : null;
551
+ let chosen = [];
552
+ const keepPlaceholders = new Set();
553
+
554
+ if (stage && stage.length) {
555
+ // Exact participant stage: one tile per on-stage person (live webcam or avatar).
556
+ const used = new Set();
557
+ for (const person of stage.slice(0, maxCams)) {
558
+ const isLocal = Boolean(person.local);
559
+ const id = person.id || "";
560
+ const name = person.name || (isLocal ? (this.selfName || "Host") : "Guest");
561
+ let live = null;
562
+ for (const slot of cameras.values()) {
563
+ if (used.has(slot.key)) continue;
564
+ if (isLocal && slot.isLocal) {
565
+ live = slot;
566
+ break;
567
+ }
568
+ if (!isLocal && id && String(slot.participantKey) === id) {
569
+ live = slot;
570
+ break;
571
+ }
572
+ if (!isLocal && !id && String(slot.participantKey).toLowerCase() === name.toLowerCase()) {
573
+ live = slot;
574
+ break;
575
+ }
576
+ }
577
+ if (live) {
578
+ used.add(live.key);
579
+ chosen.push({ ...live, displayName: name });
580
+ continue;
581
+ }
582
+ const phKey = `placeholder|${isLocal ? "local" : (id || name.toLowerCase())}`;
583
+ keepPlaceholders.add(phKey);
584
+ const track = this.ensurePlaceholderTrack(name, isLocal, phKey);
585
+ chosen.push({
586
+ key: `${phKey}|camera`,
587
+ kind: "camera",
588
+ isLocal,
589
+ participantKey: id || (isLocal ? "local" : name),
590
+ order: this.orderOf(`${phKey}|camera`),
591
+ video: this.compositor ? null : this.videoFor(`${phKey}|camera`, track),
592
+ track,
593
+ placeholder: true,
594
+ displayName: name,
595
+ });
596
+ }
508
597
  } else {
509
- this.clearPlaceholders();
598
+ // Legacy: only live cams; empty stage keeps a single host placeholder.
599
+ const localCam = [...cameras.values()].find((slot) => slot.isLocal);
600
+ const remotes = [...cameras.values()]
601
+ .filter((slot) => !slot.isLocal)
602
+ .sort((a, b) => a.order - b.order);
603
+ chosen = (localCam ? [localCam, ...remotes] : remotes).slice(0, maxCams);
604
+ if (chosen.length === 0) {
605
+ const name = this.selfName || "Host";
606
+ const phKey = "placeholder|local";
607
+ keepPlaceholders.add(phKey);
608
+ const track = this.ensurePlaceholderTrack(name, true, phKey);
609
+ chosen.push({
610
+ key: "local|camera|placeholder",
611
+ kind: "camera",
612
+ isLocal: true,
613
+ participantKey: "local",
614
+ order: this.orderOf("local|camera|placeholder"),
615
+ video: this.compositor ? null : this.videoFor("local|camera|placeholder", track),
616
+ track,
617
+ placeholder: true,
618
+ displayName: name,
619
+ });
620
+ }
510
621
  }
622
+ this.prunePlaceholders(keepPlaceholders);
511
623
  this.slots = screen ? [screen, ...chosen] : chosen;
512
624
  if (this.compositor) {
513
625
  const layout = layoutSlots(chosen.length, Boolean(screen));
514
626
  this.compositor.setSources([
515
- ...(screen ? [{ key: screen.key, track: screen.track, rect: layout.screen }] : []),
516
- ...chosen.map((slot, index) => ({ key: slot.key, track: slot.track, rect: layout.cameras[index] })),
627
+ ...(screen ? [{ key: screen.key, track: screen.track, rect: layout.screen, crop: screen.crop || null }] : []),
628
+ ...chosen.map((slot, index) => ({ key: slot.key, track: slot.track, rect: layout.cameras[index], crop: null })),
517
629
  ]);
518
630
  }
519
631
  // Mix every mic (and screen audio). Overflow cameras stay off-layout but audible.
@@ -528,9 +640,8 @@ export class CanvasRecorder {
528
640
  }
529
641
  }
530
642
 
531
- /** Synthetic webcam matching the live empty-stage avatar tile. */
532
- ensurePlaceholderTrack(name, isLocal) {
533
- const key = `placeholder|${isLocal ? "local" : name}`;
643
+ /** Synthetic webcam matching the live empty-stage avatar tile (native 1280×720, no upscale). */
644
+ ensurePlaceholderTrack(name, isLocal, key = `placeholder|${isLocal ? "local" : name}`) {
534
645
  let entry = this.placeholderSources.get(key);
535
646
  if (entry) {
536
647
  entry.name = name;
@@ -539,9 +650,10 @@ export class CanvasRecorder {
539
650
  return entry.track;
540
651
  }
541
652
  const canvas = document.createElement("canvas");
542
- canvas.width = 640;
543
- canvas.height = 360;
544
- const ctx = canvas.getContext("2d");
653
+ // Match recording output size so the compositor does not upscale (blur).
654
+ canvas.width = W;
655
+ canvas.height = H;
656
+ const ctx = canvas.getContext("2d", { alpha: false, desynchronized: true });
545
657
  const stream = canvas.captureStream(FPS);
546
658
  const track = stream.getVideoTracks()[0];
547
659
  entry = { track, canvas, name, isLocal, redraw: null, timer: null };
@@ -555,16 +667,22 @@ export class CanvasRecorder {
555
667
  return track;
556
668
  }
557
669
 
558
- clearPlaceholders() {
559
- for (const entry of this.placeholderSources.values()) {
670
+ prunePlaceholders(keepKeys) {
671
+ const keep = keepKeys instanceof Set ? keepKeys : new Set(keepKeys || []);
672
+ for (const [key, entry] of [...this.placeholderSources]) {
673
+ if (keep.has(key)) continue;
560
674
  clearInterval(entry.timer);
561
675
  try {
562
676
  entry.track.stop();
563
677
  } catch {
564
678
  // already ended
565
679
  }
680
+ this.placeholderSources.delete(key);
566
681
  }
567
- this.placeholderSources.clear();
682
+ }
683
+
684
+ clearPlaceholders() {
685
+ this.prunePlaceholders(new Set());
568
686
  }
569
687
 
570
688
  orderOf(key) {
@@ -632,15 +750,23 @@ export class CanvasRecorder {
632
750
  const layout = layoutSlots(cameras.length, Boolean(screen));
633
751
  this.ctx.fillStyle = "#000";
634
752
  this.ctx.fillRect(0, 0, W, H);
635
- if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen);
753
+ if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen, screen.crop);
636
754
  cameras.forEach((slot, index) => {
637
755
  const rect = layout.cameras[index];
638
756
  if (!rect) return;
639
757
  if (slot.placeholder) {
640
- drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, slot.displayName || this.selfName, true);
758
+ drawStagePlaceholder(
759
+ this.ctx,
760
+ rect.x,
761
+ rect.y,
762
+ rect.w,
763
+ rect.h,
764
+ slot.displayName || this.selfName,
765
+ Boolean(slot.isLocal),
766
+ );
641
767
  return;
642
768
  }
643
- paint(this.ctx, slot.video, rect);
769
+ paint(this.ctx, slot.video, rect, null);
644
770
  });
645
771
  this.capture?.requestFrame();
646
772
  }
@@ -778,51 +904,70 @@ function placeholderLetter(name) {
778
904
  return text ? text[0].toUpperCase() : "?";
779
905
  }
780
906
 
781
- /** Same magenta empty-stage look as the live sample UI. */
782
- function drawStagePlaceholder(ctx, x, y, w, h, name, isLocal) {
783
- const cx = x + w / 2;
784
- const cy = y + h / 2;
785
- const gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, Math.max(w, h) * 0.75);
786
- gradient.addColorStop(0, "rgb(152, 62, 107)");
787
- gradient.addColorStop(0.75, "rgb(104, 39, 71)");
788
- gradient.addColorStop(1, "rgb(104, 39, 71)");
789
- ctx.fillStyle = gradient;
907
+ /**
908
+ * Empty-stage tile for the recording canvas:
909
+ * maroon radial field, solid #e30096 name round (no border), white initial, name top-left.
910
+ */
911
+ function drawStagePlaceholder(ctx, x, y, w, h, name, _isLocal) {
912
+ const cx = Math.round(x + w / 2);
913
+ const cy = Math.round(y + h / 2);
914
+ const span = Math.max(w, h) * 0.75;
915
+ const field = ctx.createRadialGradient(cx, cy, 0, cx, cy, span);
916
+ field.addColorStop(0, "rgb(152, 62, 107)");
917
+ field.addColorStop(0.75, "rgb(104, 39, 71)");
918
+ field.addColorStop(1, "rgb(104, 39, 71)");
919
+ ctx.fillStyle = field;
790
920
  ctx.fillRect(x, y, w, h);
791
921
 
792
- const radius = Math.min(w, h) * 0.16;
922
+ const diameter = Math.round(Math.min(128, Math.max(88, Math.min(w, h) * 0.18)));
923
+ const radius = diameter / 2;
793
924
  ctx.beginPath();
794
925
  ctx.arc(cx, cy, radius, 0, Math.PI * 2);
795
- ctx.fillStyle = "rgba(255, 255, 255, 0.1)";
926
+ ctx.fillStyle = "#e30096";
796
927
  ctx.fill();
797
- ctx.lineWidth = Math.max(2, radius * 0.06);
798
- ctx.strokeStyle = "rgba(255, 255, 255, 0.72)";
799
- ctx.stroke();
800
928
 
801
- ctx.fillStyle = "#fff";
802
- ctx.font = `700 ${Math.round(radius * 1.15)}px Mulish, "Segoe UI", sans-serif`;
929
+ const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 28), 45));
930
+ ctx.fillStyle = "#ffffff";
931
+ ctx.font = `600 ${letterPx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
803
932
  ctx.textAlign = "center";
804
933
  ctx.textBaseline = "middle";
805
934
  ctx.fillText(placeholderLetter(name), cx, cy + 1);
806
935
 
807
- const label = `${String(name || "Host").slice(0, 40)}${isLocal ? " (You)" : ""}`;
808
- const pad = Math.max(12, Math.round(h * 0.04));
936
+ const label = String(name || "Host").slice(0, 40);
937
+ const padX = Math.max(14, Math.round(w * 0.016));
938
+ const padY = Math.max(14, Math.round(h * 0.024));
939
+ const namePx = Math.round(Math.min(Math.max(h * 0.028, 14), 18));
809
940
  ctx.textAlign = "left";
810
- ctx.textBaseline = "alphabetic";
811
- ctx.font = `800 ${Math.max(14, Math.round(h * 0.045))}px Mulish, "Segoe UI", sans-serif`;
812
- ctx.fillStyle = "rgba(0, 0, 0, 0.35)";
813
- ctx.fillText(label, x + pad + 1, y + h - pad + 1);
814
- ctx.fillStyle = "#fff";
815
- ctx.fillText(label, x + pad, y + h - pad);
941
+ ctx.textBaseline = "top";
942
+ ctx.font = `500 ${namePx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
943
+ ctx.fillStyle = "#ffffff";
944
+ ctx.fillText(label, x + padX, y + padY);
816
945
  }
817
946
 
818
- function paint(ctx, video, rect) {
947
+ function paint(ctx, video, rect, crop) {
819
948
  ctx.fillStyle = "#000";
820
949
  ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
821
950
  if (!video || video.readyState < 2 || !video.videoWidth) return;
822
- const scale = Math.min(rect.w / video.videoWidth, rect.h / video.videoHeight);
823
- const dw = video.videoWidth * scale;
824
- const dh = video.videoHeight * scale;
825
- ctx.drawImage(video, rect.x + (rect.w - dw) / 2, rect.y + (rect.h - dh) / 2, dw, dh);
951
+ let sx = 0;
952
+ let sy = 0;
953
+ let sw = video.videoWidth;
954
+ let sh = video.videoHeight;
955
+ const cropNorm = normalizeVideoCrop(crop);
956
+ if (cropNorm) {
957
+ sx = cropNorm.x * video.videoWidth;
958
+ sy = cropNorm.y * video.videoHeight;
959
+ sw = cropNorm.w * video.videoWidth;
960
+ sh = cropNorm.h * video.videoHeight;
961
+ if (sw <= 1 || sh <= 1) return;
962
+ }
963
+ // Contain (not stretch): keep source aspect ratio inside the destination slot.
964
+ const scale = Math.min(rect.w / sw, rect.h / sh);
965
+ const dw = sw * scale;
966
+ const dh = sh * scale;
967
+ const prev = ctx.imageSmoothingEnabled;
968
+ ctx.imageSmoothingEnabled = scale < 0.98;
969
+ ctx.drawImage(video, sx, sy, sw, sh, rect.x + (rect.w - dw) / 2, rect.y + (rect.h - dh) / 2, dw, dh);
970
+ ctx.imageSmoothingEnabled = prev;
826
971
  }
827
972
 
828
973
  function sleep(ms) {