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/client.js CHANGED
@@ -1,6 +1,15 @@
1
1
  import { Device } from "mediasoup-client";
2
2
  import { io } from "socket.io-client";
3
- import { CanvasRecorder, normalizeVideoCrop, recordingWebinarId, tracksFromTiles } from "./record.js";
3
+ import {
4
+ CanvasRecorder,
5
+ DEFAULT_RECORDING_FPS,
6
+ clampFps,
7
+ normalizeVideoCrop,
8
+ recordingWebinarId,
9
+ resolveRecorderAffinity,
10
+ tracksFromTiles,
11
+ } from "./record.js";
12
+ import { DEFAULT_RTMP_BITRATE, DEFAULT_RTMP_FPS, LiveCompositor } from "./live.js";
4
13
 
5
14
  const SIZES = {
6
15
  "480p": { width: 854, height: 480 },
@@ -29,10 +38,10 @@ function normalizePublishLimits(raw = {}) {
29
38
  };
30
39
  }
31
40
 
32
- /** CSS color for the recording canvas fill. Empty / invalid → #2563eb. */
41
+ /** CSS color for the recording canvas gradient. Empty → design navy default. */
33
42
  function normalizeCanvasBackground(raw) {
34
43
  const color = String(raw ?? "").trim();
35
- return color || "#2563eb";
44
+ return color || "#0A0036";
36
45
  }
37
46
 
38
47
  function readToken(token) {
@@ -62,15 +71,47 @@ function emit(socket, event, data, timeoutMs = 8000) {
62
71
  socket.emit(event, data, (response) => {
63
72
  clearTimeout(timer);
64
73
  if (!response || response.error) {
65
- if (response?.peer && typeof document !== "undefined") {
66
- document.cookie = `ms_portal=${encodeURIComponent(response.peer)}; Path=/; Max-Age=86400; SameSite=Lax`;
67
- }
68
- reject(new Error(response?.error || "Request failed"));
74
+ const err = new Error(response?.error || "Request failed");
75
+ if (response?.peer) err.peer = response.peer;
76
+ if (response?.portal) err.portal = response.portal;
77
+ reject(err);
69
78
  } else resolve(response);
70
79
  });
71
80
  });
72
81
  }
73
82
 
83
+ const PORTAL_AFFINITY_RETRIES = 3;
84
+ const PORTAL_AFFINITY_KEY = (sessionId) => `mediascale:ms_portal:${sessionId}`;
85
+
86
+ function readStoredPortalPeer(sessionId) {
87
+ try {
88
+ if (typeof sessionStorage === "undefined") return "";
89
+ return String(sessionStorage.getItem(PORTAL_AFFINITY_KEY(sessionId)) || "").trim();
90
+ } catch {
91
+ return "";
92
+ }
93
+ }
94
+
95
+ function writeStoredPortalPeer(sessionId, peer) {
96
+ const value = String(peer || "").trim();
97
+ if (!value) return;
98
+ try {
99
+ if (typeof sessionStorage !== "undefined") {
100
+ sessionStorage.setItem(PORTAL_AFFINITY_KEY(sessionId), value);
101
+ }
102
+ } catch {
103
+ /* private mode */
104
+ }
105
+ // Cookie remains a single-tab fallback; multi-session routing uses ?ms_portal=.
106
+ if (typeof document !== "undefined") {
107
+ document.cookie = `ms_portal=${encodeURIComponent(value)}; Path=/; Max-Age=86400; SameSite=Lax`;
108
+ }
109
+ }
110
+
111
+ function isPortalMismatchError(error) {
112
+ return /pinned to another portal/i.test(String(error?.message || error || ""));
113
+ }
114
+
74
115
  function videoConstraint(cameraId, resolution) {
75
116
  const size = resolution && typeof resolution === "object" ? resolution : (SIZES[resolution] || SIZES["720p"]);
76
117
  const video = { width: { ideal: size.width }, height: { ideal: size.height } };
@@ -95,6 +136,7 @@ export function createClient(options = {}) {
95
136
  const onUserList = options.onUserList || (() => {});
96
137
  const onUserBlocked = options.onUserBlocked || (() => {});
97
138
  const onStageChanged = options.onStageChanged || (() => {});
139
+ const onRtmpStatus = options.onRtmpStatus || (() => {});
98
140
 
99
141
  if (!sessionId) throw new Error("sessionId is required");
100
142
  if (!token) throw new Error("token is required");
@@ -103,8 +145,19 @@ export function createClient(options = {}) {
103
145
  // Explicit option wins; otherwise honor recording flag embedded in the host token.
104
146
  const recording = options.recording === true
105
147
  || (options.recording !== false && claims.recording === true && claims.role === "host");
106
- // Main recording canvas fill (letterbox / empty areas). Defaults to #2563eb.
148
+ // Main recording canvas fill (letterbox / empty areas). Defaults to design navy.
107
149
  const recordingCanvasBackground = normalizeCanvasBackground(options.recordingCanvasBackground);
150
+ // Frame rates are independent: recording (MediaRecorder) vs RTMP live output.
151
+ let recordingFps = clampFps(options.recordingFps, DEFAULT_RECORDING_FPS);
152
+ const recordingBitrate = Number(options.recordingBitrate) > 0 ? Math.round(Number(options.recordingBitrate)) : undefined;
153
+ let rtmpFps = clampFps(options.rtmpFps, DEFAULT_RTMP_FPS);
154
+ const rtmpBitrate = Number(options.rtmpBitrate) > 0 ? Math.round(Number(options.rtmpBitrate)) : DEFAULT_RTMP_BITRATE;
155
+ /**
156
+ * Hosts can always open Live. `claims.rtmp` means destinations were prepared at
157
+ * webinar create — auto Go Live after join when those destinations are present.
158
+ */
159
+ const rtmpEnabled = claims.role === "host";
160
+ const rtmpAutoStart = claims.rtmp === true && claims.role === "host";
108
161
 
109
162
  const displayName = String(claims.name || "Guest").slice(0, 40);
110
163
  // createClient({ publishLimits }) wins over portal join values when set.
@@ -135,9 +188,18 @@ export function createClient(options = {}) {
135
188
  /** When set, parent-provided stage list wins over roster-derived stageById. */
136
189
  let stageOverride = null;
137
190
  let lastStageSig = "";
191
+ /** Integration debug: log current recording stage every 5s. */
192
+ let stageDebugTimer = null;
138
193
  const pending = [];
139
194
  let readyPromise = null;
140
195
  let settleReady = null;
196
+ /** Session-scoped portal peer (query param). Avoids browser-wide cookie collisions. */
197
+ let portalPeer = readStoredPortalPeer(sessionId);
198
+ /** RTMP: stage compositor + hidden H264/Opus producers on the origin. */
199
+ let live = null;
200
+ let liveProducers = [];
201
+ let startingLive = null;
202
+ let rtmpState = { enabled: rtmpEnabled, state: "idle", live: false, destinations: [] };
141
203
 
142
204
  function userOnStage(user) {
143
205
  if (!user) return false;
@@ -165,14 +227,33 @@ export function createClient(options = {}) {
165
227
  return [...stageById.values()];
166
228
  }
167
229
 
230
+ function logRecordingStage(reason) {
231
+ const people = stagePeopleForRecording();
232
+ console.log("[mediascale] recording stage", {
233
+ reason,
234
+ source: stageOverride ? "setRecordingStage" : "roster",
235
+ count: people.length,
236
+ people: people.map((p) => ({ id: p.id, name: p.name, local: Boolean(p.local) })),
237
+ });
238
+ }
239
+
168
240
  function emitStageChanged() {
169
241
  const people = stagePeopleForRecording();
170
242
  const sig = people.map((p) => `${p.id}|${p.name}|${p.local ? 1 : 0}`).join(";");
171
243
  if (sig === lastStageSig) return;
172
244
  lastStageSig = sig;
245
+ // Integration: confirm setRecordingStage / roster stage updates reach the SDK recorder.
246
+ logRecordingStage("changed");
173
247
  onStageChanged(people);
174
248
  }
175
249
 
250
+ if (typeof setInterval === "function") {
251
+ stageDebugTimer = setInterval(() => {
252
+ if (closed) return;
253
+ logRecordingStage("poll-5s");
254
+ }, 5000);
255
+ }
256
+
176
257
  function ingestRosterUsers(users) {
177
258
  if (!Array.isArray(users)) return;
178
259
  stageById.clear();
@@ -226,7 +307,10 @@ export function createClient(options = {}) {
226
307
  }
227
308
 
228
309
  function syncRecording() {
229
- recorder?.sync(tracksForRecording(), stagePeopleForRecording());
310
+ const tracks = tracksForRecording();
311
+ const people = stagePeopleForRecording();
312
+ recorder?.sync(tracks, people);
313
+ live?.sync(tracks, people);
230
314
  }
231
315
 
232
316
  /**
@@ -264,8 +348,9 @@ export function createClient(options = {}) {
264
348
  const next = normalizeVideoCrop(crop);
265
349
  if (!next) recordingCrops.delete(id);
266
350
  else recordingCrops.set(id, next);
267
- if (recorder) {
268
- recorder.setVideoCrop(id, next);
351
+ if (recorder || live) {
352
+ recorder?.setVideoCrop(id, next);
353
+ live?.setVideoCrop(id, next);
269
354
  syncRecording();
270
355
  }
271
356
  }
@@ -492,188 +577,297 @@ export function createClient(options = {}) {
492
577
  return { producerId: producer.id, stream, source };
493
578
  }
494
579
 
495
- async function ensurePortalAffinity() {
580
+ async function ensurePortalAffinity({ force = false } = {}) {
496
581
  try {
497
582
  const response = await fetch(`${endpoint}/portal/api/v1/affinity?channelId=${encodeURIComponent(sessionId)}`, {
498
583
  credentials: "include",
499
584
  });
500
- if (!response.ok) return;
585
+ if (!response.ok) return portalPeer;
501
586
  const body = await response.json().catch(() => null);
502
- if (body?.peer && typeof document !== "undefined") {
503
- document.cookie = `ms_portal=${encodeURIComponent(body.peer)}; Path=/; Max-Age=86400; SameSite=Lax`;
587
+ if (body?.peer) {
588
+ portalPeer = String(body.peer).trim();
589
+ writeStoredPortalPeer(sessionId, portalPeer);
504
590
  }
591
+ return portalPeer;
505
592
  } catch {
506
593
  /* gateway may still route to the seed portal */
594
+ if (!force && portalPeer) return portalPeer;
595
+ return portalPeer;
507
596
  }
508
597
  }
509
598
 
510
- async function ensureRecorderAffinity() {
599
+ async function ensureRecorderAffinity({ force = false } = {}) {
511
600
  const webinarId = recordingWebinarId(sessionId);
512
601
  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`;
602
+ return await resolveRecorderAffinity({ endpoint, webinarId, force });
603
+ } catch {
604
+ /* gateway may still route to the seed recorder via cookie */
605
+ return "";
606
+ }
607
+ }
608
+
609
+ function destroySocket() {
610
+ if (!socket) return;
611
+ try { socket.removeAllListeners(); } catch { /* ignore */ }
612
+ try { socket.disconnect(); } catch { /* ignore */ }
613
+ socket = null;
614
+ }
615
+
616
+ function bindSocketLifecycle() {
617
+ socket.on("sessionEnded", () => {
618
+ // Whole room is ending — always finalize if we hold the recorder (never hand off).
619
+ end({ finalize: true }).catch((error) => onError(error));
620
+ });
621
+ socket.on("releaseRecording", () => {
622
+ const current = recorder;
623
+ recorder = null;
624
+ if (!current) return;
625
+ current.handoff()
626
+ .then(() => onRecording("stopped"))
627
+ .catch((error) => onError(error));
628
+ });
629
+ // Portal elected this peer to continue an in-progress recording after the host left.
630
+ socket.on("takeRecording", () => {
631
+ startRecording().catch((error) => onError(error));
632
+ });
633
+ socket.on("finalizeRecording", () => {
634
+ const current = recorder;
635
+ if (!current) return;
636
+ recorder = null;
637
+ // Background remux — do not surface a blocking status in the meet UI.
638
+ current.finish({ waitFinalize: false })
639
+ .then(() => onRecording("stopped"))
640
+ .catch((error) => onError(error));
641
+ });
642
+ socket.on("rtmpStatus", (payload) => {
643
+ if (!closed) setRtmpState(payload);
644
+ });
645
+ // Portal elected this peer to keep composing the live stream after the presenter left.
646
+ socket.on("takeRtmp", () => {
647
+ startLiveOutput().catch((error) => onError(error));
648
+ });
649
+ socket.on("rtmpStopped", () => {
650
+ stopLiveOutput().catch(() => {});
651
+ });
652
+ socket.on("activeSpeaker", (payload = {}) => {
653
+ if (closed) return;
654
+ const peerId = payload.peerId || null;
655
+ onActiveSpeaker({
656
+ peerId,
657
+ displayName: payload.displayName || null,
658
+ producerId: payload.producerId || null,
659
+ local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
660
+ });
661
+ });
662
+ socket.on("userJoined", (user) => {
663
+ if (closed) return;
664
+ ingestRosterUser(user);
665
+ onUserJoined(user);
666
+ });
667
+ socket.on("userLeft", (user) => {
668
+ if (closed) return;
669
+ removeRosterUser(user);
670
+ onUserLeft(user);
671
+ });
672
+ socket.on("userUpdated", (user) => {
673
+ if (closed) return;
674
+ ingestRosterUser(user);
675
+ onUserUpdated(user);
676
+ });
677
+ socket.on("userBlocked", (payload) => {
678
+ if (!closed) onUserBlocked(payload || {});
679
+ });
680
+ // Capacity pack while someone publishes (e.g. host screen) may park this viewer.
681
+ socket.on("waiting", (payload = {}) => {
682
+ if (!closed) onStatus(payload.message || "Please wait, we will connect you soon");
683
+ });
684
+ socket.on("releaseConsumers", () => {
685
+ if (closed) return;
686
+ pending.length = 0;
687
+ try { recvTransport?.close(); } catch { /* ignore */ }
688
+ recvTransport = null;
689
+ clearRemoteTiles();
690
+ });
691
+ socket.on("edgeChanged", () => {
692
+ recoverRecvTransport().catch((error) => onError(error));
693
+ });
694
+ socket.on("newConsumer", (params) => {
695
+ play(params).catch((error) => onError(error));
696
+ });
697
+ socket.on("producerClosed", ({ producerId }) => {
698
+ for (let i = pending.length - 1; i >= 0; i -= 1) {
699
+ if (pending[i].producerId === producerId) pending.splice(i, 1);
700
+ }
701
+ if (tiles.delete(producerId)) syncRecording();
702
+ onTrackEnded({ producerId });
703
+ });
704
+ }
705
+
706
+ function openSocket() {
707
+ destroySocket();
708
+ const query = {};
709
+ if (portalPeer) query.ms_portal = portalPeer;
710
+ socket = io(endpoint, {
711
+ transports: ["websocket"],
712
+ withCredentials: true,
713
+ auth: { token, client: "mediascale-sdk" },
714
+ query,
715
+ // Portal mismatch / 502 are handled by our bounded retry loop.
716
+ reconnection: false,
717
+ });
718
+ bindSocketLifecycle();
719
+ return socket;
720
+ }
721
+
722
+ function waitForSocketConnect(sock, timeoutMs = 12_000) {
723
+ return new Promise((resolve, reject) => {
724
+ if (sock.connected) {
725
+ resolve();
726
+ return;
727
+ }
728
+ const timer = setTimeout(() => {
729
+ cleanup();
730
+ reject(new Error("Could not reach the portal"));
731
+ }, timeoutMs);
732
+ const onConnect = () => {
733
+ cleanup();
734
+ resolve();
735
+ };
736
+ const onError = (err) => {
737
+ cleanup();
738
+ reject(err instanceof Error ? err : new Error(String(err?.message || err || "Network unstable")));
739
+ };
740
+ const cleanup = () => {
741
+ clearTimeout(timer);
742
+ sock.off("connect", onConnect);
743
+ sock.off("connect_error", onError);
744
+ };
745
+ sock.on("connect", onConnect);
746
+ sock.on("connect_error", onError);
747
+ });
748
+ }
749
+
750
+ async function joinSessionOnce() {
751
+ onStatus("Joining");
752
+ const joined = await emit(socket, "join", {
753
+ channelId: sessionId,
754
+ role: "publisher",
755
+ displayName,
756
+ ...clientHints(),
757
+ });
758
+ selfPeerId = joined.peerId || null;
759
+ if (joined.rtmp) setRtmpState(joined.rtmp);
760
+ iceServers = iceOverride || joined.iceServers || [];
761
+ applyPublishLimitsFromJoin(joined.publishLimits);
762
+ if (Array.isArray(joined.users)) {
763
+ ingestRosterUsers(joined.users);
764
+ onUserList(joined.users);
765
+ }
766
+ device = new Device();
767
+ await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
768
+
769
+ const sendParams = await emit(socket, "createTransport", { direction: "send" });
770
+ sendTransport = device.createSendTransport({ ...sendParams, iceServers });
771
+ bindSendTransport(sendTransport);
772
+
773
+ const recvParams = await emit(socket, "createTransport", { direction: "recv" });
774
+ recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
775
+ bindRecvTransport(recvTransport);
776
+ const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
777
+ for (const params of started.consumers || []) await play(params);
778
+ // Fresh roster after ready (covers anyone who joined during transport setup).
779
+ try {
780
+ const list = await emit(socket, "getUserList", {});
781
+ if (Array.isArray(list?.users)) {
782
+ ingestRosterUsers(list.users);
783
+ onUserList(list.users);
521
784
  }
522
785
  } catch {
523
- /* gateway may still route to the seed recorder */
786
+ /* roster optional if portal is older */
787
+ }
788
+ if (joined.waiting) onStatus("Please wait, we will connect you soon");
789
+ else onStatus("Ready");
790
+ if (closed) return;
791
+ // Do not await: AudioContext may need a click in this tab before chunks flow.
792
+ if (recording && claims.role === "host") {
793
+ startRecording().catch((error) => onError(error));
524
794
  }
795
+ // Destinations saved at webinar create: go live as soon as the host page is ready.
796
+ // Manual Live panel still works to stop, restart, or add destinations.
797
+ if (rtmpAutoStart && !closed) {
798
+ const ready = (rtmpState.destinations || []).some((dest) => dest.enabled !== false);
799
+ const idle = !rtmpState.live && (rtmpState.state === "idle" || rtmpState.state === "error" || !rtmpState.state);
800
+ if (ready && idle) {
801
+ startRtmp().catch((error) => onError(error));
802
+ }
803
+ }
804
+ }
805
+
806
+ function abortConnectMedia() {
807
+ destroySocket();
808
+ try { sendTransport?.close(); } catch { /* ignore */ }
809
+ try { recvTransport?.close(); } catch { /* ignore */ }
810
+ sendTransport = null;
811
+ recvTransport = null;
812
+ device = null;
813
+ }
814
+
815
+ /** end() can win the race mid-await; never leave a joined portal socket behind. */
816
+ function throwIfEnded() {
817
+ if (!closed) return;
818
+ abortConnectMedia();
819
+ throw new Error("Ended");
525
820
  }
526
821
 
527
822
  async function connect() {
528
823
  if (readyPromise) return readyPromise;
529
- readyPromise = (async () => {
530
- await ensurePortalAffinity();
531
- return new Promise((resolve, reject) => {
532
- settleReady = (error) => {
533
- settleReady = null;
534
- if (error) reject(error);
535
- else resolve();
536
- };
537
- socket = io(endpoint, {
538
- transports: ["websocket"],
539
- withCredentials: true,
540
- auth: { token, client: "mediascale-sdk" },
541
- });
542
- socket.on("connect_error", () => {
543
- if (!closed) onStatus("Network unstable");
544
- });
545
- socket.on("sessionEnded", () => {
546
- // Whole room is ending — always finalize if we hold the recorder (never hand off).
547
- end({ finalize: true }).catch((error) => onError(error));
548
- });
549
- socket.on("releaseRecording", () => {
550
- const current = recorder;
551
- recorder = null;
552
- if (!current) return;
553
- current.handoff()
554
- .then(() => onRecording("stopped"))
555
- .catch((error) => onError(error));
556
- });
557
- // Portal elected this peer to continue an in-progress recording after the host left.
558
- socket.on("takeRecording", () => {
559
- startRecording().catch((error) => onError(error));
560
- });
561
- socket.on("finalizeRecording", () => {
562
- const current = recorder;
563
- if (!current) return;
564
- recorder = null;
565
- // Background remux — do not surface a blocking status in the meet UI.
566
- current.finish({ waitFinalize: false })
567
- .then(() => onRecording("stopped"))
568
- .catch((error) => onError(error));
569
- });
570
- socket.on("activeSpeaker", (payload = {}) => {
571
- if (closed) return;
572
- const peerId = payload.peerId || null;
573
- onActiveSpeaker({
574
- peerId,
575
- displayName: payload.displayName || null,
576
- producerId: payload.producerId || null,
577
- local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
578
- });
579
- });
580
- socket.on("userJoined", (user) => {
581
- if (closed) return;
582
- ingestRosterUser(user);
583
- onUserJoined(user);
584
- });
585
- socket.on("userLeft", (user) => {
586
- if (closed) return;
587
- removeRosterUser(user);
588
- onUserLeft(user);
589
- });
590
- socket.on("userUpdated", (user) => {
591
- if (closed) return;
592
- ingestRosterUser(user);
593
- onUserUpdated(user);
594
- });
595
- socket.on("userBlocked", (payload) => {
596
- if (!closed) onUserBlocked(payload || {});
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
- });
622
- socket.on("connect", async () => {
824
+ readyPromise = new Promise((resolve, reject) => {
825
+ settleReady = (error) => {
826
+ const done = settleReady;
827
+ settleReady = null;
828
+ if (!done) return;
829
+ if (error) reject(error);
830
+ else resolve();
831
+ };
832
+ (async () => {
833
+ let lastError = null;
834
+ for (let attempt = 1; attempt <= PORTAL_AFFINITY_RETRIES; attempt += 1) {
835
+ throwIfEnded();
623
836
  try {
624
- if (closed) return;
625
- onStatus("Joining");
626
- const joined = await emit(socket, "join", {
627
- channelId: sessionId,
628
- role: "publisher",
629
- displayName,
630
- ...clientHints(),
631
- });
632
- selfPeerId = joined.peerId || null;
633
- iceServers = iceOverride || joined.iceServers || [];
634
- applyPublishLimitsFromJoin(joined.publishLimits);
635
- if (Array.isArray(joined.users)) {
636
- ingestRosterUsers(joined.users);
637
- onUserList(joined.users);
638
- }
639
- device = new Device();
640
- await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
641
-
642
- const sendParams = await emit(socket, "createTransport", { direction: "send" });
643
- sendTransport = device.createSendTransport({ ...sendParams, iceServers });
644
- bindSendTransport(sendTransport);
645
-
646
- const recvParams = await emit(socket, "createTransport", { direction: "recv" });
647
- recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
648
- bindRecvTransport(recvTransport);
649
- const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
650
- for (const params of started.consumers || []) await play(params);
651
- // Fresh roster after ready (covers anyone who joined during transport setup).
652
- try {
653
- const list = await emit(socket, "getUserList", {});
654
- if (Array.isArray(list?.users)) {
655
- ingestRosterUsers(list.users);
656
- onUserList(list.users);
657
- }
658
- } catch {
659
- /* roster optional if portal is older */
660
- }
661
- if (joined.waiting) onStatus("Please wait, we will connect you soon");
662
- else onStatus("Ready");
663
- if (closed) return;
664
- // Do not await: AudioContext may need a click in this tab before chunks flow.
665
- if (recording && claims.role === "host") {
666
- startRecording().catch((error) => onError(error));
667
- }
668
- if (closed) return;
837
+ await ensurePortalAffinity({ force: attempt > 1 });
838
+ throwIfEnded();
839
+ openSocket();
840
+ throwIfEnded();
841
+ await waitForSocketConnect(socket);
842
+ throwIfEnded();
843
+ await joinSessionOnce();
844
+ throwIfEnded();
669
845
  settleReady?.();
846
+ return;
670
847
  } catch (error) {
671
- onStatus(error.message);
672
- settleReady?.(error);
848
+ lastError = error;
849
+ // Always drop the socket first — a closed client may have joined after end().
850
+ abortConnectMedia();
851
+ if (closed) throw new Error("Ended");
852
+ onStatus(error.message || "Reconnecting");
853
+ if (attempt >= PORTAL_AFFINITY_RETRIES) break;
854
+ if (error?.peer) {
855
+ portalPeer = String(error.peer).trim();
856
+ writeStoredPortalPeer(sessionId, portalPeer);
857
+ } else if (isPortalMismatchError(error) || /portal|502|network|reach/i.test(String(error?.message || ""))) {
858
+ await ensurePortalAffinity({ force: true });
859
+ } else {
860
+ break;
861
+ }
862
+ await new Promise((r) => setTimeout(r, 250 * attempt));
673
863
  }
674
- });
864
+ }
865
+ throw lastError || new Error("Could not join portal");
866
+ })().catch((error) => {
867
+ abortConnectMedia();
868
+ settleReady?.(error);
675
869
  });
676
- })();
870
+ });
677
871
  return readyPromise;
678
872
  }
679
873
 
@@ -910,41 +1104,60 @@ export function createClient(options = {}) {
910
1104
  }
911
1105
 
912
1106
  async function openRecorder(recordingId) {
913
- await ensureRecorderAffinity();
914
1107
  await emit(socket, "claimRecording", { recordingId });
915
1108
  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) => {
1109
+ const webinarId = recordingWebinarId(sessionId);
1110
+ let lastError = null;
1111
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
1112
+ if (closed) throw new Error("The session has ended");
1113
+ try {
1114
+ const peer = await ensureRecorderAffinity({ force: attempt > 1 });
1115
+ const next = new CanvasRecorder({
1116
+ webinarId,
1117
+ webinarName: sessionId,
1118
+ recordingId,
1119
+ endpoint,
1120
+ token,
1121
+ selfName: displayName,
1122
+ canvasBackground: recordingCanvasBackground,
1123
+ recorderPeer: peer,
1124
+ fps: recordingFps,
1125
+ bitrate: recordingBitrate,
1126
+ // Chunks start immediately; empty stage uses the same host placeholder as live UI.
1127
+ onCaptureChange: () => notifyRecording(next),
1128
+ onFailure: (error) => {
1129
+ if (recorder !== next) return;
1130
+ recorder = null;
1131
+ onRecording("stopped");
1132
+ onError(error);
1133
+ },
1134
+ });
1135
+ recorder = next;
1136
+ next.wanted = true;
1137
+ notifyRecording(next);
1138
+ for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
1139
+ next.sync(tracksForRecording(), stagePeopleForRecording());
1140
+ await next.start();
927
1141
  if (recorder !== next) return;
928
- recorder = null;
1142
+ activeRecordingId = recordingId;
1143
+ notifyRecording(next);
1144
+ return;
1145
+ } catch (error) {
1146
+ lastError = error;
1147
+ if (recorder) {
1148
+ const failed = recorder;
1149
+ recorder = null;
1150
+ try { await failed.finish({ finalize: false }); } catch { /* ignore */ }
1151
+ }
929
1152
  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));
1153
+ const message = error instanceof Error ? error.message : String(error);
1154
+ if (/recording is already finished/i.test(message)) throw error;
1155
+ if (attempt >= 3) break;
1156
+ if (!/recorder|affinity|502|503|504|network|reach|upload failed/i.test(message)) throw error;
1157
+ await new Promise((r) => setTimeout(r, 250 * attempt));
1158
+ }
944
1159
  }
945
- if (recorder !== next) return;
946
- activeRecordingId = recordingId;
947
- notifyRecording(next);
1160
+ throw lastError instanceof Error ? lastError : new Error(String(lastError || "Could not start recording"));
948
1161
  }
949
1162
 
950
1163
  async function startRecording() {
@@ -984,6 +1197,201 @@ export function createClient(options = {}) {
984
1197
  onRecording("stopped");
985
1198
  }
986
1199
 
1200
+ // ---------------------------------------------------------------------------
1201
+ // RTMP live streaming
1202
+
1203
+ function setRtmpState(next) {
1204
+ if (!next || typeof next !== "object") return;
1205
+ rtmpState = { ...rtmpState, ...next, enabled: Boolean(next.enabled ?? rtmpState.enabled) };
1206
+ onRtmpStatus({ ...rtmpState, composing: Boolean(live) });
1207
+ }
1208
+
1209
+ function h264Codec() {
1210
+ const senderCaps = typeof RTCRtpSender !== "undefined" && RTCRtpSender.getCapabilities
1211
+ ? RTCRtpSender.getCapabilities("video")
1212
+ : null;
1213
+ if (senderCaps && !senderCaps.codecs.some((codec) => /h264/i.test(codec.mimeType))) return null;
1214
+ return device?.rtpCapabilities?.codecs?.find((codec) => /^video\/h264$/i.test(codec.mimeType)) || null;
1215
+ }
1216
+
1217
+ /** True when this browser can compose and encode the H264 live stream. */
1218
+ function canLiveStream() {
1219
+ return LiveCompositor.supported() && Boolean(h264Codec());
1220
+ }
1221
+
1222
+ async function produceHidden(source, track, extra = {}) {
1223
+ const options = { track, stopTracks: false, appData: { source }, ...extra };
1224
+ try {
1225
+ return await sendTransport.produce(options);
1226
+ } catch (error) {
1227
+ if (!shouldRecreateSendTransport(error)) throw error;
1228
+ await recreateSendTransport();
1229
+ return sendTransport.produce(options);
1230
+ }
1231
+ }
1232
+
1233
+ async function closeLiveProducers() {
1234
+ const producers = liveProducers;
1235
+ liveProducers = [];
1236
+ for (const producer of producers) {
1237
+ try { producer.close(); } catch { /* ignore */ }
1238
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
1239
+ }
1240
+ }
1241
+
1242
+ async function createLiveCompositor() {
1243
+ const next = new LiveCompositor({
1244
+ fps: rtmpFps,
1245
+ selfName: displayName,
1246
+ canvasBackground: recordingCanvasBackground,
1247
+ onFailure: (error) => {
1248
+ if (live !== next) return;
1249
+ onError(error);
1250
+ stopRtmp().catch(() => {});
1251
+ },
1252
+ });
1253
+ for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
1254
+ next.sync(tracksForRecording(), stagePeopleForRecording());
1255
+ await next.start();
1256
+ if (!next.videoTrack || !next.audioTrack) {
1257
+ await next.finish();
1258
+ throw new Error("The live stream compositor did not start");
1259
+ }
1260
+ return next;
1261
+ }
1262
+
1263
+ /** Compose the stage and publish hidden rtmp-video (H264) + rtmp-audio on the origin. */
1264
+ async function startLiveOutput() {
1265
+ if (closed) throw new Error("The session has ended");
1266
+ if (live) return;
1267
+ if (startingLive) return startingLive;
1268
+ startingLive = (async () => {
1269
+ await connect();
1270
+ if (!sendTransport) throw new Error("The session is not ready");
1271
+ if (!LiveCompositor.supported()) throw new Error("This browser cannot compose a live stream");
1272
+ const codec = h264Codec();
1273
+ if (!codec) throw new Error("This browser cannot encode H264, which live streaming needs. Use Chrome, Edge, or Safari.");
1274
+ const next = await createLiveCompositor();
1275
+ live = next;
1276
+ try {
1277
+ const video = await produceHidden("rtmp-video", next.videoTrack, {
1278
+ codec,
1279
+ encodings: [{ maxBitrate: rtmpBitrate, maxFramerate: rtmpFps }],
1280
+ codecOptions: { videoGoogleStartBitrate: Math.max(300, Math.min(2500, Math.round(rtmpBitrate / 2000))) },
1281
+ });
1282
+ liveProducers.push(video);
1283
+ // Platforms expect a steady frame size; let WebRTC drop frames rather than resolution.
1284
+ try {
1285
+ const params = video.rtpSender?.getParameters();
1286
+ if (params) {
1287
+ params.degradationPreference = "maintain-resolution";
1288
+ await video.rtpSender.setParameters(params);
1289
+ }
1290
+ } catch {
1291
+ /* optional */
1292
+ }
1293
+ const audio = await produceHidden("rtmp-audio", next.audioTrack);
1294
+ liveProducers.push(audio);
1295
+ } catch (error) {
1296
+ await closeLiveProducers();
1297
+ if (live === next) live = null;
1298
+ await next.finish().catch(() => {});
1299
+ throw error;
1300
+ }
1301
+ setRtmpState({});
1302
+ })();
1303
+ try {
1304
+ await startingLive;
1305
+ } finally {
1306
+ startingLive = null;
1307
+ }
1308
+ }
1309
+
1310
+ async function stopLiveOutput() {
1311
+ if (startingLive) await startingLive.catch(() => {});
1312
+ const current = live;
1313
+ live = null;
1314
+ await closeLiveProducers();
1315
+ await current?.finish().catch(() => {});
1316
+ setRtmpState({});
1317
+ }
1318
+
1319
+ /**
1320
+ * Go Live: start streaming the stage to every enabled destination (host / co-host).
1321
+ * Optional `destinations` are added to the meeting first:
1322
+ * `[{ platform: "youtube"|"twitch"|"facebook"|"custom", streamKey, serverUrl?, label? }]`.
1323
+ */
1324
+ async function startRtmp({ destinations } = {}) {
1325
+ await connect();
1326
+ if (!canLiveStream()) {
1327
+ throw new Error("This browser cannot encode H264, which live streaming needs. Use Chrome, Edge, or Safari.");
1328
+ }
1329
+ const result = await emit(socket, "startRtmp", { destinations }, 15000);
1330
+ setRtmpState(result.rtmp);
1331
+ try {
1332
+ await startLiveOutput();
1333
+ } catch (error) {
1334
+ await emit(socket, "stopRtmp", {}).catch(() => {});
1335
+ throw error;
1336
+ }
1337
+ return rtmpState;
1338
+ }
1339
+
1340
+ async function stopRtmp() {
1341
+ if (socket?.connected) {
1342
+ const result = await emit(socket, "stopRtmp", {}).catch(() => null);
1343
+ if (result?.rtmp) setRtmpState(result.rtmp);
1344
+ }
1345
+ await stopLiveOutput();
1346
+ return rtmpState;
1347
+ }
1348
+
1349
+ async function rtmpCall(event, body) {
1350
+ await connect();
1351
+ const result = await emit(socket, event, body, 15000);
1352
+ setRtmpState(result.rtmp);
1353
+ return rtmpState;
1354
+ }
1355
+
1356
+ /** Current live-stream state + destinations (destinations only for host / co-host). */
1357
+ const getRtmpStatus = () => rtmpCall("getRtmp", {});
1358
+ const addRtmpDestinations = (destinations) =>
1359
+ rtmpCall("addRtmpDestinations", { destinations: Array.isArray(destinations) ? destinations : [destinations] });
1360
+ const setRtmpDestination = (destinationId, enabled) =>
1361
+ rtmpCall("setRtmpDestination", { destinationId, enabled: enabled !== false });
1362
+ const removeRtmpDestination = (destinationId) => rtmpCall("removeRtmpDestination", { destinationId });
1363
+
1364
+ /** Recording frame rate for the next recording start (1–60). */
1365
+ function setRecordingFps(fps) {
1366
+ recordingFps = clampFps(fps, recordingFps);
1367
+ return recordingFps;
1368
+ }
1369
+
1370
+ /** RTMP frame rate (1–60). Applied live: the compositor restarts and swaps tracks in place. */
1371
+ async function setRtmpFps(fps) {
1372
+ const next = clampFps(fps, rtmpFps);
1373
+ if (next === rtmpFps) return rtmpFps;
1374
+ rtmpFps = next;
1375
+ if (!live || liveProducers.length < 2) return rtmpFps;
1376
+ const previous = live;
1377
+ const replacement = await createLiveCompositor();
1378
+ const [video, audio] = liveProducers;
1379
+ await video.replaceTrack({ track: replacement.videoTrack });
1380
+ await audio.replaceTrack({ track: replacement.audioTrack });
1381
+ try {
1382
+ const params = video.rtpSender?.getParameters();
1383
+ if (params?.encodings?.[0]) {
1384
+ params.encodings[0].maxFramerate = rtmpFps;
1385
+ await video.rtpSender.setParameters(params);
1386
+ }
1387
+ } catch {
1388
+ /* optional */
1389
+ }
1390
+ live = replacement;
1391
+ await previous.finish().catch(() => {});
1392
+ return rtmpFps;
1393
+ }
1394
+
987
1395
  /**
988
1396
  * Leave the session.
989
1397
  * options.finalize / options.endSession: start remux+upload now (no handoff).
@@ -992,12 +1400,18 @@ export function createClient(options = {}) {
992
1400
  async function end(options = {}) {
993
1401
  if (closed) return;
994
1402
  closed = true;
1403
+ if (stageDebugTimer) {
1404
+ clearInterval(stageDebugTimer);
1405
+ stageDebugTimer = null;
1406
+ }
995
1407
  settleReady?.(new Error("Ended"));
996
1408
  // Finalize only on explicit stop-session / finalize. Browser close uses disconnect handoff.
997
1409
  const forceFinalize = options.finalize === true || options.endSession === true;
998
1410
  const current = recorder;
999
1411
  recorder = null;
1000
1412
  if (forceFinalize) activeRecordingId = null;
1413
+ // Live output stops locally; the portal hands composing to another publisher or goes offline.
1414
+ await stopLiveOutput().catch(() => {});
1001
1415
  try {
1002
1416
  if (current) {
1003
1417
  let handoff = false;
@@ -1037,9 +1451,12 @@ export function createClient(options = {}) {
1037
1451
  entry.producer.close();
1038
1452
  }
1039
1453
  locals.clear();
1040
- sendTransport?.close();
1041
- recvTransport?.close();
1042
- socket?.close();
1454
+ try { sendTransport?.close(); } catch { /* ignore */ }
1455
+ try { recvTransport?.close(); } catch { /* ignore */ }
1456
+ sendTransport = null;
1457
+ recvTransport = null;
1458
+ // disconnect() so the portal dropPeer runs; close() alone can race a late join.
1459
+ destroySocket();
1043
1460
  onStatus("Ended");
1044
1461
  tiles.clear();
1045
1462
  }
@@ -1082,6 +1499,18 @@ export function createClient(options = {}) {
1082
1499
  subscribe: guard(subscribe),
1083
1500
  startRecording: guard(startRecording),
1084
1501
  stopRecording: guard(stopRecording),
1502
+ setRecordingFps,
1503
+ getRecordingFps: () => recordingFps,
1504
+ startRtmp: guard(startRtmp),
1505
+ stopRtmp: guard(stopRtmp),
1506
+ getRtmpStatus: guard(getRtmpStatus),
1507
+ addRtmpDestinations: guard(addRtmpDestinations),
1508
+ setRtmpDestination: guard(setRtmpDestination),
1509
+ removeRtmpDestination: guard(removeRtmpDestination),
1510
+ setRtmpFps: guard(setRtmpFps),
1511
+ getRtmpFps: () => rtmpFps,
1512
+ canLiveStream,
1513
+ isRtmpEnabled: () => Boolean(rtmpState.enabled),
1085
1514
  setRecordingCrop,
1086
1515
  setRecordingStage,
1087
1516
  getUserList: guard(getUserList),