mediascale-sdk 1.0.4 → 1.0.6

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.
package/src/record.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createWorkerCompositor } from "./record-compositor.js";
2
+ export { FrameCompositor } from "./record-frame-compositor.js";
3
+
1
4
  const W = 1280;
2
5
  const H = 720;
3
6
  const COL = 240;
@@ -66,15 +69,22 @@ export function tracksFromTiles(tiles) {
66
69
  return out;
67
70
  }
68
71
 
69
- /** True when at least one live webcam / mic / screenshare track is present. */
72
+ /** Screen share and custom video (e.g. whiteboard) use the large featured slot. */
73
+ function isFeaturedVideoSource(source) {
74
+ return source === "screen" || (source && source !== "webcam");
75
+ }
76
+
77
+ /** True when at least one live webcam / mic / screenshare / custom track is present.
78
+ * Recording no longer gates on this; kept for apps that want the same check. */
70
79
  export function hasActiveMedia(tracks) {
71
80
  return (tracks || []).some((item) => {
72
81
  const track = item?.track;
73
82
  if (!track || track.readyState === "ended" || track.enabled === false) return false;
74
- return item.source === "webcam"
75
- || item.source === "mic"
76
- || item.source === "screen"
77
- || item.source === "screen-audio";
83
+ if (item.source === "webcam" || item.source === "mic" || item.source === "screen" || item.source === "screen-audio") {
84
+ return true;
85
+ }
86
+ // Custom streams (whiteboard, etc.) also keep recording alive.
87
+ return Boolean(item.source);
78
88
  });
79
89
  }
80
90
 
@@ -83,13 +93,15 @@ export class CanvasRecorder {
83
93
  return typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mime);
84
94
  }
85
95
 
86
- constructor({ webinarId, webinarName, recordingId, endpoint, token, onCaptureChange }) {
96
+ constructor({ webinarId, webinarName, recordingId, endpoint, token, selfName, onCaptureChange, onFailure }) {
87
97
  this.webinarId = webinarId;
88
98
  this.webinarName = webinarName || webinarId;
89
99
  this.recordingId = recordingId;
90
100
  this.endpoint = String(endpoint || "").replace(/\/+$/, "");
91
101
  this.token = token || "";
102
+ this.selfName = String(selfName || "Host").slice(0, 40);
92
103
  this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
104
+ this.onFailure = typeof onFailure === "function" ? onFailure : () => {};
93
105
  this.segment = 0;
94
106
  this.seq = 0;
95
107
  this.startedAt = 0;
@@ -99,8 +111,11 @@ export class CanvasRecorder {
99
111
  this.nextOrder = 1;
100
112
  this.videos = new Map();
101
113
  this.audioNodes = new Map();
114
+ this.placeholderSources = new Map();
102
115
  this.tries = new Map();
103
116
  this.chain = Promise.resolve();
117
+ this.pendingStores = new Set();
118
+ this.recorderStops = new WeakMap();
104
119
  this.finishing = false;
105
120
  this.prepared = false;
106
121
  this.capturing = false;
@@ -126,17 +141,36 @@ export class CanvasRecorder {
126
141
  this.ready = resolve;
127
142
  this.failed = reject;
128
143
  });
144
+ const markReady = () => {
145
+ this.ready?.();
146
+ this.ready = null;
147
+ this.failed = null;
148
+ };
149
+ const fail = (err) => {
150
+ const error = err instanceof Error ? err : new Error(String(err));
151
+ if (this.failed) {
152
+ this.failed(error);
153
+ this.ready = null;
154
+ this.failed = null;
155
+ } else {
156
+ this.onFailure(error);
157
+ this.onCaptureChange(false);
158
+ window.dispatchEvent(new CustomEvent("mediascale:recording-error", {
159
+ detail: { message: error.message },
160
+ }));
161
+ }
162
+ this.release?.();
163
+ };
129
164
  const run = async () => {
130
165
  try {
131
- // Prepare canvas/audio only. Chunks start after the first live A/V/screen track.
166
+ // Start chunks immediately (placeholder stage + silence until real media appears).
132
167
  await this.prepare(this.audio);
133
- this.ready();
168
+ if (this.finishing) return;
134
169
  await this.updateCapture();
135
170
  if (this.finishing) return;
136
171
  await this.untilStop;
137
172
  } catch (err) {
138
- this.failed(err instanceof Error ? err : new Error(String(err)));
139
- this.release?.();
173
+ fail(err);
140
174
  } finally {
141
175
  this.teardown();
142
176
  }
@@ -144,18 +178,38 @@ export class CanvasRecorder {
144
178
  if (navigator.locks) {
145
179
  void navigator.locks.request(`webinar-rec-${this.recordingId}`, { ifAvailable: true }, async (lock) => {
146
180
  if (!lock) {
147
- this.failed(new Error("Recording is already running in another tab"));
181
+ fail(new Error("Recording is already running in another tab"));
148
182
  this.teardown();
149
183
  return;
150
184
  }
185
+ markReady();
151
186
  await run();
152
187
  });
153
188
  } else {
189
+ markReady();
154
190
  void run();
155
191
  }
156
192
  await running;
157
193
  }
158
194
 
195
+ /** Resume AudioContext when the tab gets a gesture so live mics can mix later. */
196
+ armAudioUnlock() {
197
+ if (!this.audio || this.audio.state === "running" || this._audioUnlock) return;
198
+ const events = ["pointerdown", "keydown", "touchstart", "click"];
199
+ const unlock = async () => {
200
+ try {
201
+ await this.audio?.resume();
202
+ } catch {
203
+ return;
204
+ }
205
+ if (this.audio?.state !== "running") return;
206
+ for (const type of events) window.removeEventListener(type, unlock, true);
207
+ this._audioUnlock = null;
208
+ };
209
+ this._audioUnlock = unlock;
210
+ for (const type of events) window.addEventListener(type, unlock, true);
211
+ }
212
+
159
213
  sync(tracks) {
160
214
  this.tracks = tracks || [];
161
215
  if (this.prepared) this.retile();
@@ -165,9 +219,8 @@ export class CanvasRecorder {
165
219
  updateCapture() {
166
220
  const run = this.captureGate.then(async () => {
167
221
  if (this.finishing || !this.prepared) return;
168
- const live = hasActiveMedia(this.tracks);
169
- if (this.wanted && live && !this.capturing) await this.beginCapture();
170
- else if ((!this.wanted || !live) && this.capturing) await this.pauseCapture();
222
+ if (this.wanted && !this.capturing) await this.beginCapture();
223
+ else if (!this.wanted && this.capturing) await this.pauseCapture();
171
224
  });
172
225
  this.captureGate = run.catch(() => undefined);
173
226
  return run;
@@ -175,6 +228,7 @@ export class CanvasRecorder {
175
228
 
176
229
  /** Pause or resume capture without finalizing. New segments are combined on finish(). */
177
230
  async setWanted(wanted) {
231
+ if (wanted && this.compositorFailure) throw new Error("The recording worker stopped. Reconnect media before starting recording again.");
178
232
  this.wanted = Boolean(wanted);
179
233
  await this.updateCapture();
180
234
  }
@@ -183,36 +237,51 @@ export class CanvasRecorder {
183
237
  if (this.finishing) return;
184
238
  this.finishing = true;
185
239
  this.wanted = false;
186
- await this.captureGate.catch(() => undefined);
187
- const didCapture = Boolean(this.startedAt);
188
- if (this.capturing) {
189
- this.capturing = false;
190
- this.onCaptureChange(false);
191
- }
192
- const rec = this.recorder;
193
- this.recorder = null;
194
- if (rec && rec.state !== "inactive") {
195
- const last = new Promise((resolve) => {
196
- rec.addEventListener("dataavailable", () => resolve(), { once: true });
197
- rec.addEventListener("stop", () => resolve(), { once: true });
198
- });
199
- if (rec.state === "recording" || rec.state === "paused") {
200
- try { rec.requestData(); } catch { /* ignore */ }
201
- try { rec.stop(); } catch { /* ignore */ }
240
+ this.compositor?.setActive(false);
241
+ this.setDrawActive?.(false);
242
+ try {
243
+ await this.captureGate.catch(() => undefined);
244
+ const didCapture = Boolean(this.startedAt);
245
+ if (this.capturing) {
246
+ this.capturing = false;
247
+ this.onCaptureChange(false);
202
248
  }
203
- await Promise.race([last, sleep(3000)]);
249
+ const rec = this.recorder;
250
+ this.recorder = null;
251
+ await this.drainRecorder(rec);
252
+ await this.pump();
253
+ // Skip finalize when capture never started (e.g. prepare failed before beginCapture).
254
+ if (options.finalize !== false && didCapture) await this.finalize();
255
+ } finally {
256
+ this.release?.();
257
+ this.release = undefined;
204
258
  }
205
- await this.pump();
206
- // Skip finalize when nothing was ever captured (no live media during the session).
207
- if (options.finalize !== false && didCapture) await this.finalize();
208
- this.release?.();
209
- this.release = undefined;
210
259
  }
211
260
 
212
261
  async handoff() {
213
262
  await this.finish({ finalize: false });
214
263
  }
215
264
 
265
+ async drainRecorder(recorder) {
266
+ if (recorder) {
267
+ const stopped = this.recorderStops.get(recorder);
268
+ if (recorder.state === "recording" || recorder.state === "paused") {
269
+ recorder.requestData();
270
+ recorder.stop();
271
+ }
272
+ if (stopped) {
273
+ let timer;
274
+ try {
275
+ await Promise.race([stopped, new Promise((_, reject) => {
276
+ timer = setTimeout(() => reject(new Error("Recording did not finish writing its final media")), 3000);
277
+ })]);
278
+ } finally { clearTimeout(timer); }
279
+ }
280
+ }
281
+ await Promise.all([...this.pendingStores]);
282
+ if (this.storageFailure) throw this.storageFailure;
283
+ }
284
+
216
285
  url(path) {
217
286
  return `${this.endpoint}${path}`;
218
287
  }
@@ -238,17 +307,15 @@ export class CanvasRecorder {
238
307
  async prepare(audio) {
239
308
  if (this.finishing || this.prepared) return;
240
309
  this.audio = audio ?? new AudioContext();
241
- await this.audio.resume();
242
- if (this.audio.state !== "running") throw new Error("Click the page to continue this recording");
310
+ // Do not block on running AudioContext — suspended silence is enough to start chunks.
311
+ try {
312
+ await this.audio.resume();
313
+ } catch {
314
+ // gesture unlock is armed below
315
+ }
316
+ this.armAudioUnlock();
243
317
  if (this.finishing) return;
244
318
  await this.dropOtherWebinars();
245
- this.canvas = document.createElement("canvas");
246
- this.canvas.width = W;
247
- this.canvas.height = H;
248
- this.ctx = this.canvas.getContext("2d");
249
- this.canvas.setAttribute("aria-hidden", "true");
250
- this.canvas.style.cssText = "position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none";
251
- document.body.appendChild(this.canvas);
252
319
  await this.flushStored();
253
320
  if (this.finishing) return;
254
321
  this.dest = this.audio.createMediaStreamDestination();
@@ -258,13 +325,30 @@ export class CanvasRecorder {
258
325
  this.clock.connect(silence);
259
326
  silence.connect(this.dest);
260
327
  this.clock.start();
328
+ const { compositor, reason } = await createWorkerCompositor({ width: W, height: H, fps: FPS, onError: (failure) => {
329
+ this.compositorFailure = failure;
330
+ window.dispatchEvent(new CustomEvent("mediascale:recording-error", { detail: { message: failure.message } }));
331
+ void this.setWanted(false).catch(() => {});
332
+ } });
333
+ if (this.finishing) { compositor?.close(); return; }
334
+ this.compositor = compositor;
335
+ let video = compositor?.track;
336
+ if (!video) {
337
+ this.canvas = document.createElement("canvas");
338
+ this.canvas.width = W;
339
+ this.canvas.height = H;
340
+ this.ctx = this.canvas.getContext("2d");
341
+ this.ctx.fillStyle = "#000";
342
+ this.ctx.fillRect(0, 0, W, H);
343
+ const url = URL.createObjectURL(new Blob([`let tick; onmessage = ({data}) => { clearInterval(tick); if (data) tick = setInterval(() => postMessage(0), ${Math.round(1000 / FPS)}); };`], { type: "text/javascript" }));
344
+ const worker = new Worker(url);
345
+ worker.onmessage = () => this.draw();
346
+ this.setDrawActive = (active) => worker.postMessage(active);
347
+ this.stopDraw = () => { worker.terminate(); URL.revokeObjectURL(url); };
348
+ video = this.canvas.captureStream(FPS).getVideoTracks()[0];
349
+ }
350
+ window.dispatchEvent(new CustomEvent("mediascale:recording-mode", { detail: { mode: compositor ? "worker" : "foreground", reason } }));
261
351
  this.retile();
262
- this.ctx.fillStyle = "#000";
263
- this.ctx.fillRect(0, 0, W, H);
264
- const worker = new Worker(URL.createObjectURL(new Blob([`setInterval(() => postMessage(0), ${Math.round(1000 / FPS)})`], { type: "text/javascript" })));
265
- worker.onmessage = () => this.draw();
266
- this.stopDraw = () => worker.terminate();
267
- const video = this.canvas.captureStream(FPS).getVideoTracks()[0];
268
352
  this.capture = video;
269
353
  this.captureStream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
270
354
  this.prepared = true;
@@ -278,7 +362,7 @@ export class CanvasRecorder {
278
362
  webinarName: this.webinarName,
279
363
  next: true,
280
364
  });
281
- if (this.finishing || !hasActiveMedia(this.tracks)) return;
365
+ if (this.finishing) return;
282
366
  this.segment = opened.segment;
283
367
  this.seq = 0;
284
368
  if (!this.startedAt) this.startedAt = Date.now();
@@ -287,12 +371,16 @@ export class CanvasRecorder {
287
371
  videoBitsPerSecond: BITRATE,
288
372
  audioBitsPerSecond: 128_000,
289
373
  });
374
+ this.recorderStops.set(this.recorder, new Promise((resolve) => this.recorder.addEventListener("stop", resolve, { once: true })));
375
+ const recordingSegment = this.segment;
376
+ let sequence = 0;
290
377
  this.recorder.ondataavailable = (event) => {
291
- // Drop slices while nothing live is on stage (pause races / trailing ticks).
292
- if (!this.capturing || !hasActiveMedia(this.tracks)) return;
293
- if (event.data.size < 32 || !this.segment) return;
294
- const seq = ++this.seq;
295
- void this.store(seq, event.data).then(() => this.pump()).catch(() => undefined);
378
+ // Final data arrives after capturing becomes false. Keep its segment identity.
379
+ if (event.data.size < 32) return;
380
+ const storing = this.store(++sequence, event.data, recordingSegment);
381
+ this.pendingStores.add(storing);
382
+ void storing.then(() => this.pump()).catch(() => {});
383
+ void storing.catch((failure) => { this.storageFailure = failure; }).finally(() => this.pendingStores.delete(storing));
296
384
  };
297
385
  this.recorder.onerror = () => {
298
386
  void this.finish();
@@ -300,6 +388,9 @@ export class CanvasRecorder {
300
388
  if (this.finishing) return;
301
389
  this.recorder.start(SLICE_MS);
302
390
  this.capturing = true;
391
+ this.compositor?.setActive(true);
392
+ this.setDrawActive?.(true);
393
+ for (const video of this.videos.values()) void video.play().catch(() => {});
303
394
  this.onCaptureChange(true);
304
395
  try {
305
396
  this.wake = await navigator.wakeLock?.request("screen");
@@ -318,36 +409,32 @@ export class CanvasRecorder {
318
409
  async pauseCapture() {
319
410
  if (!this.capturing) return;
320
411
  this.capturing = false;
412
+ this.compositor?.setActive(false);
413
+ this.setDrawActive?.(false);
414
+ for (const video of this.videos.values()) video.pause();
321
415
  this.onCaptureChange(false);
322
416
  const rec = this.recorder;
323
417
  this.recorder = null;
324
- if (rec && rec.state !== "inactive") {
325
- const last = new Promise((resolve) => {
326
- rec.addEventListener("dataavailable", () => resolve(), { once: true });
327
- rec.addEventListener("stop", () => resolve(), { once: true });
328
- });
329
- if (rec.state === "recording" || rec.state === "paused") {
330
- try { rec.requestData(); } catch { /* ignore */ }
331
- try { rec.stop(); } catch { /* ignore */ }
332
- }
333
- await Promise.race([last, sleep(1500)]);
334
- }
335
- await this.pump().catch(() => undefined);
336
- if (this.heartbeat) {
337
- clearInterval(this.heartbeat);
338
- this.heartbeat = undefined;
339
- }
340
- if (this.sweep) {
341
- clearInterval(this.sweep);
342
- this.sweep = undefined;
343
- }
344
418
  try {
345
- await this.wake?.release();
346
- } catch {
347
- // ignore
419
+ await this.drainRecorder(rec);
420
+ await this.pump().catch(() => undefined);
421
+ } finally {
422
+ if (this.heartbeat) {
423
+ clearInterval(this.heartbeat);
424
+ this.heartbeat = undefined;
425
+ }
426
+ if (this.sweep) {
427
+ clearInterval(this.sweep);
428
+ this.sweep = undefined;
429
+ }
430
+ try {
431
+ await this.wake?.release();
432
+ } catch {
433
+ // ignore
434
+ }
435
+ this.wake = undefined;
436
+ this.segment = 0;
348
437
  }
349
- this.wake = undefined;
350
- this.segment = 0;
351
438
  }
352
439
 
353
440
  retile() {
@@ -378,9 +465,10 @@ export class CanvasRecorder {
378
465
  continue;
379
466
  }
380
467
  if (item.kind !== "video") continue;
381
- if (item.source !== "webcam" && item.source !== "screen") continue;
382
468
  if (disabled) continue;
383
- const kind = item.source === "screen" ? "screen" : "camera";
469
+ const featured = isFeaturedVideoSource(item.source);
470
+ if (!featured && item.source !== "webcam") continue;
471
+ const kind = featured ? "screen" : "camera";
384
472
  const key = `${item.participantKey}|${kind}`;
385
473
  const slot = {
386
474
  key,
@@ -388,7 +476,8 @@ export class CanvasRecorder {
388
476
  isLocal: item.isLocal,
389
477
  participantKey: item.participantKey,
390
478
  order: this.orderOf(key),
391
- video: this.videoFor(key, item.track),
479
+ video: this.compositor ? null : this.videoFor(key, item.track),
480
+ track: item.track,
392
481
  };
393
482
  (kind === "screen" ? screens : cameras).set(key, slot);
394
483
  }
@@ -400,7 +489,33 @@ export class CanvasRecorder {
400
489
  const chosen = (localCam ? [localCam, ...remotes] : remotes).slice(0, 4);
401
490
  const screen = [...screens.values()].find((slot) => slot.isLocal)
402
491
  ?? [...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
+ });
508
+ } else {
509
+ this.clearPlaceholders();
510
+ }
403
511
  this.slots = screen ? [screen, ...chosen] : chosen;
512
+ if (this.compositor) {
513
+ const layout = layoutSlots(chosen.length, Boolean(screen));
514
+ 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] })),
517
+ ]);
518
+ }
404
519
  // Mix every mic (and screen audio). Overflow cameras stay off-layout but audible.
405
520
  this.mixAudio(chosen, screen, mics, screenAudio);
406
521
  const liveKeys = new Set(this.slots.filter((slot) => slot.video).map((slot) => slot.key));
@@ -413,6 +528,45 @@ export class CanvasRecorder {
413
528
  }
414
529
  }
415
530
 
531
+ /** Synthetic webcam matching the live empty-stage avatar tile. */
532
+ ensurePlaceholderTrack(name, isLocal) {
533
+ const key = `placeholder|${isLocal ? "local" : name}`;
534
+ let entry = this.placeholderSources.get(key);
535
+ if (entry) {
536
+ entry.name = name;
537
+ entry.isLocal = isLocal;
538
+ entry.redraw();
539
+ return entry.track;
540
+ }
541
+ const canvas = document.createElement("canvas");
542
+ canvas.width = 640;
543
+ canvas.height = 360;
544
+ const ctx = canvas.getContext("2d");
545
+ const stream = canvas.captureStream(FPS);
546
+ const track = stream.getVideoTracks()[0];
547
+ entry = { track, canvas, name, isLocal, redraw: null, timer: null };
548
+ entry.redraw = () => {
549
+ drawStagePlaceholder(ctx, 0, 0, canvas.width, canvas.height, entry.name, entry.isLocal);
550
+ track.requestFrame?.();
551
+ };
552
+ entry.timer = setInterval(entry.redraw, Math.round(1000 / FPS));
553
+ this.placeholderSources.set(key, entry);
554
+ entry.redraw();
555
+ return track;
556
+ }
557
+
558
+ clearPlaceholders() {
559
+ for (const entry of this.placeholderSources.values()) {
560
+ clearInterval(entry.timer);
561
+ try {
562
+ entry.track.stop();
563
+ } catch {
564
+ // already ended
565
+ }
566
+ }
567
+ this.placeholderSources.clear();
568
+ }
569
+
416
570
  orderOf(key) {
417
571
  let n = this.orders.get(key);
418
572
  if (!n) {
@@ -432,7 +586,7 @@ export class CanvasRecorder {
432
586
  el.muted = true;
433
587
  el.playsInline = true;
434
588
  el.srcObject = new MediaStream([track]);
435
- void el.play().catch(() => undefined);
589
+ if (this.capturing) void el.play().catch(() => undefined);
436
590
  const refresh = () => {
437
591
  if (!this.dest || this.finishing) return;
438
592
  queueMicrotask(() => {
@@ -472,7 +626,7 @@ export class CanvasRecorder {
472
626
  }
473
627
 
474
628
  draw() {
475
- if (!this.ctx) return;
629
+ if (!this.ctx || !this.capturing) return;
476
630
  const cameras = this.slots.filter((slot) => slot.kind === "camera");
477
631
  const screen = this.slots.find((slot) => slot.kind === "screen");
478
632
  const layout = layoutSlots(cameras.length, Boolean(screen));
@@ -481,7 +635,12 @@ export class CanvasRecorder {
481
635
  if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen);
482
636
  cameras.forEach((slot, index) => {
483
637
  const rect = layout.cameras[index];
484
- if (rect) paint(this.ctx, slot.video, rect);
638
+ if (!rect) return;
639
+ if (slot.placeholder) {
640
+ drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, slot.displayName || this.selfName, true);
641
+ return;
642
+ }
643
+ paint(this.ctx, slot.video, rect);
485
644
  });
486
645
  this.capture?.requestFrame();
487
646
  }
@@ -492,8 +651,8 @@ export class CanvasRecorder {
492
651
  db.close();
493
652
  }
494
653
 
495
- async store(seq, blob) {
496
- const row = { webinarId: this.webinarId, recordingId: this.recordingId, segment: this.segment, seq, blob };
654
+ async store(seq, blob, segment = this.segment) {
655
+ const row = { webinarId: this.webinarId, recordingId: this.recordingId, segment, seq, blob };
497
656
  const db = await dbOpen();
498
657
  await idbPut(db, row);
499
658
  db.close();
@@ -584,15 +743,24 @@ export class CanvasRecorder {
584
743
  teardown() {
585
744
  this.canvas?.remove();
586
745
  window.removeEventListener("beforeunload", this.onPageHide);
746
+ if (this._audioUnlock) {
747
+ for (const type of ["pointerdown", "keydown", "touchstart", "click"]) {
748
+ window.removeEventListener(type, this._audioUnlock, true);
749
+ }
750
+ this._audioUnlock = null;
751
+ }
587
752
  if (this.heartbeat) clearInterval(this.heartbeat);
588
753
  if (this.sweep) clearInterval(this.sweep);
589
754
  this.stopDraw?.();
755
+ this.compositor?.close();
756
+ this.capture?.stop();
590
757
  if (this.recorder && this.recorder.state !== "inactive") this.recorder.stop();
591
758
  this.videos.forEach((el) => {
592
759
  el.pause();
593
760
  el.srcObject = null;
594
761
  });
595
762
  this.videos.clear();
763
+ this.clearPlaceholders();
596
764
  try {
597
765
  this.clock?.stop();
598
766
  } catch {
@@ -605,6 +773,48 @@ export class CanvasRecorder {
605
773
  }
606
774
  }
607
775
 
776
+ function placeholderLetter(name) {
777
+ const text = String(name || "?").trim();
778
+ return text ? text[0].toUpperCase() : "?";
779
+ }
780
+
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;
790
+ ctx.fillRect(x, y, w, h);
791
+
792
+ const radius = Math.min(w, h) * 0.16;
793
+ ctx.beginPath();
794
+ ctx.arc(cx, cy, radius, 0, Math.PI * 2);
795
+ ctx.fillStyle = "rgba(255, 255, 255, 0.1)";
796
+ ctx.fill();
797
+ ctx.lineWidth = Math.max(2, radius * 0.06);
798
+ ctx.strokeStyle = "rgba(255, 255, 255, 0.72)";
799
+ ctx.stroke();
800
+
801
+ ctx.fillStyle = "#fff";
802
+ ctx.font = `700 ${Math.round(radius * 1.15)}px Mulish, "Segoe UI", sans-serif`;
803
+ ctx.textAlign = "center";
804
+ ctx.textBaseline = "middle";
805
+ ctx.fillText(placeholderLetter(name), cx, cy + 1);
806
+
807
+ const label = `${String(name || "Host").slice(0, 40)}${isLocal ? " (You)" : ""}`;
808
+ const pad = Math.max(12, Math.round(h * 0.04));
809
+ 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);
816
+ }
817
+
608
818
  function paint(ctx, video, rect) {
609
819
  ctx.fillStyle = "#000";
610
820
  ctx.fillRect(rect.x, rect.y, rect.w, rect.h);