mediascale-sdk 1.0.9 → 1.0.11

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 outer margin). **No border radius.** Name pill still drawn. Brand canvas background is not visible as a letterbox. |
377
+ | Two or more cameras (no screen) | Grid with even outer padding and gutters (`16px`), rounded tiles (`14px` radius), light border. Local / presenter tile gets an accent glow from `recordingCanvasBackground`. |
378
+ | Screen share or featured custom video (e.g. whiteboard) | Large main pane on the left; up to **six** cameras / avatars in a **right column stacked from the top** (fixed tile height so fewer cameras sit at the top, not stretched apart). 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 **name-only** pill (no mic or signal icons).
384
+ - Label comes from `setRecordingStage` `name`, else the track `displayName`, else the local host JWT name (`Guest` / `Host` as fallback).
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.9",
3
+ "version": "1.0.11",
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.
@@ -108,11 +116,15 @@ export function createClient(options = {}) {
108
116
  let device = null;
109
117
  let sendTransport = null;
110
118
  let recvTransport = null;
119
+ /** Single-flight when portal parks this viewer and later emits edgeChanged. */
120
+ let recvRecovering = null;
111
121
  let iceServers = iceOverride || [];
112
122
  let closed = false;
113
123
  let subscribed = false;
114
124
  let recorder = null;
115
125
  let startingRecorder = null;
126
+ /** Sticky id for stop/start segments; replaced after a take is finalized/failed. */
127
+ let activeRecordingId = null;
116
128
  let selfPeerId = null;
117
129
  const locals = new Map();
118
130
  const tiles = new Map();
@@ -129,9 +141,11 @@ export function createClient(options = {}) {
129
141
 
130
142
  function userOnStage(user) {
131
143
  if (!user) return false;
132
- if (user.onStage != null) return Boolean(user.onStage);
133
144
  const role = String(user.stageRole || "").trim().toLowerCase();
134
- return role === "host" || role === "co-host" || role === "speaker";
145
+ // Host / co-host are always on stage (screen / whiteboard / cam for everyone).
146
+ if (role === "host" || role === "co-host") return true;
147
+ if (user.onStage != null) return Boolean(user.onStage);
148
+ return role === "speaker";
135
149
  }
136
150
 
137
151
  function normalizeStagePerson(person) {
@@ -350,6 +364,89 @@ export function createClient(options = {}) {
350
364
  });
351
365
  }
352
366
 
367
+ function bindSendTransport(transport) {
368
+ transport.on("connect", ({ dtlsParameters }, callback, errback) => {
369
+ emit(socket, "connectTransport", { transportId: transport.id, dtlsParameters }).then(() => callback()).catch(errback);
370
+ });
371
+ transport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => {
372
+ emit(socket, "produce", {
373
+ transportId: transport.id,
374
+ kind,
375
+ rtpParameters,
376
+ source: appData.source,
377
+ }).then((result) => callback({ id: result.id })).catch(errback);
378
+ });
379
+ transport.on("connectionstatechange", (state) => {
380
+ if (state === "failed" || state === "disconnected") onStatus("Network unstable");
381
+ else if (state === "connected") onStatus("Live");
382
+ });
383
+ }
384
+
385
+ function bindRecvTransport(transport) {
386
+ transport.on("connect", ({ dtlsParameters }, callback, errback) => {
387
+ emit(socket, "connectTransport", { transportId: transport.id, dtlsParameters }).then(() => callback()).catch(errback);
388
+ });
389
+ }
390
+
391
+ function clearRemoteTiles() {
392
+ for (const [producerId, tile] of [...tiles.entries()]) {
393
+ if (tile.local) continue;
394
+ tiles.delete(producerId);
395
+ onTrackEnded({ producerId });
396
+ }
397
+ syncRecording();
398
+ }
399
+
400
+ /**
401
+ * After packChannel parks this viewer, portal emits releaseConsumers then later
402
+ * edgeChanged. Rebuild the receive transport and pull every producer again
403
+ * (including a host screen share that started while we were parked).
404
+ */
405
+ async function recoverRecvTransport() {
406
+ if (closed || !device || !socket?.connected) return;
407
+ if (recvRecovering) return recvRecovering;
408
+ recvRecovering = (async () => {
409
+ try {
410
+ onStatus("Reconnecting media…");
411
+ pending.length = 0;
412
+ try { recvTransport?.close(); } catch { /* ignore */ }
413
+ recvTransport = null;
414
+ clearRemoteTiles();
415
+
416
+ const recvParams = await emit(socket, "createTransport", { direction: "recv" });
417
+ if (closed) return;
418
+ recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
419
+ bindRecvTransport(recvTransport);
420
+
421
+ const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
422
+ for (const params of started.consumers || []) await play(params);
423
+ if (!closed) onStatus("Connected");
424
+ } catch (error) {
425
+ if (!closed) {
426
+ onError(error);
427
+ onStatus(error.message || "Media reconnect failed");
428
+ }
429
+ } finally {
430
+ recvRecovering = null;
431
+ }
432
+ })();
433
+ return recvRecovering;
434
+ }
435
+
436
+ /** Recreate send transport on the next vacant origin after the current one fills. */
437
+ async function recreateSendTransport() {
438
+ try { sendTransport?.close(); } catch { /* ignore */ }
439
+ sendTransport = null;
440
+ const sendParams = await emit(socket, "createTransport", { direction: "send" });
441
+ sendTransport = device.createSendTransport({ ...sendParams, iceServers });
442
+ bindSendTransport(sendTransport);
443
+ }
444
+
445
+ function shouldRecreateSendTransport(error) {
446
+ const msg = String(error?.message || error || "");
447
+ return /out of credits|transport not found|ORIGIN_FULL|Origin is full/i.test(msg);
448
+ }
449
+
353
450
  // Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
354
451
  async function produce(source, track, original = track) {
355
452
  let producer;
@@ -363,7 +460,14 @@ export function createClient(options = {}) {
363
460
  videoGoogleStartBitrate: Math.max(100, Math.min(1000, Math.round(maxBitrate / 2000))),
364
461
  };
365
462
  }
366
- producer = await sendTransport.produce(options);
463
+ if (!sendTransport) throw new Error("The session is not ready");
464
+ try {
465
+ producer = await sendTransport.produce(options);
466
+ } catch (error) {
467
+ if (!shouldRecreateSendTransport(error)) throw error;
468
+ await recreateSendTransport();
469
+ producer = await sendTransport.produce(options);
470
+ }
367
471
  if (closed) throw new Error("The session has ended");
368
472
  if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
369
473
  } catch (error) {
@@ -403,6 +507,23 @@ export function createClient(options = {}) {
403
507
  }
404
508
  }
405
509
 
510
+ async function ensureRecorderAffinity() {
511
+ const webinarId = recordingWebinarId(sessionId);
512
+ try {
513
+ const response = await fetch(
514
+ `${endpoint}/recorder/api/v1/affinity?webinarId=${encodeURIComponent(webinarId)}`,
515
+ { credentials: "include" },
516
+ );
517
+ if (!response.ok) return;
518
+ const body = await response.json().catch(() => null);
519
+ if (body?.peer && typeof document !== "undefined") {
520
+ document.cookie = `ms_recorder=${encodeURIComponent(body.peer)}; Path=/; Max-Age=86400; SameSite=Lax`;
521
+ }
522
+ } catch {
523
+ /* gateway may still route to the seed recorder */
524
+ }
525
+ }
526
+
406
527
  async function connect() {
407
528
  if (readyPromise) return readyPromise;
408
529
  readyPromise = (async () => {
@@ -422,7 +543,8 @@ export function createClient(options = {}) {
422
543
  if (!closed) onStatus("Network unstable");
423
544
  });
424
545
  socket.on("sessionEnded", () => {
425
- end().catch((error) => onError(error));
546
+ // Whole room is ending — always finalize if we hold the recorder (never hand off).
547
+ end({ finalize: true }).catch((error) => onError(error));
426
548
  });
427
549
  socket.on("releaseRecording", () => {
428
550
  const current = recorder;
@@ -440,7 +562,8 @@ export function createClient(options = {}) {
440
562
  const current = recorder;
441
563
  if (!current) return;
442
564
  recorder = null;
443
- current.finish()
565
+ // Background remux — do not surface a blocking status in the meet UI.
566
+ current.finish({ waitFinalize: false })
444
567
  .then(() => onRecording("stopped"))
445
568
  .catch((error) => onError(error));
446
569
  });
@@ -472,6 +595,30 @@ export function createClient(options = {}) {
472
595
  socket.on("userBlocked", (payload) => {
473
596
  if (!closed) onUserBlocked(payload || {});
474
597
  });
598
+ // Capacity pack while someone publishes (e.g. host screen) may park this viewer.
599
+ socket.on("waiting", (payload = {}) => {
600
+ if (!closed) onStatus(payload.message || "Please wait, we will connect you soon");
601
+ });
602
+ socket.on("releaseConsumers", () => {
603
+ if (closed) return;
604
+ pending.length = 0;
605
+ try { recvTransport?.close(); } catch { /* ignore */ }
606
+ recvTransport = null;
607
+ clearRemoteTiles();
608
+ });
609
+ socket.on("edgeChanged", () => {
610
+ recoverRecvTransport().catch((error) => onError(error));
611
+ });
612
+ socket.on("newConsumer", (params) => {
613
+ play(params).catch((error) => onError(error));
614
+ });
615
+ socket.on("producerClosed", ({ producerId }) => {
616
+ for (let i = pending.length - 1; i >= 0; i -= 1) {
617
+ if (pending[i].producerId === producerId) pending.splice(i, 1);
618
+ }
619
+ if (tiles.delete(producerId)) syncRecording();
620
+ onTrackEnded({ producerId });
621
+ });
475
622
  socket.on("connect", async () => {
476
623
  try {
477
624
  if (closed) return;
@@ -494,37 +641,11 @@ export function createClient(options = {}) {
494
641
 
495
642
  const sendParams = await emit(socket, "createTransport", { direction: "send" });
496
643
  sendTransport = device.createSendTransport({ ...sendParams, iceServers });
497
- sendTransport.on("connect", ({ dtlsParameters }, callback, errback) => {
498
- emit(socket, "connectTransport", { transportId: sendTransport.id, dtlsParameters }).then(() => callback()).catch(errback);
499
- });
500
- sendTransport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => {
501
- emit(socket, "produce", {
502
- transportId: sendTransport.id,
503
- kind,
504
- rtpParameters,
505
- source: appData.source,
506
- }).then((result) => callback({ id: result.id })).catch(errback);
507
- });
508
- sendTransport.on("connectionstatechange", (state) => {
509
- if (state === "failed" || state === "disconnected") onStatus("Network unstable");
510
- else if (state === "connected") onStatus("Live");
511
- });
644
+ bindSendTransport(sendTransport);
512
645
 
513
646
  const recvParams = await emit(socket, "createTransport", { direction: "recv" });
514
647
  recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
515
- recvTransport.on("connect", ({ dtlsParameters }, callback, errback) => {
516
- emit(socket, "connectTransport", { transportId: recvTransport.id, dtlsParameters }).then(() => callback()).catch(errback);
517
- });
518
- socket.on("newConsumer", (params) => {
519
- play(params).catch((error) => onError(error));
520
- });
521
- socket.on("producerClosed", ({ producerId }) => {
522
- for (let i = pending.length - 1; i >= 0; i -= 1) {
523
- if (pending[i].producerId === producerId) pending.splice(i, 1);
524
- }
525
- if (tiles.delete(producerId)) syncRecording();
526
- onTrackEnded({ producerId });
527
- });
648
+ bindRecvTransport(recvTransport);
528
649
  const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
529
650
  for (const params of started.consumers || []) await play(params);
530
651
  // Fresh roster after ready (covers anyone who joined during transport setup).
@@ -708,8 +829,16 @@ export function createClient(options = {}) {
708
829
  }
709
830
  try {
710
831
  const screen = await produce("screen", videoTrack);
832
+ // Screen audio is optional — never tear down a live video share if mic capture fails.
711
833
  const audioTrack = stream.getAudioTracks()[0];
712
- if (audioTrack) await produce("screen", audioTrack);
834
+ if (audioTrack) {
835
+ try {
836
+ await produce("screen", audioTrack);
837
+ } catch (audioError) {
838
+ try { audioTrack.stop(); } catch { /* ignore */ }
839
+ onError(audioError);
840
+ }
841
+ }
713
842
  return screen;
714
843
  } catch (error) {
715
844
  stream.getTracks().forEach((track) => track.stop());
@@ -780,6 +909,44 @@ export function createClient(options = {}) {
780
909
  onRecording(next.capturing ? "recording" : "armed");
781
910
  }
782
911
 
912
+ async function openRecorder(recordingId) {
913
+ await ensureRecorderAffinity();
914
+ await emit(socket, "claimRecording", { recordingId });
915
+ if (closed || recorder) return;
916
+ const next = new CanvasRecorder({
917
+ webinarId: recordingWebinarId(sessionId),
918
+ webinarName: sessionId,
919
+ recordingId,
920
+ endpoint,
921
+ token,
922
+ selfName: displayName,
923
+ canvasBackground: recordingCanvasBackground,
924
+ // Chunks start immediately; empty stage uses the same host placeholder as live UI.
925
+ onCaptureChange: () => notifyRecording(next),
926
+ onFailure: (error) => {
927
+ if (recorder !== next) return;
928
+ recorder = null;
929
+ onRecording("stopped");
930
+ onError(error);
931
+ },
932
+ });
933
+ recorder = next;
934
+ next.wanted = true;
935
+ notifyRecording(next);
936
+ for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
937
+ next.sync(tracksForRecording(), stagePeopleForRecording());
938
+ try {
939
+ await next.start();
940
+ } catch (error) {
941
+ if (recorder === next) recorder = null;
942
+ onRecording("stopped");
943
+ throw error instanceof Error ? error : new Error(String(error));
944
+ }
945
+ if (recorder !== next) return;
946
+ activeRecordingId = recordingId;
947
+ notifyRecording(next);
948
+ }
949
+
783
950
  async function startRecording() {
784
951
  if (closed) throw new Error("The session has ended");
785
952
  if (!sendTransport) await connect();
@@ -791,38 +958,18 @@ export function createClient(options = {}) {
791
958
  }
792
959
  if (startingRecorder) return startingRecorder;
793
960
  startingRecorder = (async () => {
794
- await emit(socket, "claimRecording", {});
795
- if (closed || recorder) return;
796
- const next = new CanvasRecorder({
797
- webinarId: recordingWebinarId(sessionId),
798
- webinarName: sessionId,
799
- recordingId: await recordingIdFor(sessionId),
800
- endpoint,
801
- token,
802
- selfName: displayName,
803
- // Chunks start immediately; empty stage uses the same host placeholder as live UI.
804
- onCaptureChange: () => notifyRecording(next),
805
- onFailure: (error) => {
806
- if (recorder !== next) return;
807
- recorder = null;
808
- onRecording("stopped");
809
- onError(error);
810
- },
811
- });
812
- recorder = next;
813
- next.wanted = true;
814
- notifyRecording(next);
815
- for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
816
- next.sync(tracksForRecording(), stagePeopleForRecording());
961
+ // Prefer the session's stable id (handoff). If that take already finalized/failed,
962
+ // mint a new UUID so the host can record again in the same room.
963
+ let recordingId = activeRecordingId || await recordingIdFor(sessionId);
817
964
  try {
818
- await next.start();
965
+ await openRecorder(recordingId);
819
966
  } catch (error) {
820
- if (recorder === next) recorder = null;
821
- onRecording("stopped");
822
- throw error instanceof Error ? error : new Error(String(error));
967
+ const message = error instanceof Error ? error.message : String(error);
968
+ if (!/recording is already finished/i.test(message)) throw error;
969
+ recordingId = crypto.randomUUID();
970
+ activeRecordingId = recordingId;
971
+ await openRecorder(recordingId);
823
972
  }
824
- if (recorder !== next) return;
825
- notifyRecording(next);
826
973
  })();
827
974
  try {
828
975
  await startingRecorder;
@@ -837,27 +984,51 @@ export function createClient(options = {}) {
837
984
  onRecording("stopped");
838
985
  }
839
986
 
840
- async function end() {
987
+ /**
988
+ * Leave the session.
989
+ * options.finalize / options.endSession: start remux+upload now (no handoff).
990
+ * options.endSession: also ask the portal to disconnect everyone else — does not wait for remux.
991
+ */
992
+ async function end(options = {}) {
841
993
  if (closed) return;
842
994
  closed = true;
843
995
  settleReady?.(new Error("Ended"));
996
+ // Finalize only on explicit stop-session / finalize. Browser close uses disconnect handoff.
997
+ const forceFinalize = options.finalize === true || options.endSession === true;
844
998
  const current = recorder;
845
999
  recorder = null;
1000
+ if (forceFinalize) activeRecordingId = null;
846
1001
  try {
847
1002
  if (current) {
848
1003
  let handoff = false;
849
- if (socket?.connected) {
1004
+ if (forceFinalize) {
1005
+ // Stop-session: start remux immediately, do not await, do not change meet status.
1006
+ if (socket?.connected) {
1007
+ void emit(socket, "leaveRecording", { ending: true }).catch(() => {});
1008
+ }
1009
+ current.kickFinalize();
1010
+ void current.finish({ waitFinalize: false })
1011
+ .then(() => onRecording("stopped"))
1012
+ .catch((error) => onError(error));
1013
+ onRecording("stopped");
1014
+ } else if (socket?.connected) {
850
1015
  try {
851
1016
  const result = await emit(socket, "leaveRecording", {});
852
1017
  handoff = Boolean(result?.handoff);
853
1018
  } catch {
854
1019
  handoff = false;
855
1020
  }
1021
+ if (handoff) await current.handoff();
1022
+ else await current.finish();
1023
+ onRecording("stopped");
1024
+ } else {
1025
+ await current.finish();
1026
+ onRecording("stopped");
856
1027
  }
857
- // Cohost continues the same recordingId; only finalize when nobody else can take over.
858
- if (handoff) await current.handoff();
859
- else await current.finish();
860
- onRecording("stopped");
1028
+ }
1029
+ if (options.endSession === true && socket?.connected) {
1030
+ // Do not block leave/redirect on room teardown ack.
1031
+ void emit(socket, "endSession", {}).catch(() => {});
861
1032
  }
862
1033
  } finally {
863
1034
  for (const entry of locals.values()) {
@@ -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();