mediascale-sdk 1.0.7 → 1.0.9

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.
@@ -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).
@@ -141,7 +180,27 @@ await client.replaceMicrophoneTrack(nextMicTrack);
141
180
 
142
181
  `replaceCameraTrack` / `replaceMicrophoneTrack` swap media on the **existing producer** (no unpublish). Use these for smooth device switching while live.
143
182
 
144
- The SFU origin caps each publisher’s uplink at **2500 Kbps** (`MAX_PUBLISH_BITRATE_BPS`) via `setMaxIncomingBitrate` on the send transport.
183
+ ### Publish bitrate caps (camera / screen)
184
+
185
+ The SDK limits **outgoing** video encode bitrate via WebRTC `encodings.maxBitrate`:
186
+
187
+ | Stream | Default | Env (portal) |
188
+ | --- | --- | --- |
189
+ | Camera (`webcam`) | **1 Mbps** | `CAMERA_MAX_BITRATE_BPS` |
190
+ | Screen share, whiteboard, PDF, other custom video | **1.5 Mbps** | `SCREEN_MAX_BITRATE_BPS` |
191
+
192
+ Flow: portal reads those env vars → includes `publishLimits: { cameraBps, screenBps }` on the `join` ack → SDK applies them on `produce`. Set a value to `0` to disable that SDK-side cap. Optional override on the client:
193
+
194
+ ```js
195
+ createClient({
196
+ // …
197
+ publishLimits: { cameraBps: 1_000_000, screenBps: 1_500_000 },
198
+ });
199
+ ```
200
+
201
+ `createClient({ publishLimits })` wins over the portal values. Mic / screen-audio are unchanged.
202
+
203
+ Separately, the SFU origin still caps each publisher’s uplink at **2500 Kbps** (`MAX_PUBLISH_BITRATE_BPS`) via `setMaxIncomingBitrate` on the send transport.
145
204
 
146
205
  Toggle recording during the session:
147
206
 
@@ -156,7 +215,7 @@ await client.end(); // combines every segment into one file
156
215
 
157
216
  | Function | What it does |
158
217
  | --- | --- |
159
- | `createClient({ endpoint, sessionId, token, recording, iceServers, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. If you omit `recording` (or pass anything other than `false`) and the host token has `recording: true`, auto-start is still enabled. Pass `recording: false` to force off. |
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. |
160
219
  | `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. |
161
220
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
162
221
  | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
@@ -174,6 +233,10 @@ await client.end(); // combines every segment into one file
174
233
  | `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
234
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
176
235
  | `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
+ | `getPeerId()` | Socket peer id for this browser after `connect()`. |
238
+ | `getPublishLimits()` | Current `{ cameraBps, screenBps }` used for outgoing video encode caps. |
239
+ | `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. |
177
240
  | `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
178
241
  | `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
179
242
 
@@ -191,6 +254,8 @@ Pass these to `createClient`.
191
254
  | `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
192
255
  | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
193
256
  | `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. |
257
+ | `onStageChanged(people)` | Optional. Fires when the recording stage list changes after `setRecordingStage` (or sample roster updates). |
258
+ | `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. |
194
259
 
195
260
  ## Active speaker
196
261
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
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
@@ -11,6 +11,24 @@ const SIZES = {
11
11
  /** Built-in sources that have dedicated start/stop helpers. */
12
12
  const RESERVED_SOURCES = new Set(["webcam", "mic", "screen", "screen-audio"]);
13
13
 
14
+ /** Default SDK publish caps (bps). Portal join / createClient can override. */
15
+ const DEFAULT_CAMERA_MAX_BITRATE_BPS = 1_000_000;
16
+ const DEFAULT_SCREEN_MAX_BITRATE_BPS = 1_500_000;
17
+
18
+ function parseBitrateBps(raw, fallback) {
19
+ if (raw == null || raw === "") return fallback;
20
+ const n = Number(raw);
21
+ if (!Number.isFinite(n)) return fallback;
22
+ return Math.max(0, Math.floor(n));
23
+ }
24
+
25
+ function normalizePublishLimits(raw = {}) {
26
+ return {
27
+ cameraBps: parseBitrateBps(raw.cameraBps ?? raw.camera, DEFAULT_CAMERA_MAX_BITRATE_BPS),
28
+ screenBps: parseBitrateBps(raw.screenBps ?? raw.screen, DEFAULT_SCREEN_MAX_BITRATE_BPS),
29
+ };
30
+ }
31
+
14
32
  function readToken(token) {
15
33
  const body = String(token || "").split(".")[0];
16
34
  if (!body) throw new Error("token is required");
@@ -65,6 +83,12 @@ export function createClient(options = {}) {
65
83
  const onError = options.onError || (() => {});
66
84
  const onRecording = options.onRecording || (() => {});
67
85
  const onActiveSpeaker = options.onActiveSpeaker || (() => {});
86
+ const onUserJoined = options.onUserJoined || (() => {});
87
+ const onUserLeft = options.onUserLeft || (() => {});
88
+ const onUserUpdated = options.onUserUpdated || (() => {});
89
+ const onUserList = options.onUserList || (() => {});
90
+ const onUserBlocked = options.onUserBlocked || (() => {});
91
+ const onStageChanged = options.onStageChanged || (() => {});
68
92
 
69
93
  if (!sessionId) throw new Error("sessionId is required");
70
94
  if (!token) throw new Error("token is required");
@@ -75,6 +99,11 @@ export function createClient(options = {}) {
75
99
  || (options.recording !== false && claims.recording === true && claims.role === "host");
76
100
 
77
101
  const displayName = String(claims.name || "Guest").slice(0, 40);
102
+ // createClient({ publishLimits }) wins over portal join values when set.
103
+ const publishLimitsOverride = options.publishLimits != null
104
+ ? normalizePublishLimits(options.publishLimits)
105
+ : null;
106
+ let publishLimits = publishLimitsOverride || normalizePublishLimits({});
78
107
  let socket = null;
79
108
  let device = null;
80
109
  let sendTransport = null;
@@ -89,10 +118,80 @@ export function createClient(options = {}) {
89
118
  const tiles = new Map();
90
119
  /** source id → normalized crop for recording compositor (e.g. whiteboard). */
91
120
  const recordingCrops = new Map();
121
+ /** peerId → { id, name, local } for people currently on stage (from roster or setRecordingStage). */
122
+ const stageById = new Map();
123
+ /** When set, parent-provided stage list wins over roster-derived stageById. */
124
+ let stageOverride = null;
125
+ let lastStageSig = "";
92
126
  const pending = [];
93
127
  let readyPromise = null;
94
128
  let settleReady = null;
95
129
 
130
+ function userOnStage(user) {
131
+ if (!user) return false;
132
+ if (user.onStage != null) return Boolean(user.onStage);
133
+ const role = String(user.stageRole || "").trim().toLowerCase();
134
+ return role === "host" || role === "co-host" || role === "speaker";
135
+ }
136
+
137
+ function normalizeStagePerson(person) {
138
+ if (!person) return null;
139
+ const id = String(person.id || "").trim();
140
+ const name = String(person.name || "Guest").trim().slice(0, 40) || "Guest";
141
+ if (!id && !name) return null;
142
+ return {
143
+ id,
144
+ name,
145
+ local: Boolean(person.local) || Boolean(id && selfPeerId && id === selfPeerId),
146
+ };
147
+ }
148
+
149
+ function stagePeopleForRecording() {
150
+ if (stageOverride) return stageOverride;
151
+ return [...stageById.values()];
152
+ }
153
+
154
+ function emitStageChanged() {
155
+ const people = stagePeopleForRecording();
156
+ const sig = people.map((p) => `${p.id}|${p.name}|${p.local ? 1 : 0}`).join(";");
157
+ if (sig === lastStageSig) return;
158
+ lastStageSig = sig;
159
+ onStageChanged(people);
160
+ }
161
+
162
+ function ingestRosterUsers(users) {
163
+ if (!Array.isArray(users)) return;
164
+ stageById.clear();
165
+ for (const user of users) {
166
+ if (!userOnStage(user)) continue;
167
+ const person = normalizeStagePerson(user);
168
+ if (!person?.id) continue;
169
+ stageById.set(person.id, person);
170
+ }
171
+ emitStageChanged();
172
+ syncRecording();
173
+ }
174
+
175
+ function ingestRosterUser(user) {
176
+ if (!user?.id) return;
177
+ if (userOnStage(user)) {
178
+ const person = normalizeStagePerson(user);
179
+ if (person?.id) stageById.set(person.id, person);
180
+ } else {
181
+ stageById.delete(String(user.id));
182
+ }
183
+ emitStageChanged();
184
+ syncRecording();
185
+ }
186
+
187
+ function removeRosterUser(user) {
188
+ const id = String(user?.id || "").trim();
189
+ if (!id) return;
190
+ if (!stageById.delete(id)) return;
191
+ emitStageChanged();
192
+ syncRecording();
193
+ }
194
+
96
195
  function clientHints() {
97
196
  if (typeof navigator === "undefined") return {};
98
197
  const ua = String(navigator.userAgent || "");
@@ -113,7 +212,32 @@ export function createClient(options = {}) {
113
212
  }
114
213
 
115
214
  function syncRecording() {
116
- recorder?.sync(tracksForRecording());
215
+ recorder?.sync(tracksForRecording(), stagePeopleForRecording());
216
+ }
217
+
218
+ /**
219
+ * Tell the recorder who belongs on stage (same tiles participants see).
220
+ * Each person is `{ id, name, local? }`. When they publish webcam, that tile becomes video.
221
+ * Pass `null` to fall back to the socket roster; pass `[]` for an empty stage.
222
+ */
223
+ function setRecordingStage(people) {
224
+ if (people == null) {
225
+ stageOverride = null;
226
+ } else {
227
+ const next = [];
228
+ const seen = new Set();
229
+ for (const raw of Array.isArray(people) ? people : []) {
230
+ const person = normalizeStagePerson(raw);
231
+ if (!person) continue;
232
+ const key = person.id || `name:${person.name.toLowerCase()}`;
233
+ if (seen.has(key)) continue;
234
+ seen.add(key);
235
+ next.push(person);
236
+ }
237
+ stageOverride = next;
238
+ }
239
+ emitStageChanged();
240
+ syncRecording();
117
241
  }
118
242
 
119
243
  /**
@@ -210,11 +334,36 @@ export function createClient(options = {}) {
210
334
  if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
211
335
  }
212
336
 
337
+ function maxBitrateFor(source, kind) {
338
+ if (kind !== "video") return 0;
339
+ if (source === "webcam") return publishLimits.cameraBps;
340
+ // screen + custom video (whiteboard, pdf, …)
341
+ return publishLimits.screenBps;
342
+ }
343
+
344
+ function applyPublishLimitsFromJoin(raw) {
345
+ if (publishLimitsOverride) return;
346
+ if (!raw || typeof raw !== "object") return;
347
+ publishLimits = normalizePublishLimits({
348
+ cameraBps: raw.cameraBps ?? raw.camera,
349
+ screenBps: raw.screenBps ?? raw.screen,
350
+ });
351
+ }
352
+
213
353
  // Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
214
354
  async function produce(source, track, original = track) {
215
355
  let producer;
216
356
  try {
217
- producer = await sendTransport.produce({ track, stopTracks: false, appData: { source } });
357
+ const options = { track, stopTracks: false, appData: { source } };
358
+ const maxBitrate = maxBitrateFor(source, track.kind);
359
+ if (maxBitrate > 0) {
360
+ options.encodings = [{ maxBitrate }];
361
+ // Chrome start bitrate is kbps; keep a modest ramp under the cap.
362
+ options.codecOptions = {
363
+ videoGoogleStartBitrate: Math.max(100, Math.min(1000, Math.round(maxBitrate / 2000))),
364
+ };
365
+ }
366
+ producer = await sendTransport.produce(options);
218
367
  if (closed) throw new Error("The session has ended");
219
368
  if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
220
369
  } catch (error) {
@@ -305,6 +454,24 @@ export function createClient(options = {}) {
305
454
  local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
306
455
  });
307
456
  });
457
+ socket.on("userJoined", (user) => {
458
+ if (closed) return;
459
+ ingestRosterUser(user);
460
+ onUserJoined(user);
461
+ });
462
+ socket.on("userLeft", (user) => {
463
+ if (closed) return;
464
+ removeRosterUser(user);
465
+ onUserLeft(user);
466
+ });
467
+ socket.on("userUpdated", (user) => {
468
+ if (closed) return;
469
+ ingestRosterUser(user);
470
+ onUserUpdated(user);
471
+ });
472
+ socket.on("userBlocked", (payload) => {
473
+ if (!closed) onUserBlocked(payload || {});
474
+ });
308
475
  socket.on("connect", async () => {
309
476
  try {
310
477
  if (closed) return;
@@ -317,6 +484,11 @@ export function createClient(options = {}) {
317
484
  });
318
485
  selfPeerId = joined.peerId || null;
319
486
  iceServers = iceOverride || joined.iceServers || [];
487
+ applyPublishLimitsFromJoin(joined.publishLimits);
488
+ if (Array.isArray(joined.users)) {
489
+ ingestRosterUsers(joined.users);
490
+ onUserList(joined.users);
491
+ }
320
492
  device = new Device();
321
493
  await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
322
494
 
@@ -355,6 +527,16 @@ export function createClient(options = {}) {
355
527
  });
356
528
  const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
357
529
  for (const params of started.consumers || []) await play(params);
530
+ // Fresh roster after ready (covers anyone who joined during transport setup).
531
+ try {
532
+ const list = await emit(socket, "getUserList", {});
533
+ if (Array.isArray(list?.users)) {
534
+ ingestRosterUsers(list.users);
535
+ onUserList(list.users);
536
+ }
537
+ } catch {
538
+ /* roster optional if portal is older */
539
+ }
358
540
  if (joined.waiting) onStatus("Please wait, we will connect you soon");
359
541
  else onStatus("Ready");
360
542
  if (closed) return;
@@ -374,6 +556,40 @@ export function createClient(options = {}) {
374
556
  return readyPromise;
375
557
  }
376
558
 
559
+ async function getUserList() {
560
+ await connect();
561
+ if (!socket?.connected) throw new Error("Not connected");
562
+ const result = await emit(socket, "getUserList", {});
563
+ if (result?.error) throw new Error(result.error);
564
+ const users = Array.isArray(result?.users) ? result.users : [];
565
+ ingestRosterUsers(users);
566
+ onUserList(users);
567
+ return users;
568
+ }
569
+
570
+ async function updateSelf(patch = {}) {
571
+ await connect();
572
+ if (!socket?.connected) throw new Error("Not connected");
573
+ const result = await emit(socket, "updateSelf", patch);
574
+ if (result?.error) throw new Error(result.error);
575
+ return result?.user || null;
576
+ }
577
+
578
+ async function stageAction(action, targetId) {
579
+ await connect();
580
+ if (!socket?.connected) throw new Error("Not connected");
581
+ const result = await emit(socket, "stageAction", { action, targetId });
582
+ if (result?.error) throw new Error(result.error);
583
+ if (Array.isArray(result?.users)) {
584
+ ingestRosterUsers(result.users);
585
+ onUserList(result.users);
586
+ } else if (result?.user) {
587
+ ingestRosterUser(result.user);
588
+ onUserUpdated(result.user);
589
+ }
590
+ return result;
591
+ }
592
+
377
593
  async function startCamera({ cameraId, resolution, track } = {}) {
378
594
  if (track !== undefined) requireLiveTrack(track, "video");
379
595
  await connect();
@@ -597,7 +813,7 @@ export function createClient(options = {}) {
597
813
  next.wanted = true;
598
814
  notifyRecording(next);
599
815
  for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
600
- next.sync(tracksForRecording());
816
+ next.sync(tracksForRecording(), stagePeopleForRecording());
601
817
  try {
602
818
  await next.start();
603
819
  } catch (error) {
@@ -696,6 +912,12 @@ export function createClient(options = {}) {
696
912
  startRecording: guard(startRecording),
697
913
  stopRecording: guard(stopRecording),
698
914
  setRecordingCrop,
915
+ setRecordingStage,
916
+ getUserList: guard(getUserList),
917
+ updateSelf: guard(updateSelf),
918
+ stageAction: guard(stageAction),
919
+ getPeerId: () => selfPeerId,
920
+ getPublishLimits: () => ({ ...publishLimits }),
699
921
  end: guard(end),
700
922
  listDevices: guard(listDevices),
701
923
  };
package/src/record.js CHANGED
@@ -118,6 +118,8 @@ export class CanvasRecorder {
118
118
  this.webinarName = webinarName || webinarId;
119
119
  this.recordingId = recordingId;
120
120
  this.endpoint = String(endpoint || "").replace(/\/+$/, "");
121
+ /** @type {{ id: string, name: string, local?: boolean }[] | null} */
122
+ this.stagePeople = null;
121
123
  this.token = token || "";
122
124
  this.selfName = String(selfName || "Host").slice(0, 40);
123
125
  this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
@@ -232,8 +234,25 @@ export class CanvasRecorder {
232
234
  for (const type of events) window.addEventListener(type, unlock, true);
233
235
  }
234
236
 
235
- 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) {
236
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
+ }
237
256
  for (const item of this.tracks) {
238
257
  if (item?.kind !== "video" || !item.source) continue;
239
258
  const crop = normalizeVideoCrop(item.crop);
@@ -525,33 +544,82 @@ export class CanvasRecorder {
525
544
  };
526
545
  (kind === "screen" ? screens : cameras).set(key, slot);
527
546
  }
528
- // Up to 4 camera tiles: prefer local host first, then earliest remotes.
529
- const localCam = [...cameras.values()].find((slot) => slot.isLocal);
530
- const remotes = [...cameras.values()]
531
- .filter((slot) => !slot.isLocal)
532
- .sort((a, b) => a.order - b.order);
533
- const chosen = (localCam ? [localCam, ...remotes] : remotes).slice(0, 4);
534
547
  const screen = [...screens.values()].find((slot) => slot.isLocal)
535
548
  ?? [...screens.values()].sort((a, b) => a.order - b.order)[0];
536
- // Match live stage: empty stage (or screen with no cameras) keeps the host placeholder tile.
537
- if (chosen.length === 0) {
538
- const name = this.selfName || "Host";
539
- const key = "local|camera|placeholder";
540
- const track = this.ensurePlaceholderTrack(name, true);
541
- chosen.push({
542
- key,
543
- kind: "camera",
544
- isLocal: true,
545
- participantKey: "local",
546
- order: this.orderOf(key),
547
- video: this.compositor ? null : this.videoFor(key, track),
548
- track,
549
- placeholder: true,
550
- displayName: name,
551
- });
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
+ }
552
597
  } else {
553
- 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
+ }
554
621
  }
622
+ this.prunePlaceholders(keepPlaceholders);
555
623
  this.slots = screen ? [screen, ...chosen] : chosen;
556
624
  if (this.compositor) {
557
625
  const layout = layoutSlots(chosen.length, Boolean(screen));
@@ -573,8 +641,7 @@ export class CanvasRecorder {
573
641
  }
574
642
 
575
643
  /** Synthetic webcam matching the live empty-stage avatar tile (native 1280×720, no upscale). */
576
- ensurePlaceholderTrack(name, isLocal) {
577
- const key = `placeholder|${isLocal ? "local" : name}`;
644
+ ensurePlaceholderTrack(name, isLocal, key = `placeholder|${isLocal ? "local" : name}`) {
578
645
  let entry = this.placeholderSources.get(key);
579
646
  if (entry) {
580
647
  entry.name = name;
@@ -600,16 +667,22 @@ export class CanvasRecorder {
600
667
  return track;
601
668
  }
602
669
 
603
- clearPlaceholders() {
604
- 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;
605
674
  clearInterval(entry.timer);
606
675
  try {
607
676
  entry.track.stop();
608
677
  } catch {
609
678
  // already ended
610
679
  }
680
+ this.placeholderSources.delete(key);
611
681
  }
612
- this.placeholderSources.clear();
682
+ }
683
+
684
+ clearPlaceholders() {
685
+ this.prunePlaceholders(new Set());
613
686
  }
614
687
 
615
688
  orderOf(key) {
@@ -682,7 +755,15 @@ export class CanvasRecorder {
682
755
  const rect = layout.cameras[index];
683
756
  if (!rect) return;
684
757
  if (slot.placeholder) {
685
- 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
+ );
686
767
  return;
687
768
  }
688
769
  paint(this.ctx, slot.video, rect, null);
@@ -825,7 +906,7 @@ function placeholderLetter(name) {
825
906
 
826
907
  /**
827
908
  * Empty-stage tile for the recording canvas:
828
- * maroon radial field, solid #bd5a61 disk (no border), white initial, name top-left.
909
+ * maroon radial field, solid #e30096 name round (no border), white initial, name top-left.
829
910
  */
830
911
  function drawStagePlaceholder(ctx, x, y, w, h, name, _isLocal) {
831
912
  const cx = Math.round(x + w / 2);
@@ -842,7 +923,7 @@ function drawStagePlaceholder(ctx, x, y, w, h, name, _isLocal) {
842
923
  const radius = diameter / 2;
843
924
  ctx.beginPath();
844
925
  ctx.arc(cx, cy, radius, 0, Math.PI * 2);
845
- ctx.fillStyle = "#bd5a61";
926
+ ctx.fillStyle = "#e30096";
846
927
  ctx.fill();
847
928
 
848
929
  const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 28), 45));