mediascale-sdk 1.0.12 → 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,24 +3,37 @@ import {
3
3
  fillRadialBackground,
4
4
  paintRoundedTile,
5
5
  drawNamePill,
6
- strokeTileBorder,
7
6
  roundedRectPath,
7
+ fillNameTone,
8
+ drawInitialAvatar,
9
+ STAGE_BACKGROUND,
8
10
  PRESENTER_ACCENT,
9
11
  } from "./record-frame-compositor.js";
10
- export { FrameCompositor, fillRadialBackground, PRESENTER_ACCENT } from "./record-frame-compositor.js";
12
+ export {
13
+ FrameCompositor,
14
+ fillRadialBackground,
15
+ PRESENTER_ACCENT,
16
+ STAGE_BACKGROUND,
17
+ } from "./record-frame-compositor.js";
11
18
 
12
19
  const W = 1280;
13
20
  const H = 720;
14
- /** Right rail width with screenshare (~20%). Camera tiles keep 16:9 — not stretched to full height. */
15
- const COL = Math.round(W * 0.2);
16
- /** Flush mosaic: no outer margin and no gutters between tiles. */
17
- const PAD = 0;
18
- const GAP = 0;
19
- /** Recording tiles are square-edged (no borders / radius). */
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). */
20
29
  const TILE_RADIUS = 0;
21
- /** Side-rail camera aspect (width / height). */
22
- const SIDE_CAM_ASPECT = 16 / 9;
23
- const FPS = 15;
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;
24
37
  const SLICE_MS = 5000;
25
38
  /** Hard cap for on-canvas camera / avatar tiles (host included). Audio is uncapped. */
26
39
  const MAX_STAGE_CAMERAS = 6;
@@ -28,56 +41,147 @@ const MAX_STAGE_CAMERAS = 6;
28
41
  const BITRATE = 4_500_000;
29
42
  const mime = "video/webm;codecs=vp8,opus";
30
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
+
31
51
  /** Channel ids become a single path segment. The original text stays the webinar name. */
32
52
  export function recordingWebinarId(channelId) {
33
53
  const cleaned = String(channelId || "").trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 128);
34
54
  return cleaned || "webinar";
35
55
  }
36
56
 
37
- /** Equal flush tiles, or screenshare + cameras stacked from the top (proportionate height). Up to 6 cameras. */
38
- export function layoutSlots(cameras, screen) {
39
- const n = Math.max(0, Math.min(MAX_STAGE_CAMERAS, Number(cameras) || 0));
40
- // One tile only — fill the canvas so recordingCanvasBackground is not visible as a border.
41
- if (screen && n === 0) {
42
- 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 "";
43
66
  }
44
- if (!screen && n === 1) {
45
- 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;
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})`);
46
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
+
47
129
  if (screen) {
48
- const mainW = W - COL;
49
- // Keep 16:9 side tiles; shrink only when the stack would overflow the canvas.
50
- let tileH = Math.max(1, Math.round(COL / SIDE_CAM_ASPECT));
51
- if (n > 0 && tileH * n > H) {
52
- tileH = Math.max(1, Math.floor(H / n));
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;
53
142
  }
54
- const stackH = n * tileH;
55
- const y0 = Math.max(0, Math.floor((H - stackH) / 2));
143
+ const sideX = PAD + mainW + GAP + Math.round((sideSlotW - tileW) / 2);
144
+ const y0 = PAD + Math.round((innerH - stackH) / 2);
56
145
  return {
57
- screen: { x: 0, y: 0, w: mainW, h: H },
146
+ screen: { x: PAD, y: PAD, w: mainW, h: innerH, radius: SCREEN_RADIUS },
58
147
  cameras: Array.from({ length: n }, (_, i) => ({
59
- x: mainW,
60
- y: y0 + i * tileH,
61
- w: COL,
148
+ x: sideX,
149
+ y: y0 + i * (tileH + GAP),
150
+ w: tileW,
62
151
  h: tileH,
152
+ radius: TILE_RADIUS,
63
153
  })),
64
154
  };
65
155
  }
66
- // Gallery: 3 cams → one row; otherwise pack 2 or 3 columns. Zero gaps, edge-to-edge.
67
- const cols = n <= 3 ? n : n <= 4 ? 2 : 3;
156
+
157
+ if (n === 0) return { cameras: [] };
158
+
159
+ const cols = galleryColumns(n);
68
160
  const rows = Math.max(1, Math.ceil(n / cols));
69
- const cellW = Math.floor(W / cols);
70
- const cellH = Math.floor(H / 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
+
71
171
  return {
72
172
  cameras: Array.from({ length: n }, (_, i) => {
73
- const col = i % cols;
74
173
  const row = Math.floor(i / cols);
75
- const x = col * cellW;
76
- const y = row * cellH;
77
- // Give leftover pixels to the last column / row so the mosaic reaches the canvas edge.
78
- const w = col === cols - 1 ? W - x : cellW;
79
- const h = row === rows - 1 ? H - y : cellH;
80
- return { x, y, w, h };
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
+ };
81
185
  }),
82
186
  };
83
187
  }
@@ -169,16 +273,39 @@ export class CanvasRecorder {
169
273
  return typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mime);
170
274
  }
171
275
 
172
- 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;
173
297
  this.webinarId = webinarId;
174
298
  this.webinarName = webinarName || webinarId;
175
299
  this.recordingId = recordingId;
176
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);
177
304
  /** @type {{ id: string, name: string, local?: boolean }[] | null} */
178
305
  this.stagePeople = null;
179
306
  this.token = token || "";
180
307
  this.selfName = String(selfName || "Host").slice(0, 40);
181
- this.canvasBackground = String(canvasBackground || "").trim() || "#2563eb";
308
+ this.canvasBackground = String(canvasBackground || "").trim() || STAGE_BACKGROUND;
182
309
  this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
183
310
  this.onFailure = typeof onFailure === "function" ? onFailure : () => {};
184
311
  this.segment = 0;
@@ -235,7 +362,7 @@ export class CanvasRecorder {
235
362
  } else {
236
363
  this.onFailure(error);
237
364
  this.onCaptureChange(false);
238
- window.dispatchEvent(new CustomEvent("mediascale:recording-error", {
365
+ window.dispatchEvent(new CustomEvent(`mediascale:${this.eventPrefix}-error`, {
239
366
  detail: { message: error.message },
240
367
  }));
241
368
  }
@@ -409,7 +536,10 @@ export class CanvasRecorder {
409
536
  }
410
537
 
411
538
  url(path) {
412
- 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)}`;
413
543
  }
414
544
 
415
545
  authHeaders(extra = {}) {
@@ -419,16 +549,51 @@ export class CanvasRecorder {
419
549
  };
420
550
  }
421
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
+
422
581
  async api(method, path, body) {
423
- const res = await fetch(this.url(path), {
424
- method,
425
- credentials: "include",
426
- headers: this.authHeaders({ "content-type": "application/json" }),
427
- 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;
428
596
  });
429
- const data = await res.json().catch(() => ({}));
430
- if (!res.ok) throw new Error(data.error ?? "recording upload failed");
431
- return data;
432
597
  }
433
598
 
434
599
  async prepare(audio) {
@@ -455,11 +620,12 @@ export class CanvasRecorder {
455
620
  const { compositor, reason } = await createWorkerCompositor({
456
621
  width: W,
457
622
  height: H,
458
- fps: FPS,
623
+ fps: this.fps,
624
+ steady: this.steadyFrames,
459
625
  background: this.canvasBackground,
460
626
  onError: (failure) => {
461
627
  this.compositorFailure = failure;
462
- window.dispatchEvent(new CustomEvent("mediascale:recording-error", { detail: { message: failure.message } }));
628
+ window.dispatchEvent(new CustomEvent(`mediascale:${this.eventPrefix}-error`, { detail: { message: failure.message } }));
463
629
  void this.setWanted(false).catch(() => {});
464
630
  },
465
631
  });
@@ -472,14 +638,14 @@ export class CanvasRecorder {
472
638
  this.canvas.height = H;
473
639
  this.ctx = this.canvas.getContext("2d");
474
640
  fillRadialBackground(this.ctx, 0, 0, W, H, this.canvasBackground);
475
- 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" }));
476
642
  const worker = new Worker(url);
477
643
  worker.onmessage = () => this.draw();
478
644
  this.setDrawActive = (active) => worker.postMessage(active);
479
645
  this.stopDraw = () => { worker.terminate(); URL.revokeObjectURL(url); };
480
- video = this.canvas.captureStream(FPS).getVideoTracks()[0];
646
+ video = this.canvas.captureStream(this.fps).getVideoTracks()[0];
481
647
  }
482
- 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 } }));
483
649
  this.retile();
484
650
  this.capture = video;
485
651
  this.captureStream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
@@ -499,7 +665,7 @@ export class CanvasRecorder {
499
665
  if (!this.startedAt) this.startedAt = Date.now();
500
666
  this.recorder = new MediaRecorder(this.captureStream, {
501
667
  mimeType: mime,
502
- videoBitsPerSecond: BITRATE,
668
+ videoBitsPerSecond: this.bitrate,
503
669
  audioBitsPerSecond: 128_000,
504
670
  });
505
671
  this.recorderStops.set(this.recorder, new Promise((resolve) => this.recorder.addEventListener("stop", resolve, { once: true })));
@@ -720,9 +886,10 @@ export class CanvasRecorder {
720
886
  label: "",
721
887
  accent: false,
722
888
  muted: false,
723
- // Letterbox screenshare (no crop); bars use brand canvas blue.
724
889
  fit: "contain",
725
- fillStyle: this.canvasBackground || "#2563eb",
890
+ fillStyle: this.canvasBackground || STAGE_BACKGROUND,
891
+ radius: layout.screen?.radius ?? SCREEN_RADIUS,
892
+ placeholder: false,
726
893
  }] : []),
727
894
  ...chosen.map((slot, index) => {
728
895
  const rect = layout.cameras[index];
@@ -732,11 +899,11 @@ export class CanvasRecorder {
732
899
  rect,
733
900
  crop: null,
734
901
  label: slot.displayName,
735
- // Presenter flag drives the name-pill label only (no tile borders).
736
- accent: Boolean(slot.presenter),
737
- radius: TILE_RADIUS,
738
- muted: Boolean(slot.micMuted),
902
+ accent: false,
903
+ radius: rect?.radius ?? TILE_RADIUS,
904
+ muted: false,
739
905
  fit: "cover",
906
+ placeholder: Boolean(slot.placeholder),
740
907
  };
741
908
  }),
742
909
  ]);
@@ -767,15 +934,15 @@ export class CanvasRecorder {
767
934
  canvas.width = W;
768
935
  canvas.height = H;
769
936
  const ctx = canvas.getContext("2d", { alpha: false, desynchronized: true });
770
- const stream = canvas.captureStream(FPS);
937
+ const stream = canvas.captureStream(this.fps);
771
938
  const track = stream.getVideoTracks()[0];
772
939
  entry = { track, canvas, name, isLocal, redraw: null, timer: null };
773
940
  entry.redraw = () => {
774
941
  // Full-frame synthetic track: avatar only. Tile chrome/name are drawn on the layout rect.
775
- 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 });
776
943
  track.requestFrame?.();
777
944
  };
778
- entry.timer = setInterval(entry.redraw, Math.round(1000 / FPS));
945
+ entry.timer = setInterval(entry.redraw, Math.round(1000 / this.fps));
779
946
  this.placeholderSources.set(key, entry);
780
947
  entry.redraw();
781
948
  return track;
@@ -869,30 +1036,29 @@ export class CanvasRecorder {
869
1036
  accent: false,
870
1037
  accentColor: this.canvasBackground,
871
1038
  fit: "contain",
872
- fillStyle: this.canvasBackground || "#2563eb",
1039
+ fillStyle: this.canvasBackground || STAGE_BACKGROUND,
1040
+ radius: layout.screen.radius ?? SCREEN_RADIUS,
873
1041
  });
874
1042
  }
875
1043
  cameras.forEach((slot, index) => {
876
1044
  const rect = layout.cameras[index];
877
1045
  if (!rect) return;
878
1046
  const label = resolveTileLabel(slot, this.selfName);
879
- const accent = slot.presenter != null ? Boolean(slot.presenter) : isPresenterSlot(slot, label);
880
- const radius = TILE_RADIUS;
881
- const muted = slot.micMuted != null ? Boolean(slot.micMuted) : false;
1047
+ const radius = rect.radius ?? TILE_RADIUS;
882
1048
  if (slot.placeholder) {
883
- drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, label, accent, PRESENTER_ACCENT, {
1049
+ drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, label, false, STAGE_BACKGROUND, {
884
1050
  chrome: true,
885
1051
  radius,
886
- muted,
1052
+ muted: false,
887
1053
  });
888
1054
  return;
889
1055
  }
890
1056
  paint(this.ctx, slot.video, rect, null, {
891
1057
  label,
892
- accent,
1058
+ accent: false,
893
1059
  accentColor: PRESENTER_ACCENT,
894
1060
  radius,
895
- muted,
1061
+ muted: false,
896
1062
  });
897
1063
  });
898
1064
  this.capture?.requestFrame();
@@ -940,17 +1106,29 @@ export class CanvasRecorder {
940
1106
 
941
1107
  async upload(row) {
942
1108
  const checksum = await sha256(row.blob);
943
- const res = await fetch(this.url(`/api/chunks/${this.recordingId}/${row.segment}/${row.seq}`), {
944
- method: "PUT",
945
- credentials: "include",
946
- headers: this.authHeaders({ "content-type": "application/octet-stream", "x-checksum": checksum }),
947
- body: row.blob,
948
- });
949
- if (!res.ok) return false;
950
- const db = await dbOpen();
951
- await idbDel(db, row);
952
- db.close();
953
- 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;
954
1132
  }
955
1133
 
956
1134
  /** Fire remux/upload without waiting (survives tab redirect via keepalive). */
@@ -973,39 +1151,38 @@ export class CanvasRecorder {
973
1151
  this.kickFinalize();
974
1152
  return;
975
1153
  }
976
- for (let round = 0; round < 3; round += 1) {
1154
+ const postFinalize = (body) => this.withRecorderRetry(async () => {
977
1155
  const res = await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
978
1156
  method: "POST",
979
1157
  credentials: "include",
980
1158
  headers: this.authHeaders({ "content-type": "application/json" }),
981
- body: JSON.stringify({ durationMs }),
1159
+ body: JSON.stringify(body),
982
1160
  });
983
- if (res.ok) return;
984
- if (res.status !== 409) {
985
- const data = await res.json().catch(() => ({}));
986
- 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");
987
1175
  }
988
- const body = await res.json().catch(() => ({}));
989
- const missing = body.missingChunks ?? [];
1176
+ const missing = result.data.missingChunks ?? [];
990
1177
  if (!missing.length) return;
991
1178
  await this.pump();
992
1179
  const still = await this.hasAny(missing);
993
1180
  if (!still) {
994
- await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
995
- method: "POST",
996
- credentials: "include",
997
- headers: this.authHeaders({ "content-type": "application/json" }),
998
- body: JSON.stringify({ durationMs, force: true }),
999
- });
1181
+ await postFinalize({ durationMs, force: true });
1000
1182
  return;
1001
1183
  }
1002
1184
  }
1003
- await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
1004
- method: "POST",
1005
- credentials: "include",
1006
- headers: this.authHeaders({ "content-type": "application/json" }),
1007
- body: JSON.stringify({ durationMs, force: true }),
1008
- });
1185
+ await postFinalize({ durationMs, force: true });
1009
1186
  }
1010
1187
 
1011
1188
  async hasAny(missing) {
@@ -1054,45 +1231,21 @@ function placeholderLetter(name) {
1054
1231
  }
1055
1232
 
1056
1233
  /**
1057
- * Empty-stage tile: magenta avatar field. With chrome: rounded border + name pill (signal / mute icons).
1234
+ * Camera-off tile: per-name radial gradient + translucent initial + bottom-left name.
1058
1235
  */
1059
- function drawStagePlaceholder(ctx, x, y, w, h, name, accent = false, accentColor = PRESENTER_ACCENT, options = {}) {
1236
+ function drawStagePlaceholder(ctx, x, y, w, h, name, _accent = false, _accentColor = PRESENTER_ACCENT, options = {}) {
1060
1237
  const chrome = options.chrome !== false;
1061
1238
  const corner = options.radius ?? TILE_RADIUS;
1062
- const muted = Boolean(options.muted);
1063
- const cx = Math.round(x + w / 2);
1064
- const cy = Math.round(y + h / 2);
1065
1239
  ctx.save();
1066
- if (chrome && corner > 0) {
1240
+ if (corner > 0) {
1067
1241
  roundedRectPath(ctx, x, y, w, h, corner);
1068
1242
  ctx.clip();
1069
1243
  }
1070
- const span = Math.max(w, h) * 0.75;
1071
- const field = ctx.createRadialGradient(cx, cy, 0, cx, cy, span);
1072
- field.addColorStop(0, "rgb(152, 62, 107)");
1073
- field.addColorStop(0.75, "rgb(104, 39, 71)");
1074
- field.addColorStop(1, "rgb(104, 39, 71)");
1075
- ctx.fillStyle = field;
1076
- ctx.fillRect(x, y, w, h);
1077
-
1078
- const diameter = Math.round(Math.min(128, Math.max(72, Math.min(w, h) * 0.28)));
1079
- const avatarR = diameter / 2;
1080
- ctx.beginPath();
1081
- ctx.arc(cx, cy, avatarR, 0, Math.PI * 2);
1082
- ctx.fillStyle = "#e30096";
1083
- ctx.fill();
1084
-
1085
- const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 22), 45));
1086
- ctx.fillStyle = "#ffffff";
1087
- ctx.font = `600 ${letterPx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
1088
- ctx.textAlign = "center";
1089
- ctx.textBaseline = "middle";
1090
- 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));
1091
1246
  ctx.restore();
1092
-
1093
1247
  if (!chrome) return;
1094
- if (corner > 0) strokeTileBorder(ctx, x, y, w, h, corner, { accent, accentColor });
1095
- drawNamePill(ctx, x, y, w, h, name, { presenter: accent, muted });
1248
+ drawNamePill(ctx, x, y, w, h, name, {});
1096
1249
  }
1097
1250
 
1098
1251
  function paint(ctx, video, rect, crop, options = {}) {
@@ -1102,7 +1255,7 @@ function paint(ctx, video, rect, crop, options = {}) {
1102
1255
  const radius = options.radius ?? TILE_RADIUS;
1103
1256
  const muted = Boolean(options.muted);
1104
1257
  const fit = options.fit === "contain" ? "contain" : "cover";
1105
- const fillStyle = options.fillStyle || "#0f172a";
1258
+ const fillStyle = options.fillStyle || STAGE_BACKGROUND;
1106
1259
  if (!video || video.readyState < 2 || !video.videoWidth) {
1107
1260
  paintRoundedTile(ctx, {
1108
1261
  source: null,
@@ -1116,6 +1269,7 @@ function paint(ctx, video, rect, crop, options = {}) {
1116
1269
  muted,
1117
1270
  fit,
1118
1271
  fillStyle,
1272
+ placeholder: true,
1119
1273
  });
1120
1274
  return;
1121
1275
  }