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/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.
@@ -140,6 +193,13 @@ export function createClient(options = {}) {
140
193
  const pending = [];
141
194
  let readyPromise = null;
142
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: [] };
143
203
 
144
204
  function userOnStage(user) {
145
205
  if (!user) return false;
@@ -247,7 +307,10 @@ export function createClient(options = {}) {
247
307
  }
248
308
 
249
309
  function syncRecording() {
250
- recorder?.sync(tracksForRecording(), stagePeopleForRecording());
310
+ const tracks = tracksForRecording();
311
+ const people = stagePeopleForRecording();
312
+ recorder?.sync(tracks, people);
313
+ live?.sync(tracks, people);
251
314
  }
252
315
 
253
316
  /**
@@ -285,8 +348,9 @@ export function createClient(options = {}) {
285
348
  const next = normalizeVideoCrop(crop);
286
349
  if (!next) recordingCrops.delete(id);
287
350
  else recordingCrops.set(id, next);
288
- if (recorder) {
289
- recorder.setVideoCrop(id, next);
351
+ if (recorder || live) {
352
+ recorder?.setVideoCrop(id, next);
353
+ live?.setVideoCrop(id, next);
290
354
  syncRecording();
291
355
  }
292
356
  }
@@ -513,188 +577,297 @@ export function createClient(options = {}) {
513
577
  return { producerId: producer.id, stream, source };
514
578
  }
515
579
 
516
- async function ensurePortalAffinity() {
580
+ async function ensurePortalAffinity({ force = false } = {}) {
517
581
  try {
518
582
  const response = await fetch(`${endpoint}/portal/api/v1/affinity?channelId=${encodeURIComponent(sessionId)}`, {
519
583
  credentials: "include",
520
584
  });
521
- if (!response.ok) return;
585
+ if (!response.ok) return portalPeer;
522
586
  const body = await response.json().catch(() => null);
523
- if (body?.peer && typeof document !== "undefined") {
524
- 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);
525
590
  }
591
+ return portalPeer;
526
592
  } catch {
527
593
  /* gateway may still route to the seed portal */
594
+ if (!force && portalPeer) return portalPeer;
595
+ return portalPeer;
528
596
  }
529
597
  }
530
598
 
531
- async function ensureRecorderAffinity() {
599
+ async function ensureRecorderAffinity({ force = false } = {}) {
532
600
  const webinarId = recordingWebinarId(sessionId);
533
601
  try {
534
- const response = await fetch(
535
- `${endpoint}/recorder/api/v1/affinity?webinarId=${encodeURIComponent(webinarId)}`,
536
- { credentials: "include" },
537
- );
538
- if (!response.ok) return;
539
- const body = await response.json().catch(() => null);
540
- if (body?.peer && typeof document !== "undefined") {
541
- 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);
542
784
  }
543
785
  } catch {
544
- /* 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));
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
+ }
545
803
  }
546
804
  }
547
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");
820
+ }
821
+
548
822
  async function connect() {
549
823
  if (readyPromise) return readyPromise;
550
- readyPromise = (async () => {
551
- await ensurePortalAffinity();
552
- return new Promise((resolve, reject) => {
553
- settleReady = (error) => {
554
- settleReady = null;
555
- if (error) reject(error);
556
- else resolve();
557
- };
558
- socket = io(endpoint, {
559
- transports: ["websocket"],
560
- withCredentials: true,
561
- auth: { token, client: "mediascale-sdk" },
562
- });
563
- socket.on("connect_error", () => {
564
- if (!closed) onStatus("Network unstable");
565
- });
566
- socket.on("sessionEnded", () => {
567
- // Whole room is ending — always finalize if we hold the recorder (never hand off).
568
- end({ finalize: true }).catch((error) => onError(error));
569
- });
570
- socket.on("releaseRecording", () => {
571
- const current = recorder;
572
- recorder = null;
573
- if (!current) return;
574
- current.handoff()
575
- .then(() => onRecording("stopped"))
576
- .catch((error) => onError(error));
577
- });
578
- // Portal elected this peer to continue an in-progress recording after the host left.
579
- socket.on("takeRecording", () => {
580
- startRecording().catch((error) => onError(error));
581
- });
582
- socket.on("finalizeRecording", () => {
583
- const current = recorder;
584
- if (!current) return;
585
- recorder = null;
586
- // Background remux — do not surface a blocking status in the meet UI.
587
- current.finish({ waitFinalize: false })
588
- .then(() => onRecording("stopped"))
589
- .catch((error) => onError(error));
590
- });
591
- socket.on("activeSpeaker", (payload = {}) => {
592
- if (closed) return;
593
- const peerId = payload.peerId || null;
594
- onActiveSpeaker({
595
- peerId,
596
- displayName: payload.displayName || null,
597
- producerId: payload.producerId || null,
598
- local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
599
- });
600
- });
601
- socket.on("userJoined", (user) => {
602
- if (closed) return;
603
- ingestRosterUser(user);
604
- onUserJoined(user);
605
- });
606
- socket.on("userLeft", (user) => {
607
- if (closed) return;
608
- removeRosterUser(user);
609
- onUserLeft(user);
610
- });
611
- socket.on("userUpdated", (user) => {
612
- if (closed) return;
613
- ingestRosterUser(user);
614
- onUserUpdated(user);
615
- });
616
- socket.on("userBlocked", (payload) => {
617
- if (!closed) onUserBlocked(payload || {});
618
- });
619
- // Capacity pack while someone publishes (e.g. host screen) may park this viewer.
620
- socket.on("waiting", (payload = {}) => {
621
- if (!closed) onStatus(payload.message || "Please wait, we will connect you soon");
622
- });
623
- socket.on("releaseConsumers", () => {
624
- if (closed) return;
625
- pending.length = 0;
626
- try { recvTransport?.close(); } catch { /* ignore */ }
627
- recvTransport = null;
628
- clearRemoteTiles();
629
- });
630
- socket.on("edgeChanged", () => {
631
- recoverRecvTransport().catch((error) => onError(error));
632
- });
633
- socket.on("newConsumer", (params) => {
634
- play(params).catch((error) => onError(error));
635
- });
636
- socket.on("producerClosed", ({ producerId }) => {
637
- for (let i = pending.length - 1; i >= 0; i -= 1) {
638
- if (pending[i].producerId === producerId) pending.splice(i, 1);
639
- }
640
- if (tiles.delete(producerId)) syncRecording();
641
- onTrackEnded({ producerId });
642
- });
643
- 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();
644
836
  try {
645
- if (closed) return;
646
- onStatus("Joining");
647
- const joined = await emit(socket, "join", {
648
- channelId: sessionId,
649
- role: "publisher",
650
- displayName,
651
- ...clientHints(),
652
- });
653
- selfPeerId = joined.peerId || null;
654
- iceServers = iceOverride || joined.iceServers || [];
655
- applyPublishLimitsFromJoin(joined.publishLimits);
656
- if (Array.isArray(joined.users)) {
657
- ingestRosterUsers(joined.users);
658
- onUserList(joined.users);
659
- }
660
- device = new Device();
661
- await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
662
-
663
- const sendParams = await emit(socket, "createTransport", { direction: "send" });
664
- sendTransport = device.createSendTransport({ ...sendParams, iceServers });
665
- bindSendTransport(sendTransport);
666
-
667
- const recvParams = await emit(socket, "createTransport", { direction: "recv" });
668
- recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
669
- bindRecvTransport(recvTransport);
670
- const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
671
- for (const params of started.consumers || []) await play(params);
672
- // Fresh roster after ready (covers anyone who joined during transport setup).
673
- try {
674
- const list = await emit(socket, "getUserList", {});
675
- if (Array.isArray(list?.users)) {
676
- ingestRosterUsers(list.users);
677
- onUserList(list.users);
678
- }
679
- } catch {
680
- /* roster optional if portal is older */
681
- }
682
- if (joined.waiting) onStatus("Please wait, we will connect you soon");
683
- else onStatus("Ready");
684
- if (closed) return;
685
- // Do not await: AudioContext may need a click in this tab before chunks flow.
686
- if (recording && claims.role === "host") {
687
- startRecording().catch((error) => onError(error));
688
- }
689
- 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();
690
845
  settleReady?.();
846
+ return;
691
847
  } catch (error) {
692
- onStatus(error.message);
693
- 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));
694
863
  }
695
- });
864
+ }
865
+ throw lastError || new Error("Could not join portal");
866
+ })().catch((error) => {
867
+ abortConnectMedia();
868
+ settleReady?.(error);
696
869
  });
697
- })();
870
+ });
698
871
  return readyPromise;
699
872
  }
700
873
 
@@ -931,41 +1104,60 @@ export function createClient(options = {}) {
931
1104
  }
932
1105
 
933
1106
  async function openRecorder(recordingId) {
934
- await ensureRecorderAffinity();
935
1107
  await emit(socket, "claimRecording", { recordingId });
936
1108
  if (closed || recorder) return;
937
- const next = new CanvasRecorder({
938
- webinarId: recordingWebinarId(sessionId),
939
- webinarName: sessionId,
940
- recordingId,
941
- endpoint,
942
- token,
943
- selfName: displayName,
944
- canvasBackground: recordingCanvasBackground,
945
- // Chunks start immediately; empty stage uses the same host placeholder as live UI.
946
- onCaptureChange: () => notifyRecording(next),
947
- 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();
948
1141
  if (recorder !== next) return;
949
- 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
+ }
950
1152
  onRecording("stopped");
951
- onError(error);
952
- },
953
- });
954
- recorder = next;
955
- next.wanted = true;
956
- notifyRecording(next);
957
- for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
958
- next.sync(tracksForRecording(), stagePeopleForRecording());
959
- try {
960
- await next.start();
961
- } catch (error) {
962
- if (recorder === next) recorder = null;
963
- onRecording("stopped");
964
- 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
+ }
965
1159
  }
966
- if (recorder !== next) return;
967
- activeRecordingId = recordingId;
968
- notifyRecording(next);
1160
+ throw lastError instanceof Error ? lastError : new Error(String(lastError || "Could not start recording"));
969
1161
  }
970
1162
 
971
1163
  async function startRecording() {
@@ -1005,6 +1197,201 @@ export function createClient(options = {}) {
1005
1197
  onRecording("stopped");
1006
1198
  }
1007
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
+
1008
1395
  /**
1009
1396
  * Leave the session.
1010
1397
  * options.finalize / options.endSession: start remux+upload now (no handoff).
@@ -1023,6 +1410,8 @@ export function createClient(options = {}) {
1023
1410
  const current = recorder;
1024
1411
  recorder = null;
1025
1412
  if (forceFinalize) activeRecordingId = null;
1413
+ // Live output stops locally; the portal hands composing to another publisher or goes offline.
1414
+ await stopLiveOutput().catch(() => {});
1026
1415
  try {
1027
1416
  if (current) {
1028
1417
  let handoff = false;
@@ -1062,9 +1451,12 @@ export function createClient(options = {}) {
1062
1451
  entry.producer.close();
1063
1452
  }
1064
1453
  locals.clear();
1065
- sendTransport?.close();
1066
- recvTransport?.close();
1067
- 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();
1068
1460
  onStatus("Ended");
1069
1461
  tiles.clear();
1070
1462
  }
@@ -1107,6 +1499,18 @@ export function createClient(options = {}) {
1107
1499
  subscribe: guard(subscribe),
1108
1500
  startRecording: guard(startRecording),
1109
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),
1110
1514
  setRecordingCrop,
1111
1515
  setRecordingStage,
1112
1516
  getUserList: guard(getUserList),