mediascale-sdk 1.0.9 → 1.0.10

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
4
4
  "description": "Mediascale React/browser SDK for live sessions, WebRTC publish/subscribe, and recording",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -108,6 +108,8 @@ export function createClient(options = {}) {
108
108
  let device = null;
109
109
  let sendTransport = null;
110
110
  let recvTransport = null;
111
+ /** Single-flight when portal parks this viewer and later emits edgeChanged. */
112
+ let recvRecovering = null;
111
113
  let iceServers = iceOverride || [];
112
114
  let closed = false;
113
115
  let subscribed = false;
@@ -129,9 +131,11 @@ export function createClient(options = {}) {
129
131
 
130
132
  function userOnStage(user) {
131
133
  if (!user) return false;
132
- if (user.onStage != null) return Boolean(user.onStage);
133
134
  const role = String(user.stageRole || "").trim().toLowerCase();
134
- return role === "host" || role === "co-host" || role === "speaker";
135
+ // Host / co-host are always on stage (screen / whiteboard / cam for everyone).
136
+ if (role === "host" || role === "co-host") return true;
137
+ if (user.onStage != null) return Boolean(user.onStage);
138
+ return role === "speaker";
135
139
  }
136
140
 
137
141
  function normalizeStagePerson(person) {
@@ -350,6 +354,89 @@ export function createClient(options = {}) {
350
354
  });
351
355
  }
352
356
 
357
+ function bindSendTransport(transport) {
358
+ transport.on("connect", ({ dtlsParameters }, callback, errback) => {
359
+ emit(socket, "connectTransport", { transportId: transport.id, dtlsParameters }).then(() => callback()).catch(errback);
360
+ });
361
+ transport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => {
362
+ emit(socket, "produce", {
363
+ transportId: transport.id,
364
+ kind,
365
+ rtpParameters,
366
+ source: appData.source,
367
+ }).then((result) => callback({ id: result.id })).catch(errback);
368
+ });
369
+ transport.on("connectionstatechange", (state) => {
370
+ if (state === "failed" || state === "disconnected") onStatus("Network unstable");
371
+ else if (state === "connected") onStatus("Live");
372
+ });
373
+ }
374
+
375
+ function bindRecvTransport(transport) {
376
+ transport.on("connect", ({ dtlsParameters }, callback, errback) => {
377
+ emit(socket, "connectTransport", { transportId: transport.id, dtlsParameters }).then(() => callback()).catch(errback);
378
+ });
379
+ }
380
+
381
+ function clearRemoteTiles() {
382
+ for (const [producerId, tile] of [...tiles.entries()]) {
383
+ if (tile.local) continue;
384
+ tiles.delete(producerId);
385
+ onTrackEnded({ producerId });
386
+ }
387
+ syncRecording();
388
+ }
389
+
390
+ /**
391
+ * After packChannel parks this viewer, portal emits releaseConsumers then later
392
+ * edgeChanged. Rebuild the receive transport and pull every producer again
393
+ * (including a host screen share that started while we were parked).
394
+ */
395
+ async function recoverRecvTransport() {
396
+ if (closed || !device || !socket?.connected) return;
397
+ if (recvRecovering) return recvRecovering;
398
+ recvRecovering = (async () => {
399
+ try {
400
+ onStatus("Reconnecting media…");
401
+ pending.length = 0;
402
+ try { recvTransport?.close(); } catch { /* ignore */ }
403
+ recvTransport = null;
404
+ clearRemoteTiles();
405
+
406
+ const recvParams = await emit(socket, "createTransport", { direction: "recv" });
407
+ if (closed) return;
408
+ recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
409
+ bindRecvTransport(recvTransport);
410
+
411
+ const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
412
+ for (const params of started.consumers || []) await play(params);
413
+ if (!closed) onStatus("Connected");
414
+ } catch (error) {
415
+ if (!closed) {
416
+ onError(error);
417
+ onStatus(error.message || "Media reconnect failed");
418
+ }
419
+ } finally {
420
+ recvRecovering = null;
421
+ }
422
+ })();
423
+ return recvRecovering;
424
+ }
425
+
426
+ /** Recreate send transport on the next vacant origin after the current one fills. */
427
+ async function recreateSendTransport() {
428
+ try { sendTransport?.close(); } catch { /* ignore */ }
429
+ sendTransport = null;
430
+ const sendParams = await emit(socket, "createTransport", { direction: "send" });
431
+ sendTransport = device.createSendTransport({ ...sendParams, iceServers });
432
+ bindSendTransport(sendTransport);
433
+ }
434
+
435
+ function shouldRecreateSendTransport(error) {
436
+ const msg = String(error?.message || error || "");
437
+ return /out of credits|transport not found|ORIGIN_FULL|Origin is full/i.test(msg);
438
+ }
439
+
353
440
  // Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
354
441
  async function produce(source, track, original = track) {
355
442
  let producer;
@@ -363,7 +450,14 @@ export function createClient(options = {}) {
363
450
  videoGoogleStartBitrate: Math.max(100, Math.min(1000, Math.round(maxBitrate / 2000))),
364
451
  };
365
452
  }
366
- producer = await sendTransport.produce(options);
453
+ if (!sendTransport) throw new Error("The session is not ready");
454
+ try {
455
+ producer = await sendTransport.produce(options);
456
+ } catch (error) {
457
+ if (!shouldRecreateSendTransport(error)) throw error;
458
+ await recreateSendTransport();
459
+ producer = await sendTransport.produce(options);
460
+ }
367
461
  if (closed) throw new Error("The session has ended");
368
462
  if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
369
463
  } catch (error) {
@@ -422,7 +516,8 @@ export function createClient(options = {}) {
422
516
  if (!closed) onStatus("Network unstable");
423
517
  });
424
518
  socket.on("sessionEnded", () => {
425
- end().catch((error) => onError(error));
519
+ // Whole room is ending — always finalize if we hold the recorder (never hand off).
520
+ end({ finalize: true }).catch((error) => onError(error));
426
521
  });
427
522
  socket.on("releaseRecording", () => {
428
523
  const current = recorder;
@@ -440,7 +535,8 @@ export function createClient(options = {}) {
440
535
  const current = recorder;
441
536
  if (!current) return;
442
537
  recorder = null;
443
- current.finish()
538
+ // Background remux — do not surface a blocking status in the meet UI.
539
+ current.finish({ waitFinalize: false })
444
540
  .then(() => onRecording("stopped"))
445
541
  .catch((error) => onError(error));
446
542
  });
@@ -472,6 +568,30 @@ export function createClient(options = {}) {
472
568
  socket.on("userBlocked", (payload) => {
473
569
  if (!closed) onUserBlocked(payload || {});
474
570
  });
571
+ // Capacity pack while someone publishes (e.g. host screen) may park this viewer.
572
+ socket.on("waiting", (payload = {}) => {
573
+ if (!closed) onStatus(payload.message || "Please wait, we will connect you soon");
574
+ });
575
+ socket.on("releaseConsumers", () => {
576
+ if (closed) return;
577
+ pending.length = 0;
578
+ try { recvTransport?.close(); } catch { /* ignore */ }
579
+ recvTransport = null;
580
+ clearRemoteTiles();
581
+ });
582
+ socket.on("edgeChanged", () => {
583
+ recoverRecvTransport().catch((error) => onError(error));
584
+ });
585
+ socket.on("newConsumer", (params) => {
586
+ play(params).catch((error) => onError(error));
587
+ });
588
+ socket.on("producerClosed", ({ producerId }) => {
589
+ for (let i = pending.length - 1; i >= 0; i -= 1) {
590
+ if (pending[i].producerId === producerId) pending.splice(i, 1);
591
+ }
592
+ if (tiles.delete(producerId)) syncRecording();
593
+ onTrackEnded({ producerId });
594
+ });
475
595
  socket.on("connect", async () => {
476
596
  try {
477
597
  if (closed) return;
@@ -494,37 +614,11 @@ export function createClient(options = {}) {
494
614
 
495
615
  const sendParams = await emit(socket, "createTransport", { direction: "send" });
496
616
  sendTransport = device.createSendTransport({ ...sendParams, iceServers });
497
- sendTransport.on("connect", ({ dtlsParameters }, callback, errback) => {
498
- emit(socket, "connectTransport", { transportId: sendTransport.id, dtlsParameters }).then(() => callback()).catch(errback);
499
- });
500
- sendTransport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => {
501
- emit(socket, "produce", {
502
- transportId: sendTransport.id,
503
- kind,
504
- rtpParameters,
505
- source: appData.source,
506
- }).then((result) => callback({ id: result.id })).catch(errback);
507
- });
508
- sendTransport.on("connectionstatechange", (state) => {
509
- if (state === "failed" || state === "disconnected") onStatus("Network unstable");
510
- else if (state === "connected") onStatus("Live");
511
- });
617
+ bindSendTransport(sendTransport);
512
618
 
513
619
  const recvParams = await emit(socket, "createTransport", { direction: "recv" });
514
620
  recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
515
- recvTransport.on("connect", ({ dtlsParameters }, callback, errback) => {
516
- emit(socket, "connectTransport", { transportId: recvTransport.id, dtlsParameters }).then(() => callback()).catch(errback);
517
- });
518
- socket.on("newConsumer", (params) => {
519
- play(params).catch((error) => onError(error));
520
- });
521
- socket.on("producerClosed", ({ producerId }) => {
522
- for (let i = pending.length - 1; i >= 0; i -= 1) {
523
- if (pending[i].producerId === producerId) pending.splice(i, 1);
524
- }
525
- if (tiles.delete(producerId)) syncRecording();
526
- onTrackEnded({ producerId });
527
- });
621
+ bindRecvTransport(recvTransport);
528
622
  const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
529
623
  for (const params of started.consumers || []) await play(params);
530
624
  // Fresh roster after ready (covers anyone who joined during transport setup).
@@ -708,8 +802,16 @@ export function createClient(options = {}) {
708
802
  }
709
803
  try {
710
804
  const screen = await produce("screen", videoTrack);
805
+ // Screen audio is optional — never tear down a live video share if mic capture fails.
711
806
  const audioTrack = stream.getAudioTracks()[0];
712
- if (audioTrack) await produce("screen", audioTrack);
807
+ if (audioTrack) {
808
+ try {
809
+ await produce("screen", audioTrack);
810
+ } catch (audioError) {
811
+ try { audioTrack.stop(); } catch { /* ignore */ }
812
+ onError(audioError);
813
+ }
814
+ }
713
815
  return screen;
714
816
  } catch (error) {
715
817
  stream.getTracks().forEach((track) => track.stop());
@@ -791,12 +893,13 @@ export function createClient(options = {}) {
791
893
  }
792
894
  if (startingRecorder) return startingRecorder;
793
895
  startingRecorder = (async () => {
794
- await emit(socket, "claimRecording", {});
896
+ const recordingId = await recordingIdFor(sessionId);
897
+ await emit(socket, "claimRecording", { recordingId });
795
898
  if (closed || recorder) return;
796
899
  const next = new CanvasRecorder({
797
900
  webinarId: recordingWebinarId(sessionId),
798
901
  webinarName: sessionId,
799
- recordingId: await recordingIdFor(sessionId),
902
+ recordingId,
800
903
  endpoint,
801
904
  token,
802
905
  selfName: displayName,
@@ -837,27 +940,50 @@ export function createClient(options = {}) {
837
940
  onRecording("stopped");
838
941
  }
839
942
 
840
- async function end() {
943
+ /**
944
+ * Leave the session.
945
+ * options.finalize / options.endSession: start remux+upload now (no handoff).
946
+ * options.endSession: also ask the portal to disconnect everyone else — does not wait for remux.
947
+ */
948
+ async function end(options = {}) {
841
949
  if (closed) return;
842
950
  closed = true;
843
951
  settleReady?.(new Error("Ended"));
952
+ // Finalize only on explicit stop-session / finalize. Browser close uses disconnect handoff.
953
+ const forceFinalize = options.finalize === true || options.endSession === true;
844
954
  const current = recorder;
845
955
  recorder = null;
846
956
  try {
847
957
  if (current) {
848
958
  let handoff = false;
849
- if (socket?.connected) {
959
+ if (forceFinalize) {
960
+ // Stop-session: start remux immediately, do not await, do not change meet status.
961
+ if (socket?.connected) {
962
+ void emit(socket, "leaveRecording", { ending: true }).catch(() => {});
963
+ }
964
+ current.kickFinalize();
965
+ void current.finish({ waitFinalize: false })
966
+ .then(() => onRecording("stopped"))
967
+ .catch((error) => onError(error));
968
+ onRecording("stopped");
969
+ } else if (socket?.connected) {
850
970
  try {
851
971
  const result = await emit(socket, "leaveRecording", {});
852
972
  handoff = Boolean(result?.handoff);
853
973
  } catch {
854
974
  handoff = false;
855
975
  }
976
+ if (handoff) await current.handoff();
977
+ else await current.finish();
978
+ onRecording("stopped");
979
+ } else {
980
+ await current.finish();
981
+ onRecording("stopped");
856
982
  }
857
- // Cohost continues the same recordingId; only finalize when nobody else can take over.
858
- if (handoff) await current.handoff();
859
- else await current.finish();
860
- onRecording("stopped");
983
+ }
984
+ if (options.endSession === true && socket?.connected) {
985
+ // Do not block leave/redirect on room teardown ack.
986
+ void emit(socket, "endSession", {}).catch(() => {});
861
987
  }
862
988
  } finally {
863
989
  for (const entry of locals.values()) {
package/src/record.js CHANGED
@@ -149,10 +149,9 @@ export class CanvasRecorder {
149
149
  this.untilStop = new Promise((resolve) => {
150
150
  this.release = resolve;
151
151
  });
152
- this.onPageHide = (event) => {
153
- event.preventDefault();
154
- event.returnValue = "";
155
- };
152
+ // No beforeunload prompt — browser close hands off via portal disconnect;
153
+ // End session redirects without a leave-site warning.
154
+ this.onBeforeUnload = null;
156
155
  }
157
156
 
158
157
  async start(audio) {
@@ -310,7 +309,11 @@ export class CanvasRecorder {
310
309
  await this.drainRecorder(rec);
311
310
  await this.pump();
312
311
  // Skip finalize when capture never started (e.g. prepare failed before beginCapture).
313
- if (options.finalize !== false && didCapture) await this.finalize();
312
+ if (options.finalize !== false && didCapture) {
313
+ // waitFinalize:false — kick remux/upload without blocking session teardown.
314
+ if (options.waitFinalize === false) void this.finalize({ wait: false }).catch(() => {});
315
+ else await this.finalize();
316
+ }
314
317
  } finally {
315
318
  this.release?.();
316
319
  this.release = undefined;
@@ -411,7 +414,6 @@ export class CanvasRecorder {
411
414
  this.capture = video;
412
415
  this.captureStream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
413
416
  this.prepared = true;
414
- window.addEventListener("beforeunload", this.onPageHide);
415
417
  }
416
418
 
417
419
  async beginCapture() {
@@ -825,8 +827,25 @@ export class CanvasRecorder {
825
827
  return true;
826
828
  }
827
829
 
828
- async finalize() {
830
+ /** Fire remux/upload without waiting (survives tab redirect via keepalive). */
831
+ kickFinalize() {
832
+ if (!this.startedAt) return;
833
+ const durationMs = Date.now() - this.startedAt;
834
+ fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
835
+ method: "POST",
836
+ headers: this.authHeaders({ "content-type": "application/json" }),
837
+ body: JSON.stringify({ durationMs, force: true }),
838
+ keepalive: true,
839
+ }).catch(() => {});
840
+ }
841
+
842
+ async finalize(options = {}) {
829
843
  const durationMs = this.startedAt ? Date.now() - this.startedAt : 0;
844
+ // Background path for stop-session: do not wait for remux; keepalive survives teardown.
845
+ if (options.wait === false) {
846
+ this.kickFinalize();
847
+ return;
848
+ }
830
849
  for (let round = 0; round < 3; round += 1) {
831
850
  const res = await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
832
851
  method: "POST",
@@ -868,7 +887,7 @@ export class CanvasRecorder {
868
887
 
869
888
  teardown() {
870
889
  this.canvas?.remove();
871
- window.removeEventListener("beforeunload", this.onPageHide);
890
+ if (this.onBeforeUnload) window.removeEventListener("beforeunload", this.onBeforeUnload);
872
891
  if (this._audioUnlock) {
873
892
  for (const type of ["pointerdown", "keydown", "touchstart", "click"]) {
874
893
  window.removeEventListener(type, this._audioUnlock, true);