mediascale-sdk 1.0.11 → 1.0.13

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
@@ -3,19 +3,37 @@ import {
3
3
  fillRadialBackground,
4
4
  paintRoundedTile,
5
5
  drawNamePill,
6
- strokeTileBorder,
7
6
  roundedRectPath,
7
+ fillNameTone,
8
+ drawInitialAvatar,
9
+ STAGE_BACKGROUND,
10
+ PRESENTER_ACCENT,
11
+ } from "./record-frame-compositor.js";
12
+ export {
13
+ FrameCompositor,
14
+ fillRadialBackground,
15
+ PRESENTER_ACCENT,
16
+ STAGE_BACKGROUND,
8
17
  } from "./record-frame-compositor.js";
9
- export { FrameCompositor, fillRadialBackground } from "./record-frame-compositor.js";
10
18
 
11
19
  const W = 1280;
12
20
  const H = 720;
13
- const COL = 240;
14
- /** Match reference stage: even outer margin and gutters between tiles. */
15
- const PAD = 16;
16
- const GAP = 16;
17
- const TILE_RADIUS = 14;
18
- const FPS = 15;
21
+ /** Outer margin around the whole layout. */
22
+ const PAD = 28;
23
+ /**
24
+ * Single gutter used everywhere: screenshare ↔ camera rail, and between camera tiles.
25
+ * Keep one value so spacing stays uniform.
26
+ */
27
+ const GAP = 12;
28
+ /** No rounded corners on recording tiles (square). */
29
+ const TILE_RADIUS = 0;
30
+ const SCREEN_RADIUS = 0;
31
+ /** Sidebar share of the inner content width when screenshare is active. */
32
+ const SIDE_FRAC = 0.22;
33
+ /** Default recording frame rate. Override with createClient({ recordingFps }). */
34
+ export const DEFAULT_RECORDING_FPS = 15;
35
+ const MIN_FPS = 1;
36
+ const MAX_FPS = 60;
19
37
  const SLICE_MS = 5000;
20
38
  /** Hard cap for on-canvas camera / avatar tiles (host included). Audio is uncapped. */
21
39
  const MAX_STAGE_CAMERAS = 6;
@@ -23,48 +41,148 @@ const MAX_STAGE_CAMERAS = 6;
23
41
  const BITRATE = 4_500_000;
24
42
  const mime = "video/webm;codecs=vp8,opus";
25
43
 
44
+ /** Clamp a configured frame rate to 1–60 (fallback when missing or invalid). */
45
+ export function clampFps(value, fallback = DEFAULT_RECORDING_FPS) {
46
+ const n = Math.round(Number(value));
47
+ if (!Number.isFinite(n) || n <= 0) return fallback;
48
+ return Math.max(MIN_FPS, Math.min(MAX_FPS, n));
49
+ }
50
+
26
51
  /** Channel ids become a single path segment. The original text stays the webinar name. */
27
52
  export function recordingWebinarId(channelId) {
28
53
  const cleaned = String(channelId || "").trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 128);
29
54
  return cleaned || "webinar";
30
55
  }
31
56
 
32
- /** Equal tiles, or one screenshare with cameras stacked from the top in a side column. Up to 6 cameras. */
33
- export function layoutSlots(cameras, screen) {
34
- const n = Math.max(0, Math.min(MAX_STAGE_CAMERAS, Number(cameras) || 0));
35
- // One tile only — fill the canvas so recordingCanvasBackground is not visible as a border.
36
- if (screen && n === 0) {
37
- return { screen: { x: 0, y: 0, w: W, h: H }, cameras: [] };
57
+ const RECORDER_AFFINITY_RETRIES = 3;
58
+ const RECORDER_AFFINITY_KEY = (webinarId) => `mediascale:ms_recorder:${webinarId}`;
59
+
60
+ export function readStoredRecorderPeer(webinarId) {
61
+ try {
62
+ if (typeof sessionStorage === "undefined") return "";
63
+ return String(sessionStorage.getItem(RECORDER_AFFINITY_KEY(webinarId)) || "").trim();
64
+ } catch {
65
+ return "";
38
66
  }
39
- if (!screen && n === 1) {
40
- return { cameras: [{ x: 0, y: 0, w: W, h: H }] };
67
+ }
68
+
69
+ export function writeStoredRecorderPeer(webinarId, peer) {
70
+ const value = String(peer || "").trim();
71
+ if (!value) return;
72
+ try {
73
+ if (typeof sessionStorage !== "undefined") {
74
+ sessionStorage.setItem(RECORDER_AFFINITY_KEY(webinarId), value);
75
+ }
76
+ } catch {
77
+ /* private mode */
78
+ }
79
+ // Cookie remains a single-tab fallback; multi-session routing uses ?ms_recorder=.
80
+ if (typeof document !== "undefined") {
81
+ document.cookie = `ms_recorder=${encodeURIComponent(value)}; Path=/; Max-Age=86400; SameSite=Lax`;
82
+ }
83
+ }
84
+
85
+ /** Resolve sticky recorder peer for a webinar (seed affinity → pin → peer name). */
86
+ export async function resolveRecorderAffinity({ endpoint, webinarId, force = false } = {}) {
87
+ const id = recordingWebinarId(webinarId);
88
+ if (!force) {
89
+ const stored = readStoredRecorderPeer(id);
90
+ if (stored) return stored;
41
91
  }
92
+ const base = String(endpoint || "").replace(/\/+$/, "");
93
+ const response = await fetch(
94
+ `${base}/recorder/api/v1/affinity?webinarId=${encodeURIComponent(id)}`,
95
+ { credentials: "include" },
96
+ );
97
+ if (!response.ok) {
98
+ const body = await response.json().catch(() => null);
99
+ throw new Error(body?.error || `Recorder affinity failed (${response.status})`);
100
+ }
101
+ const body = await response.json().catch(() => null);
102
+ const peer = String(body?.peer || "").trim();
103
+ if (!peer) throw new Error("Recorder affinity returned no peer");
104
+ writeStoredRecorderPeer(id, peer);
105
+ return peer;
106
+ }
107
+
108
+ function isRecorderRouteError(error, status = 0) {
109
+ if (status === 502 || status === 503 || status === 504) return true;
110
+ const msg = String(error?.message || error || "");
111
+ return /recorder|affinity|502|503|504|network|reach|failed to fetch|could not assign/i.test(msg);
112
+ }
113
+
114
+ function galleryColumns(n) {
115
+ if (n <= 1) return 1;
116
+ if (n <= 4) return 2;
117
+ return 3;
118
+ }
119
+
120
+ /**
121
+ * Design layout: padded 16:9 gallery (incomplete last row centered), or screenshare
122
+ * left (~78%) + up to 6 camera tiles stacked on the right. Max 6 cameras.
123
+ */
124
+ export function layoutSlots(cameras, screen) {
125
+ const n = Math.max(0, Math.min(MAX_STAGE_CAMERAS, Number(cameras) || 0));
126
+ const innerW = W - PAD * 2;
127
+ const innerH = H - PAD * 2;
128
+
42
129
  if (screen) {
43
- const mainW = W - COL - PAD * 2 - GAP;
44
- const mainH = H - PAD * 2;
45
- // Fixed tile height so up to 6 fit; fewer cameras stack from the top (not stretched apart).
46
- const tileH = Math.floor((mainH - GAP * (MAX_STAGE_CAMERAS - 1)) / MAX_STAGE_CAMERAS);
130
+ if (n === 0) {
131
+ return { screen: { x: PAD, y: PAD, w: innerW, h: innerH, radius: SCREEN_RADIUS }, cameras: [] };
132
+ }
133
+ const sideSlotW = Math.round(innerW * SIDE_FRAC);
134
+ const mainW = innerW - sideSlotW - GAP;
135
+ let tileW = sideSlotW;
136
+ let tileH = Math.max(1, Math.round((tileW * 9) / 16));
137
+ let stackH = n * tileH + (n - 1) * GAP;
138
+ if (stackH > innerH) {
139
+ tileH = Math.max(1, Math.floor((innerH - (n - 1) * GAP) / n));
140
+ tileW = Math.max(1, Math.round((tileH * 16) / 9));
141
+ stackH = n * tileH + (n - 1) * GAP;
142
+ }
143
+ const sideX = PAD + mainW + GAP + Math.round((sideSlotW - tileW) / 2);
144
+ const y0 = PAD + Math.round((innerH - stackH) / 2);
47
145
  return {
48
- screen: { x: PAD, y: PAD, w: mainW, h: mainH },
146
+ screen: { x: PAD, y: PAD, w: mainW, h: innerH, radius: SCREEN_RADIUS },
49
147
  cameras: Array.from({ length: n }, (_, i) => ({
50
- x: PAD + mainW + GAP,
51
- y: PAD + i * (tileH + GAP),
52
- w: COL,
148
+ x: sideX,
149
+ y: y0 + i * (tileH + GAP),
150
+ w: tileW,
53
151
  h: tileH,
152
+ radius: TILE_RADIUS,
54
153
  })),
55
154
  };
56
155
  }
57
- const cols = n <= 1 ? 1 : n <= 2 ? 2 : n <= 4 ? 2 : 3;
156
+
157
+ if (n === 0) return { cameras: [] };
158
+
159
+ const cols = galleryColumns(n);
58
160
  const rows = Math.max(1, Math.ceil(n / cols));
59
- const cellW = Math.floor((W - PAD * 2 - GAP * (cols - 1)) / cols);
60
- const cellH = Math.floor((H - PAD * 2 - GAP * (rows - 1)) / rows);
161
+ let tileW = Math.floor((innerW - (cols - 1) * GAP) / cols);
162
+ let tileH = Math.max(1, Math.round((tileW * 9) / 16));
163
+ let gridH = rows * tileH + (rows - 1) * GAP;
164
+ if (gridH > innerH) {
165
+ tileH = Math.max(1, Math.floor((innerH - (rows - 1) * GAP) / rows));
166
+ tileW = Math.max(1, Math.round((tileH * 16) / 9));
167
+ gridH = rows * tileH + (rows - 1) * GAP;
168
+ }
169
+ const originY = Math.round((H - gridH) / 2);
170
+
61
171
  return {
62
- cameras: Array.from({ length: n }, (_, i) => ({
63
- x: PAD + (i % cols) * (cellW + GAP),
64
- y: PAD + Math.floor(i / cols) * (cellH + GAP),
65
- w: cellW,
66
- h: cellH,
67
- })),
172
+ cameras: Array.from({ length: n }, (_, i) => {
173
+ const row = Math.floor(i / cols);
174
+ const col = i % cols;
175
+ const inRow = row === rows - 1 ? n - row * cols : cols;
176
+ const rowW = inRow * tileW + (inRow - 1) * GAP;
177
+ const rowX = Math.round((W - rowW) / 2);
178
+ return {
179
+ x: rowX + col * (tileW + GAP),
180
+ y: originY + row * (tileH + GAP),
181
+ w: tileW,
182
+ h: tileH,
183
+ radius: TILE_RADIUS,
184
+ };
185
+ }),
68
186
  };
69
187
  }
70
188
 
@@ -119,12 +237,16 @@ function resolveTileLabel(slot, selfName) {
119
237
  return "Guest";
120
238
  }
121
239
 
122
- function isFullBleedRect(rect) {
123
- return rect
124
- && rect.x <= 0
125
- && rect.y <= 0
126
- && rect.w >= W - 1
127
- && rect.h >= H - 1;
240
+ function hasLiveMic(slot, mics) {
241
+ if (!mics || typeof mics.has !== "function") return false;
242
+ if (slot?.isLocal) return mics.has("local-mic");
243
+ const key = String(slot?.participantKey || "").trim();
244
+ if (!key) return false;
245
+ return mics.has(`${key}|mic`);
246
+ }
247
+
248
+ function isPresenterSlot(slot, label) {
249
+ return Boolean(slot?.isLocal) || /presenter/i.test(String(label || ""));
128
250
  }
129
251
 
130
252
  /** Screen share and custom video (e.g. whiteboard) use the large featured slot. */
@@ -151,16 +273,39 @@ export class CanvasRecorder {
151
273
  return typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mime);
152
274
  }
153
275
 
154
- constructor({ webinarId, webinarName, recordingId, endpoint, token, selfName, canvasBackground, onCaptureChange, onFailure }) {
276
+ constructor({
277
+ webinarId,
278
+ webinarName,
279
+ recordingId,
280
+ endpoint,
281
+ token,
282
+ selfName,
283
+ canvasBackground,
284
+ recorderPeer,
285
+ onCaptureChange,
286
+ onFailure,
287
+ fps,
288
+ bitrate,
289
+ }) {
290
+ /** Compositor + capture frame rate (recording and live output can differ). */
291
+ this.fps = clampFps(fps);
292
+ this.bitrate = Number(bitrate) > 0 ? Math.round(Number(bitrate)) : BITRATE;
293
+ /** Window event prefix: "recording" here, "live" for the RTMP compositor. */
294
+ this.eventPrefix = "recording";
295
+ /** Worker compositor emits frames only on change unless steady (live output sets this). */
296
+ this.steadyFrames = false;
155
297
  this.webinarId = webinarId;
156
298
  this.webinarName = webinarName || webinarId;
157
299
  this.recordingId = recordingId;
158
300
  this.endpoint = String(endpoint || "").replace(/\/+$/, "");
301
+ /** Sticky nginx peer for this webinar (query beats cookie). */
302
+ this.recorderPeer = String(recorderPeer || readStoredRecorderPeer(webinarId) || "").trim();
303
+ if (this.recorderPeer) writeStoredRecorderPeer(this.webinarId, this.recorderPeer);
159
304
  /** @type {{ id: string, name: string, local?: boolean }[] | null} */
160
305
  this.stagePeople = null;
161
306
  this.token = token || "";
162
307
  this.selfName = String(selfName || "Host").slice(0, 40);
163
- this.canvasBackground = String(canvasBackground || "").trim() || "#2563eb";
308
+ this.canvasBackground = String(canvasBackground || "").trim() || STAGE_BACKGROUND;
164
309
  this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
165
310
  this.onFailure = typeof onFailure === "function" ? onFailure : () => {};
166
311
  this.segment = 0;
@@ -217,7 +362,7 @@ export class CanvasRecorder {
217
362
  } else {
218
363
  this.onFailure(error);
219
364
  this.onCaptureChange(false);
220
- window.dispatchEvent(new CustomEvent("mediascale:recording-error", {
365
+ window.dispatchEvent(new CustomEvent(`mediascale:${this.eventPrefix}-error`, {
221
366
  detail: { message: error.message },
222
367
  }));
223
368
  }
@@ -391,7 +536,10 @@ export class CanvasRecorder {
391
536
  }
392
537
 
393
538
  url(path) {
394
- return `${this.endpoint}${path}`;
539
+ const base = `${this.endpoint}${path}`;
540
+ if (!this.recorderPeer) return base;
541
+ const sep = String(path).includes("?") ? "&" : "?";
542
+ return `${base}${sep}ms_recorder=${encodeURIComponent(this.recorderPeer)}`;
395
543
  }
396
544
 
397
545
  authHeaders(extra = {}) {
@@ -401,16 +549,51 @@ export class CanvasRecorder {
401
549
  };
402
550
  }
403
551
 
552
+ async refreshAffinity({ force = true } = {}) {
553
+ const peer = await resolveRecorderAffinity({
554
+ endpoint: this.endpoint,
555
+ webinarId: this.webinarId,
556
+ force,
557
+ });
558
+ this.recorderPeer = peer;
559
+ return peer;
560
+ }
561
+
562
+ async withRecorderRetry(run) {
563
+ let lastError = null;
564
+ for (let attempt = 1; attempt <= RECORDER_AFFINITY_RETRIES; attempt += 1) {
565
+ try {
566
+ if (!this.recorderPeer) await this.refreshAffinity({ force: attempt > 1 });
567
+ return await run();
568
+ } catch (error) {
569
+ lastError = error;
570
+ const status = Number(error?.status || 0);
571
+ if (attempt >= RECORDER_AFFINITY_RETRIES || !isRecorderRouteError(error, status)) {
572
+ throw error instanceof Error ? error : new Error(String(error));
573
+ }
574
+ await this.refreshAffinity({ force: true });
575
+ await sleep(250 * attempt);
576
+ }
577
+ }
578
+ throw lastError instanceof Error ? lastError : new Error(String(lastError || "Recorder request failed"));
579
+ }
580
+
404
581
  async api(method, path, body) {
405
- const res = await fetch(this.url(path), {
406
- method,
407
- credentials: "include",
408
- headers: this.authHeaders({ "content-type": "application/json" }),
409
- body: body === undefined ? "{}" : JSON.stringify(body),
582
+ return this.withRecorderRetry(async () => {
583
+ const res = await fetch(this.url(path), {
584
+ method,
585
+ credentials: "include",
586
+ headers: this.authHeaders({ "content-type": "application/json" }),
587
+ body: body === undefined ? "{}" : JSON.stringify(body),
588
+ });
589
+ const data = await res.json().catch(() => ({}));
590
+ if (!res.ok) {
591
+ const err = new Error(data.error ?? "recording upload failed");
592
+ err.status = res.status;
593
+ throw err;
594
+ }
595
+ return data;
410
596
  });
411
- const data = await res.json().catch(() => ({}));
412
- if (!res.ok) throw new Error(data.error ?? "recording upload failed");
413
- return data;
414
597
  }
415
598
 
416
599
  async prepare(audio) {
@@ -437,11 +620,12 @@ export class CanvasRecorder {
437
620
  const { compositor, reason } = await createWorkerCompositor({
438
621
  width: W,
439
622
  height: H,
440
- fps: FPS,
623
+ fps: this.fps,
624
+ steady: this.steadyFrames,
441
625
  background: this.canvasBackground,
442
626
  onError: (failure) => {
443
627
  this.compositorFailure = failure;
444
- window.dispatchEvent(new CustomEvent("mediascale:recording-error", { detail: { message: failure.message } }));
628
+ window.dispatchEvent(new CustomEvent(`mediascale:${this.eventPrefix}-error`, { detail: { message: failure.message } }));
445
629
  void this.setWanted(false).catch(() => {});
446
630
  },
447
631
  });
@@ -454,14 +638,14 @@ export class CanvasRecorder {
454
638
  this.canvas.height = H;
455
639
  this.ctx = this.canvas.getContext("2d");
456
640
  fillRadialBackground(this.ctx, 0, 0, W, H, this.canvasBackground);
457
- 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" }));
641
+ const url = URL.createObjectURL(new Blob([`let tick; onmessage = ({data}) => { clearInterval(tick); if (data) tick = setInterval(() => postMessage(0), ${Math.round(1000 / this.fps)}); };`], { type: "text/javascript" }));
458
642
  const worker = new Worker(url);
459
643
  worker.onmessage = () => this.draw();
460
644
  this.setDrawActive = (active) => worker.postMessage(active);
461
645
  this.stopDraw = () => { worker.terminate(); URL.revokeObjectURL(url); };
462
- video = this.canvas.captureStream(FPS).getVideoTracks()[0];
646
+ video = this.canvas.captureStream(this.fps).getVideoTracks()[0];
463
647
  }
464
- window.dispatchEvent(new CustomEvent("mediascale:recording-mode", { detail: { mode: compositor ? "worker" : "foreground", reason } }));
648
+ window.dispatchEvent(new CustomEvent(`mediascale:${this.eventPrefix}-mode`, { detail: { mode: compositor ? "worker" : "foreground", reason } }));
465
649
  this.retile();
466
650
  this.capture = video;
467
651
  this.captureStream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
@@ -481,7 +665,7 @@ export class CanvasRecorder {
481
665
  if (!this.startedAt) this.startedAt = Date.now();
482
666
  this.recorder = new MediaRecorder(this.captureStream, {
483
667
  mimeType: mime,
484
- videoBitsPerSecond: BITRATE,
668
+ videoBitsPerSecond: this.bitrate,
485
669
  audioBitsPerSecond: 128_000,
486
670
  });
487
671
  this.recorderStops.set(this.recorder, new Promise((resolve) => this.recorder.addEventListener("stop", resolve, { once: true })));
@@ -679,6 +863,16 @@ export class CanvasRecorder {
679
863
  });
680
864
  }
681
865
  }
866
+ // Attach mic / presenter chrome onto camera slots for both compositor paths.
867
+ chosen = chosen.map((slot) => {
868
+ const label = resolveTileLabel(slot, this.selfName);
869
+ return {
870
+ ...slot,
871
+ displayName: label,
872
+ micMuted: !hasLiveMic(slot, mics),
873
+ presenter: isPresenterSlot(slot, label),
874
+ };
875
+ });
682
876
  this.prunePlaceholders(keepPlaceholders);
683
877
  this.slots = screen ? [screen, ...chosen] : chosen;
684
878
  if (this.compositor) {
@@ -688,23 +882,28 @@ export class CanvasRecorder {
688
882
  key: screen.key,
689
883
  track: screen.track,
690
884
  rect: layout.screen,
691
- crop: screen.crop || null,
885
+ crop: null,
692
886
  label: "",
693
887
  accent: false,
888
+ muted: false,
889
+ fit: "contain",
890
+ fillStyle: this.canvasBackground || STAGE_BACKGROUND,
891
+ radius: layout.screen?.radius ?? SCREEN_RADIUS,
892
+ placeholder: false,
694
893
  }] : []),
695
894
  ...chosen.map((slot, index) => {
696
895
  const rect = layout.cameras[index];
697
- const label = resolveTileLabel(slot, this.selfName);
698
- const fullBleed = isFullBleedRect(rect);
699
896
  return {
700
897
  key: slot.key,
701
898
  track: slot.track,
702
899
  rect,
703
900
  crop: null,
704
- label,
705
- // Presenter / local host gets the accent glow border from the brand color.
706
- accent: !fullBleed && (Boolean(slot.isLocal) || /presenter/i.test(label)),
707
- radius: fullBleed ? 0 : TILE_RADIUS,
901
+ label: slot.displayName,
902
+ accent: false,
903
+ radius: rect?.radius ?? TILE_RADIUS,
904
+ muted: false,
905
+ fit: "cover",
906
+ placeholder: Boolean(slot.placeholder),
708
907
  };
709
908
  }),
710
909
  ]);
@@ -735,15 +934,15 @@ export class CanvasRecorder {
735
934
  canvas.width = W;
736
935
  canvas.height = H;
737
936
  const ctx = canvas.getContext("2d", { alpha: false, desynchronized: true });
738
- const stream = canvas.captureStream(FPS);
937
+ const stream = canvas.captureStream(this.fps);
739
938
  const track = stream.getVideoTracks()[0];
740
939
  entry = { track, canvas, name, isLocal, redraw: null, timer: null };
741
940
  entry.redraw = () => {
742
941
  // Full-frame synthetic track: avatar only. Tile chrome/name are drawn on the layout rect.
743
- drawStagePlaceholder(ctx, 0, 0, canvas.width, canvas.height, entry.name, false, "#2563eb", { chrome: false });
942
+ drawStagePlaceholder(ctx, 0, 0, canvas.width, canvas.height, entry.name, false, STAGE_BACKGROUND, { chrome: false });
744
943
  track.requestFrame?.();
745
944
  };
746
- entry.timer = setInterval(entry.redraw, Math.round(1000 / FPS));
945
+ entry.timer = setInterval(entry.redraw, Math.round(1000 / this.fps));
747
946
  this.placeholderSources.set(key, entry);
748
947
  entry.redraw();
749
948
  return track;
@@ -832,31 +1031,34 @@ export class CanvasRecorder {
832
1031
  const layout = layoutSlots(cameras.length, Boolean(screen));
833
1032
  fillRadialBackground(this.ctx, 0, 0, W, H, this.canvasBackground);
834
1033
  if (screen && layout.screen) {
835
- paint(this.ctx, screen.video, layout.screen, screen.crop, {
1034
+ paint(this.ctx, screen.video, layout.screen, null, {
836
1035
  label: "",
837
1036
  accent: false,
838
1037
  accentColor: this.canvasBackground,
1038
+ fit: "contain",
1039
+ fillStyle: this.canvasBackground || STAGE_BACKGROUND,
1040
+ radius: layout.screen.radius ?? SCREEN_RADIUS,
839
1041
  });
840
1042
  }
841
1043
  cameras.forEach((slot, index) => {
842
1044
  const rect = layout.cameras[index];
843
1045
  if (!rect) return;
844
1046
  const label = resolveTileLabel(slot, this.selfName);
845
- const fullBleed = isFullBleedRect(rect);
846
- const accent = !fullBleed && (Boolean(slot.isLocal) || /presenter/i.test(label));
847
- const radius = fullBleed ? 0 : TILE_RADIUS;
1047
+ const radius = rect.radius ?? TILE_RADIUS;
848
1048
  if (slot.placeholder) {
849
- drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, label, accent, this.canvasBackground, {
1049
+ drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, label, false, STAGE_BACKGROUND, {
850
1050
  chrome: true,
851
1051
  radius,
1052
+ muted: false,
852
1053
  });
853
1054
  return;
854
1055
  }
855
1056
  paint(this.ctx, slot.video, rect, null, {
856
1057
  label,
857
- accent,
858
- accentColor: this.canvasBackground,
1058
+ accent: false,
1059
+ accentColor: PRESENTER_ACCENT,
859
1060
  radius,
1061
+ muted: false,
860
1062
  });
861
1063
  });
862
1064
  this.capture?.requestFrame();
@@ -904,17 +1106,29 @@ export class CanvasRecorder {
904
1106
 
905
1107
  async upload(row) {
906
1108
  const checksum = await sha256(row.blob);
907
- const res = await fetch(this.url(`/api/chunks/${this.recordingId}/${row.segment}/${row.seq}`), {
908
- method: "PUT",
909
- credentials: "include",
910
- headers: this.authHeaders({ "content-type": "application/octet-stream", "x-checksum": checksum }),
911
- body: row.blob,
912
- });
913
- if (!res.ok) return false;
914
- const db = await dbOpen();
915
- await idbDel(db, row);
916
- db.close();
917
- return true;
1109
+ for (let attempt = 1; attempt <= RECORDER_AFFINITY_RETRIES; attempt += 1) {
1110
+ if (!this.recorderPeer) {
1111
+ try { await this.refreshAffinity({ force: attempt > 1 }); } catch { /* cookie may still route */ }
1112
+ }
1113
+ const res = await fetch(this.url(`/api/chunks/${this.recordingId}/${row.segment}/${row.seq}`), {
1114
+ method: "PUT",
1115
+ credentials: "include",
1116
+ headers: this.authHeaders({ "content-type": "application/octet-stream", "x-checksum": checksum }),
1117
+ body: row.blob,
1118
+ });
1119
+ if (res.ok) {
1120
+ const db = await dbOpen();
1121
+ await idbDel(db, row);
1122
+ db.close();
1123
+ return true;
1124
+ }
1125
+ if (attempt >= RECORDER_AFFINITY_RETRIES || !isRecorderRouteError(null, res.status)) {
1126
+ return false;
1127
+ }
1128
+ try { await this.refreshAffinity({ force: true }); } catch { /* retry with prior peer */ }
1129
+ await sleep(250 * attempt);
1130
+ }
1131
+ return false;
918
1132
  }
919
1133
 
920
1134
  /** Fire remux/upload without waiting (survives tab redirect via keepalive). */
@@ -937,39 +1151,38 @@ export class CanvasRecorder {
937
1151
  this.kickFinalize();
938
1152
  return;
939
1153
  }
940
- for (let round = 0; round < 3; round += 1) {
1154
+ const postFinalize = (body) => this.withRecorderRetry(async () => {
941
1155
  const res = await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
942
1156
  method: "POST",
943
1157
  credentials: "include",
944
1158
  headers: this.authHeaders({ "content-type": "application/json" }),
945
- body: JSON.stringify({ durationMs }),
1159
+ body: JSON.stringify(body),
946
1160
  });
947
- if (res.ok) return;
948
- if (res.status !== 409) {
949
- const data = await res.json().catch(() => ({}));
950
- throw new Error(data.error || "could not finish the recording");
1161
+ const data = await res.json().catch(() => ({}));
1162
+ if (!res.ok && res.status !== 409) {
1163
+ const err = new Error(data.error || "could not finish the recording");
1164
+ err.status = res.status;
1165
+ throw err;
1166
+ }
1167
+ return { ok: res.ok, status: res.status, data };
1168
+ });
1169
+
1170
+ for (let round = 0; round < 3; round += 1) {
1171
+ const result = await postFinalize({ durationMs });
1172
+ if (result.ok) return;
1173
+ if (result.status !== 409) {
1174
+ throw new Error(result.data.error || "could not finish the recording");
951
1175
  }
952
- const body = await res.json().catch(() => ({}));
953
- const missing = body.missingChunks ?? [];
1176
+ const missing = result.data.missingChunks ?? [];
954
1177
  if (!missing.length) return;
955
1178
  await this.pump();
956
1179
  const still = await this.hasAny(missing);
957
1180
  if (!still) {
958
- await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
959
- method: "POST",
960
- credentials: "include",
961
- headers: this.authHeaders({ "content-type": "application/json" }),
962
- body: JSON.stringify({ durationMs, force: true }),
963
- });
1181
+ await postFinalize({ durationMs, force: true });
964
1182
  return;
965
1183
  }
966
1184
  }
967
- await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
968
- method: "POST",
969
- credentials: "include",
970
- headers: this.authHeaders({ "content-type": "application/json" }),
971
- body: JSON.stringify({ durationMs, force: true }),
972
- });
1185
+ await postFinalize({ durationMs, force: true });
973
1186
  }
974
1187
 
975
1188
  async hasAny(missing) {
@@ -1018,51 +1231,31 @@ function placeholderLetter(name) {
1018
1231
  }
1019
1232
 
1020
1233
  /**
1021
- * Empty-stage tile: magenta avatar field. With chrome: rounded border + name pill (no mic/signal icons).
1234
+ * Camera-off tile: per-name radial gradient + translucent initial + bottom-left name.
1022
1235
  */
1023
- function drawStagePlaceholder(ctx, x, y, w, h, name, accent = false, accentColor = "#2563eb", options = {}) {
1236
+ function drawStagePlaceholder(ctx, x, y, w, h, name, _accent = false, _accentColor = PRESENTER_ACCENT, options = {}) {
1024
1237
  const chrome = options.chrome !== false;
1025
1238
  const corner = options.radius ?? TILE_RADIUS;
1026
- const cx = Math.round(x + w / 2);
1027
- const cy = Math.round(y + h / 2);
1028
1239
  ctx.save();
1029
- if (chrome && corner > 0) {
1240
+ if (corner > 0) {
1030
1241
  roundedRectPath(ctx, x, y, w, h, corner);
1031
1242
  ctx.clip();
1032
1243
  }
1033
- const span = Math.max(w, h) * 0.75;
1034
- const field = ctx.createRadialGradient(cx, cy, 0, cx, cy, span);
1035
- field.addColorStop(0, "rgb(152, 62, 107)");
1036
- field.addColorStop(0.75, "rgb(104, 39, 71)");
1037
- field.addColorStop(1, "rgb(104, 39, 71)");
1038
- ctx.fillStyle = field;
1039
- ctx.fillRect(x, y, w, h);
1040
-
1041
- const diameter = Math.round(Math.min(128, Math.max(72, Math.min(w, h) * 0.28)));
1042
- const avatarR = diameter / 2;
1043
- ctx.beginPath();
1044
- ctx.arc(cx, cy, avatarR, 0, Math.PI * 2);
1045
- ctx.fillStyle = "#e30096";
1046
- ctx.fill();
1047
-
1048
- const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 22), 45));
1049
- ctx.fillStyle = "#ffffff";
1050
- ctx.font = `600 ${letterPx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
1051
- ctx.textAlign = "center";
1052
- ctx.textBaseline = "middle";
1053
- ctx.fillText(placeholderLetter(name), cx, cy + 1);
1244
+ fillNameTone(ctx, x, y, w, h, name);
1245
+ drawInitialAvatar(ctx, x, y, w, h, name || placeholderLetter(name));
1054
1246
  ctx.restore();
1055
-
1056
1247
  if (!chrome) return;
1057
- if (corner > 0) strokeTileBorder(ctx, x, y, w, h, corner, { accent, accentColor });
1058
- drawNamePill(ctx, x, y, w, h, name);
1248
+ drawNamePill(ctx, x, y, w, h, name, {});
1059
1249
  }
1060
1250
 
1061
1251
  function paint(ctx, video, rect, crop, options = {}) {
1062
1252
  const label = options.label || "";
1063
1253
  const accent = Boolean(options.accent);
1064
- const accentColor = options.accentColor || "#2563eb";
1254
+ const accentColor = options.accentColor || PRESENTER_ACCENT;
1065
1255
  const radius = options.radius ?? TILE_RADIUS;
1256
+ const muted = Boolean(options.muted);
1257
+ const fit = options.fit === "contain" ? "contain" : "cover";
1258
+ const fillStyle = options.fillStyle || STAGE_BACKGROUND;
1066
1259
  if (!video || video.readyState < 2 || !video.videoWidth) {
1067
1260
  paintRoundedTile(ctx, {
1068
1261
  source: null,
@@ -1073,7 +1266,10 @@ function paint(ctx, video, rect, crop, options = {}) {
1073
1266
  accent,
1074
1267
  accentColor,
1075
1268
  radius,
1076
- fillStyle: "#0f172a",
1269
+ muted,
1270
+ fit,
1271
+ fillStyle,
1272
+ placeholder: true,
1077
1273
  });
1078
1274
  return;
1079
1275
  }
@@ -1081,7 +1277,8 @@ function paint(ctx, video, rect, crop, options = {}) {
1081
1277
  let sy = 0;
1082
1278
  let sw = video.videoWidth;
1083
1279
  let sh = video.videoHeight;
1084
- const cropNorm = normalizeVideoCrop(crop);
1280
+ // Screenshare uses contain (no crop). Camera tiles may still honor a stage crop.
1281
+ const cropNorm = fit === "contain" ? null : normalizeVideoCrop(crop);
1085
1282
  if (cropNorm) {
1086
1283
  sx = cropNorm.x * video.videoWidth;
1087
1284
  sy = cropNorm.y * video.videoHeight;
@@ -1100,7 +1297,9 @@ function paint(ctx, video, rect, crop, options = {}) {
1100
1297
  accent,
1101
1298
  accentColor,
1102
1299
  radius,
1103
- fillStyle: "#0f172a",
1300
+ muted,
1301
+ fit,
1302
+ fillStyle,
1104
1303
  });
1105
1304
  }
1106
1305