@whereby.com/media 1.17.10 → 1.17.11

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/dist/index.cjs CHANGED
@@ -8,8 +8,20 @@ var sdpTransform = require('sdp-transform');
8
8
  var ipAddress = require('ip-address');
9
9
  var checkIp = require('check-ip');
10
10
  var validate = require('uuid-validate');
11
- var mediasoupClient = require('mediasoup-client');
12
11
  var EventEmitter = require('events');
12
+ var mediasoupClient = require('mediasoup-client');
13
+ var uaParserJs = require('ua-parser-js');
14
+ var Logger$1 = require('mediasoup-client/lib/Logger');
15
+ var utils = require('mediasoup-client/lib/utils');
16
+ var ortc = require('mediasoup-client/lib/ortc');
17
+ var sdpCommonUtils = require('mediasoup-client/lib/handlers/sdp/commonUtils');
18
+ var sdpUnifiedPlanUtils = require('mediasoup-client/lib/handlers/sdp/unifiedPlanUtils');
19
+ var ortcUtils = require('mediasoup-client/lib/handlers/ortc/utils');
20
+ var errors = require('mediasoup-client/lib/errors');
21
+ var HandlerInterface = require('mediasoup-client/lib/handlers/HandlerInterface');
22
+ var RemoteSdp = require('mediasoup-client/lib/handlers/sdp/RemoteSdp');
23
+ var scalabilityModes = require('mediasoup-client/lib/scalabilityModes');
24
+ var Safari12_js = require('mediasoup-client/lib/handlers/Safari12.js');
13
25
  var socket_ioClient = require('socket.io-client');
14
26
 
15
27
  function _interopNamespaceDefault(e) {
@@ -30,6 +42,11 @@ function _interopNamespaceDefault(e) {
30
42
  }
31
43
 
32
44
  var sdpTransform__namespace = /*#__PURE__*/_interopNamespaceDefault(sdpTransform);
45
+ var utils__namespace = /*#__PURE__*/_interopNamespaceDefault(utils);
46
+ var ortc__namespace = /*#__PURE__*/_interopNamespaceDefault(ortc);
47
+ var sdpCommonUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(sdpCommonUtils);
48
+ var sdpUnifiedPlanUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(sdpUnifiedPlanUtils);
49
+ var ortcUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(ortcUtils);
33
50
 
34
51
  const debugOn = process.env.NODE_ENV === "development" || new URLSearchParams(window.location.search).has("debug");
35
52
  class Logger {
@@ -852,7 +869,7 @@ function subscribeStats(subscription, options = OPTIONS, state = STATE) {
852
869
 
853
870
  var _a$6;
854
871
  const adapter$6 = (_a$6 = adapterRaw.default) !== null && _a$6 !== void 0 ? _a$6 : adapterRaw;
855
- const logger$a = new Logger();
872
+ const logger$b = new Logger();
856
873
  const browserName$2 = adapter$6.browserDetails.browser;
857
874
  const browserVersion$1 = adapter$6.browserDetails.version;
858
875
  function setCodecPreferenceSDP(sdp, vp9On, redOn) {
@@ -893,7 +910,7 @@ function setCodecPreferenceSDP(sdp, vp9On, redOn) {
893
910
  return newSdp;
894
911
  }
895
912
  catch (error) {
896
- logger$a.error("setCodecPreferenceSDP error:", error);
913
+ logger$b.error("setCodecPreferenceSDP error:", error);
897
914
  }
898
915
  }
899
916
  function cleanSdp(sdp) {
@@ -1102,7 +1119,7 @@ const MEDIA_JITTER_BUFFER_TARGET = 400;
1102
1119
 
1103
1120
  var _a$5;
1104
1121
  const adapter$5 = (_a$5 = adapterRaw.default) !== null && _a$5 !== void 0 ? _a$5 : adapterRaw;
1105
- const logger$9 = new Logger();
1122
+ const logger$a = new Logger();
1106
1123
  class Session {
1107
1124
  constructor({ peerConnectionId, bandwidth, maximumTurnBandwidth, deprioritizeH264Encoding, }) {
1108
1125
  this.peerConnectionId = peerConnectionId;
@@ -1247,7 +1264,7 @@ class Session {
1247
1264
  return this._setRemoteDescription(desc).then(() => {
1248
1265
  return setVideoBandwidthUsingSetParameters(this.pc, this.bandwidth);
1249
1266
  }, (e) => {
1250
- logger$9.warn("Could not set remote description from remote answer: ", e);
1267
+ logger$a.warn("Could not set remote description from remote answer: ", e);
1251
1268
  });
1252
1269
  }
1253
1270
  addIceCandidate(candidate) {
@@ -1263,7 +1280,7 @@ class Session {
1263
1280
  return;
1264
1281
  }
1265
1282
  this.pc.addIceCandidate(candidate).catch((e) => {
1266
- logger$9.warn("Failed to add ICE candidate ('%s'): %s", candidate ? candidate.candidate : null, e);
1283
+ logger$a.warn("Failed to add ICE candidate ('%s'): %s", candidate ? candidate.candidate : null, e);
1267
1284
  });
1268
1285
  });
1269
1286
  }
@@ -1282,7 +1299,7 @@ class Session {
1282
1299
  pc.close();
1283
1300
  }
1284
1301
  catch (e) {
1285
- logger$9.warn("failures during close of session", e);
1302
+ logger$a.warn("failures during close of session", e);
1286
1303
  }
1287
1304
  }
1288
1305
  hasConnectedPeerConnection() {
@@ -1735,7 +1752,7 @@ var rtcManagerEvents = {
1735
1752
 
1736
1753
  var _a$3, _b;
1737
1754
  const adapter$3 = (_a$3 = adapterRaw.default) !== null && _a$3 !== void 0 ? _a$3 : adapterRaw;
1738
- const logger$8 = new Logger();
1755
+ const logger$9 = new Logger();
1739
1756
  const ICE_PUBLIC_IP_GATHERING_TIMEOUT = 3 * 1000;
1740
1757
  const CAMERA_STREAM_ID = RtcStream.getCameraId();
1741
1758
  const browserName$1 = adapter$3.browserDetails.browser;
@@ -1885,7 +1902,7 @@ class P2pRtcManager {
1885
1902
  () => this._clearMediaServersRefresh(),
1886
1903
  this._serverSocket.on(PROTOCOL_RESPONSES.MEDIASERVER_CONFIG, (data) => {
1887
1904
  if (data.error) {
1888
- logger$8.warn("FETCH_MEDIASERVER_CONFIG failed:", data.error);
1905
+ logger$9.warn("FETCH_MEDIASERVER_CONFIG failed:", data.error);
1889
1906
  return;
1890
1907
  }
1891
1908
  this._updateAndScheduleMediaServersRefresh(data);
@@ -1896,7 +1913,7 @@ class P2pRtcManager {
1896
1913
  this._serverSocket.on(RELAY_MESSAGES.ICE_CANDIDATE, (data) => {
1897
1914
  const session = this._getSession(data.clientId);
1898
1915
  if (!session) {
1899
- logger$8.warn("No RTCPeerConnection on ICE_CANDIDATE", data);
1916
+ logger$9.warn("No RTCPeerConnection on ICE_CANDIDATE", data);
1900
1917
  return;
1901
1918
  }
1902
1919
  session.addIceCandidate(data.message);
@@ -1904,7 +1921,7 @@ class P2pRtcManager {
1904
1921
  this._serverSocket.on(RELAY_MESSAGES.ICE_END_OF_CANDIDATES, (data) => {
1905
1922
  const session = this._getSession(data.clientId);
1906
1923
  if (!session) {
1907
- logger$8.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES", data);
1924
+ logger$9.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES", data);
1908
1925
  return;
1909
1926
  }
1910
1927
  session.addIceCandidate(null);
@@ -1913,7 +1930,7 @@ class P2pRtcManager {
1913
1930
  var _a, _b;
1914
1931
  const session = this._getSession(data.clientId);
1915
1932
  if (!session) {
1916
- logger$8.warn("No RTCPeerConnection on SDP_OFFER", data);
1933
+ logger$9.warn("No RTCPeerConnection on SDP_OFFER", data);
1917
1934
  return;
1918
1935
  }
1919
1936
  const offer = this._transformIncomingSdp(data.message, session.pc);
@@ -1932,7 +1949,7 @@ class P2pRtcManager {
1932
1949
  var _a, _b;
1933
1950
  const session = this._getSession(data.clientId);
1934
1951
  if (!session) {
1935
- logger$8.warn("No RTCPeerConnection on SDP_ANSWER", data);
1952
+ logger$9.warn("No RTCPeerConnection on SDP_ANSWER", data);
1936
1953
  return;
1937
1954
  }
1938
1955
  const answer = this._transformIncomingSdp(data.message, session.pc);
@@ -1949,7 +1966,7 @@ class P2pRtcManager {
1949
1966
  }
1950
1967
  const screenshareStream = this.localStreams[screenShareStreamId];
1951
1968
  if (!screenshareStream) {
1952
- logger$8.warn("screenshare stream %s not found", screenShareStreamId);
1969
+ logger$9.warn("screenshare stream %s not found", screenShareStreamId);
1953
1970
  return;
1954
1971
  }
1955
1972
  const hasAudioTrack = screenshareStream.getAudioTracks().length > 0;
@@ -2026,7 +2043,7 @@ class P2pRtcManager {
2026
2043
  });
2027
2044
  }
2028
2045
  catch (error) {
2029
- logger$8.error("Error during setting jitter buffer target:", error);
2046
+ logger$9.error("Error during setting jitter buffer target:", error);
2030
2047
  }
2031
2048
  }
2032
2049
  _emitServerEvent(eventName, data, callback) {
@@ -2289,7 +2306,7 @@ class P2pRtcManager {
2289
2306
  _cleanup(peerConnectionId) {
2290
2307
  const session = this._getSession(peerConnectionId);
2291
2308
  if (!session) {
2292
- logger$8.warn("No RTCPeerConnection in RTCManager.disconnect()", peerConnectionId);
2309
+ logger$9.warn("No RTCPeerConnection in RTCManager.disconnect()", peerConnectionId);
2293
2310
  return;
2294
2311
  }
2295
2312
  session.close();
@@ -2314,17 +2331,17 @@ class P2pRtcManager {
2314
2331
  const promises = [];
2315
2332
  this._forEachPeerConnection((session) => {
2316
2333
  if (!session.hasConnectedPeerConnection()) {
2317
- logger$8.info("Session doesn't have a connected PeerConnection, adding pending action!");
2334
+ logger$9.info("Session doesn't have a connected PeerConnection, adding pending action!");
2318
2335
  const pendingActions = this._pendingActionsForConnectedPeerConnections;
2319
2336
  if (!pendingActions) {
2320
- logger$8.warn(`No pending action is created to replace track, because the pending actions array is null`);
2337
+ logger$9.warn(`No pending action is created to replace track, because the pending actions array is null`);
2321
2338
  return;
2322
2339
  }
2323
2340
  const promise = new Promise((resolve, reject) => {
2324
2341
  const action = () => {
2325
2342
  const replacedTrackPromise = session.replaceTrack(oldTrack, newTrack);
2326
2343
  if (!replacedTrackPromise) {
2327
- logger$8.error("replaceTrack returned false!");
2344
+ logger$9.error("replaceTrack returned false!");
2328
2345
  reject(`ReplaceTrack returned false`);
2329
2346
  return;
2330
2347
  }
@@ -2337,7 +2354,7 @@ class P2pRtcManager {
2337
2354
  }
2338
2355
  const replacedTrackResult = session.replaceTrack(oldTrack, newTrack);
2339
2356
  if (!replacedTrackResult) {
2340
- logger$8.error("replaceTrack returned false!");
2357
+ logger$9.error("replaceTrack returned false!");
2341
2358
  return;
2342
2359
  }
2343
2360
  promises.push(replacedTrackResult);
@@ -2398,7 +2415,7 @@ class P2pRtcManager {
2398
2415
  let session = this._getSession(clientId);
2399
2416
  let initialBandwidth = (session && session.bandwidth) || 0;
2400
2417
  if (session) {
2401
- logger$8.warn("Replacing peer session", clientId);
2418
+ logger$9.warn("Replacing peer session", clientId);
2402
2419
  this._cleanup(clientId);
2403
2420
  }
2404
2421
  else {
@@ -2473,12 +2490,12 @@ class P2pRtcManager {
2473
2490
  });
2474
2491
  }
2475
2492
  catch (error) {
2476
- logger$8.error("Error during setting setCodecPreferences:", error);
2493
+ logger$9.error("Error during setting setCodecPreferences:", error);
2477
2494
  }
2478
2495
  }
2479
2496
  _negotiatePeerConnection(clientId, session, constraints) {
2480
2497
  if (!session) {
2481
- logger$8.warn("No RTCPeerConnection in negotiatePeerConnection()", clientId);
2498
+ logger$9.warn("No RTCPeerConnection in negotiatePeerConnection()", clientId);
2482
2499
  return;
2483
2500
  }
2484
2501
  const pc = session.pc;
@@ -2504,7 +2521,7 @@ class P2pRtcManager {
2504
2521
  offer.sdp = cleanSdp(offer.sdp);
2505
2522
  pc.setLocalDescription(offer)
2506
2523
  .catch((e) => {
2507
- logger$8.warn("RTCPeerConnection.setLocalDescription() failed with local offer", e);
2524
+ logger$9.warn("RTCPeerConnection.setLocalDescription() failed with local offer", e);
2508
2525
  this._emit(rtcManagerEvents.PC_SLD_FAILURE, e);
2509
2526
  throw e;
2510
2527
  })
@@ -2516,7 +2533,7 @@ class P2pRtcManager {
2516
2533
  });
2517
2534
  })
2518
2535
  .catch((e) => {
2519
- logger$8.warn("RTCPeerConnection.createOffer() failed to create local offer", e);
2536
+ logger$9.warn("RTCPeerConnection.createOffer() failed to create local offer", e);
2520
2537
  });
2521
2538
  }
2522
2539
  _withForcedRenegotiation(session, action) {
@@ -2647,7 +2664,7 @@ class P2pRtcManager {
2647
2664
  }
2648
2665
  }
2649
2666
  catch (error) {
2650
- logger$8.info("Error during parsing candidates! Error: ", { error });
2667
+ logger$9.info("Error during parsing candidates! Error: ", { error });
2651
2668
  }
2652
2669
  break;
2653
2670
  case "srflx":
@@ -2703,7 +2720,7 @@ class P2pRtcManager {
2703
2720
  }
2704
2721
  let initialBandwidth = (session && session.bandwidth) || 0;
2705
2722
  if (session) {
2706
- logger$8.warn("Replacing peer session", clientId);
2723
+ logger$9.warn("Replacing peer session", clientId);
2707
2724
  this._cleanup(clientId);
2708
2725
  }
2709
2726
  else {
@@ -2912,7 +2929,7 @@ class SfuV2Parser {
2912
2929
  }
2913
2930
  }
2914
2931
 
2915
- const logger$7 = new Logger();
2932
+ const logger$8 = new Logger();
2916
2933
  class VegaConnection extends EventEmitter.EventEmitter {
2917
2934
  constructor(wsUrl, protocol = "whereby-sfu#v4") {
2918
2935
  super();
@@ -2945,12 +2962,12 @@ class VegaConnection extends EventEmitter.EventEmitter {
2945
2962
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
2946
2963
  }
2947
2964
  _onOpen() {
2948
- logger$7.info("Connected");
2965
+ logger$8.info("Connected");
2949
2966
  this.emit("open");
2950
2967
  }
2951
2968
  _onMessage(event) {
2952
2969
  const socketMessage = SfuV2Parser.parse(event.data);
2953
- logger$7.info("Received message", socketMessage);
2970
+ logger$8.info("Received message", socketMessage);
2954
2971
  if (socketMessage === null || socketMessage === void 0 ? void 0 : socketMessage.response) {
2955
2972
  this._handleResponse(socketMessage);
2956
2973
  }
@@ -2959,11 +2976,11 @@ class VegaConnection extends EventEmitter.EventEmitter {
2959
2976
  }
2960
2977
  }
2961
2978
  _onClose() {
2962
- logger$7.info("Disconnected");
2979
+ logger$8.info("Disconnected");
2963
2980
  this._tearDown();
2964
2981
  }
2965
2982
  _onError(error) {
2966
- logger$7.info("Error", error);
2983
+ logger$8.info("Error", error);
2967
2984
  }
2968
2985
  _handleResponse(socketMessage) {
2969
2986
  const sent = this.sents.get(socketMessage.id);
@@ -3129,7 +3146,7 @@ const defaultParams = {
3129
3146
  scoreFormula: "300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",
3130
3147
  outFormula: "score",
3131
3148
  };
3132
- const logger$6 = new Logger();
3149
+ const logger$7 = new Logger();
3133
3150
  function createMicAnalyser({ micTrack, params, onScoreUpdated, }) {
3134
3151
  const audioCtx = new AudioContext();
3135
3152
  let analyser = null;
@@ -3151,7 +3168,7 @@ function createMicAnalyser({ micTrack, params, onScoreUpdated, }) {
3151
3168
  lastTrackWasOurs = true;
3152
3169
  }
3153
3170
  catch (ex) {
3154
- logger$6.warn("unable to fetch new track for colocation speaker analysis, using current", ex);
3171
+ logger$7.warn("unable to fetch new track for colocation speaker analysis, using current", ex);
3155
3172
  }
3156
3173
  }
3157
3174
  lastTrack = track;
@@ -3238,7 +3255,7 @@ function createMicAnalyser({ micTrack, params, onScoreUpdated, }) {
3238
3255
  };
3239
3256
  }
3240
3257
 
3241
- const logger$5 = new Logger();
3258
+ const logger$6 = new Logger();
3242
3259
  const MEDIA_QUALITY = Object.freeze({
3243
3260
  ok: "ok",
3244
3261
  warning: "warning",
@@ -3308,7 +3325,7 @@ class VegaMediaQualityMonitor extends EventEmitter {
3308
3325
  }
3309
3326
  addProducer(clientId, producerId) {
3310
3327
  if (!clientId || !producerId || !(typeof clientId === "string" && typeof producerId === "string")) {
3311
- logger$5.warn("Missing clientId or producerId");
3328
+ logger$6.warn("Missing clientId or producerId");
3312
3329
  return;
3313
3330
  }
3314
3331
  if (!this._producers[clientId]) {
@@ -3324,7 +3341,7 @@ class VegaMediaQualityMonitor extends EventEmitter {
3324
3341
  }
3325
3342
  addConsumer(clientId, consumerId) {
3326
3343
  if (!clientId || !consumerId) {
3327
- logger$5.warn("Missing clientId or consumerId");
3344
+ logger$6.warn("Missing clientId or consumerId");
3328
3345
  return;
3329
3346
  }
3330
3347
  if (!this._producers[clientId]) {
@@ -3342,14 +3359,14 @@ class VegaMediaQualityMonitor extends EventEmitter {
3342
3359
  if (!Array.isArray(score) ||
3343
3360
  score.length === 0 ||
3344
3361
  score.some((s) => !s || !s.hasOwnProperty("score") || typeof s.score !== "number" || isNaN(s.score))) {
3345
- logger$5.warn("Unexpected producer score format");
3362
+ logger$6.warn("Unexpected producer score format");
3346
3363
  return;
3347
3364
  }
3348
3365
  this._producers[clientId][producerId] = { kind, score: this._calcAvgProducerScore(score.map((s) => s.score)) };
3349
3366
  }
3350
3367
  addConsumerScore(clientId, consumerId, kind, score) {
3351
3368
  if (!score || !score.hasOwnProperty("producerScores") || !Array.isArray(score.producerScores)) {
3352
- logger$5.warn("Unexpected consumer score format");
3369
+ logger$6.warn("Unexpected consumer score format");
3353
3370
  return;
3354
3371
  }
3355
3372
  this._producers[clientId][consumerId] = { kind, score: this._calcAvgProducerScore(score.producerScores) };
@@ -3386,7 +3403,7 @@ class VegaMediaQualityMonitor extends EventEmitter {
3386
3403
  }
3387
3404
  }
3388
3405
  catch (error) {
3389
- logger$5.error(error);
3406
+ logger$6.error(error);
3390
3407
  return 0;
3391
3408
  }
3392
3409
  }
@@ -3495,11 +3512,704 @@ const modifyMediaCapabilities = (routerRtpCapabilities, features) => {
3495
3512
  }
3496
3513
  };
3497
3514
 
3498
- const getHandler = () => {
3499
- let handlerName = mediasoupClient.detectDevice() || (/applecoremedia|applewebkit|safari/i.test(navigator.userAgent) ? "Safari12" : undefined);
3515
+ const logger$5 = new Logger$1.Logger("Safari17");
3516
+ const NAME = "Safari17";
3517
+ const SCTP_NUM_STREAMS = { OS: 1024, MIS: 1024 };
3518
+ class Safari17 extends HandlerInterface.HandlerInterface {
3519
+ static createFactory() {
3520
+ return () => new Safari17();
3521
+ }
3522
+ constructor() {
3523
+ super();
3524
+ this._closed = false;
3525
+ this._mapMidTransceiver = new Map();
3526
+ this._sendStream = new MediaStream();
3527
+ this._hasDataChannelMediaSection = false;
3528
+ this._nextSendSctpStreamId = 0;
3529
+ this._transportReady = false;
3530
+ }
3531
+ get name() {
3532
+ return NAME;
3533
+ }
3534
+ close() {
3535
+ logger$5.debug("close()");
3536
+ if (this._closed) {
3537
+ return;
3538
+ }
3539
+ this._closed = true;
3540
+ if (this._pc) {
3541
+ try {
3542
+ this._pc.close();
3543
+ }
3544
+ catch (error) { }
3545
+ }
3546
+ this.emit("@close");
3547
+ }
3548
+ getNativeRtpCapabilities() {
3549
+ return __awaiter(this, void 0, void 0, function* () {
3550
+ logger$5.debug("getNativeRtpCapabilities()");
3551
+ const pc = new RTCPeerConnection({
3552
+ iceServers: [],
3553
+ iceTransportPolicy: "all",
3554
+ bundlePolicy: "max-bundle",
3555
+ rtcpMuxPolicy: "require",
3556
+ });
3557
+ try {
3558
+ pc.addTransceiver("audio");
3559
+ pc.addTransceiver("video");
3560
+ const offer = yield pc.createOffer();
3561
+ try {
3562
+ pc.close();
3563
+ }
3564
+ catch (error) { }
3565
+ const sdpObject = sdpTransform__namespace.parse(offer.sdp);
3566
+ const nativeRtpCapabilities = sdpCommonUtils__namespace.extractRtpCapabilities({
3567
+ sdpObject,
3568
+ });
3569
+ ortcUtils__namespace.addNackSuppportForOpus(nativeRtpCapabilities);
3570
+ return nativeRtpCapabilities;
3571
+ }
3572
+ catch (error) {
3573
+ try {
3574
+ pc.close();
3575
+ }
3576
+ catch (error2) { }
3577
+ throw error;
3578
+ }
3579
+ });
3580
+ }
3581
+ getNativeSctpCapabilities() {
3582
+ return __awaiter(this, void 0, void 0, function* () {
3583
+ logger$5.debug("getNativeSctpCapabilities()");
3584
+ return {
3585
+ numStreams: SCTP_NUM_STREAMS,
3586
+ };
3587
+ });
3588
+ }
3589
+ run({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, extendedRtpCapabilities, }) {
3590
+ this.assertNotClosed();
3591
+ logger$5.debug("run()");
3592
+ this._direction = direction;
3593
+ this._remoteSdp = new RemoteSdp.RemoteSdp({
3594
+ iceParameters,
3595
+ iceCandidates,
3596
+ dtlsParameters,
3597
+ sctpParameters,
3598
+ });
3599
+ this._sendingRtpParametersByKind = {
3600
+ audio: ortc__namespace.getSendingRtpParameters("audio", extendedRtpCapabilities),
3601
+ video: ortc__namespace.getSendingRtpParameters("video", extendedRtpCapabilities),
3602
+ };
3603
+ this._sendingRemoteRtpParametersByKind = {
3604
+ audio: ortc__namespace.getSendingRemoteRtpParameters("audio", extendedRtpCapabilities),
3605
+ video: ortc__namespace.getSendingRemoteRtpParameters("video", extendedRtpCapabilities),
3606
+ };
3607
+ if (dtlsParameters.role && dtlsParameters.role !== "auto") {
3608
+ this._forcedLocalDtlsRole = dtlsParameters.role === "server" ? "client" : "server";
3609
+ }
3610
+ this._pc = new RTCPeerConnection(Object.assign({ iceServers: iceServers !== null && iceServers !== void 0 ? iceServers : [], iceTransportPolicy: iceTransportPolicy !== null && iceTransportPolicy !== void 0 ? iceTransportPolicy : "all", bundlePolicy: "max-bundle", rtcpMuxPolicy: "require" }, additionalSettings), proprietaryConstraints);
3611
+ this._pc.addEventListener("icegatheringstatechange", () => {
3612
+ this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
3613
+ });
3614
+ if (this._pc.connectionState) {
3615
+ this._pc.addEventListener("connectionstatechange", () => {
3616
+ this.emit("@connectionstatechange", this._pc.connectionState);
3617
+ });
3618
+ }
3619
+ else {
3620
+ this._pc.addEventListener("iceconnectionstatechange", () => {
3621
+ logger$5.warn("run() | pc.connectionState not supported, using pc.iceConnectionState");
3622
+ switch (this._pc.iceConnectionState) {
3623
+ case "checking": {
3624
+ this.emit("@connectionstatechange", "connecting");
3625
+ break;
3626
+ }
3627
+ case "connected":
3628
+ case "completed": {
3629
+ this.emit("@connectionstatechange", "connected");
3630
+ break;
3631
+ }
3632
+ case "failed": {
3633
+ this.emit("@connectionstatechange", "failed");
3634
+ break;
3635
+ }
3636
+ case "disconnected": {
3637
+ this.emit("@connectionstatechange", "disconnected");
3638
+ break;
3639
+ }
3640
+ case "closed": {
3641
+ this.emit("@connectionstatechange", "closed");
3642
+ break;
3643
+ }
3644
+ }
3645
+ });
3646
+ }
3647
+ }
3648
+ updateIceServers(iceServers) {
3649
+ return __awaiter(this, void 0, void 0, function* () {
3650
+ this.assertNotClosed();
3651
+ logger$5.debug("updateIceServers()");
3652
+ const configuration = this._pc.getConfiguration();
3653
+ configuration.iceServers = iceServers;
3654
+ this._pc.setConfiguration(configuration);
3655
+ });
3656
+ }
3657
+ restartIce(iceParameters) {
3658
+ return __awaiter(this, void 0, void 0, function* () {
3659
+ this.assertNotClosed();
3660
+ logger$5.debug("restartIce()");
3661
+ this._remoteSdp.updateIceParameters(iceParameters);
3662
+ if (!this._transportReady) {
3663
+ return;
3664
+ }
3665
+ if (this._direction === "send") {
3666
+ const offer = yield this._pc.createOffer({ iceRestart: true });
3667
+ logger$5.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]", offer);
3668
+ yield this._pc.setLocalDescription(offer);
3669
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3670
+ logger$5.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]", answer);
3671
+ yield this._pc.setRemoteDescription(answer);
3672
+ }
3673
+ else {
3674
+ const offer = { type: "offer", sdp: this._remoteSdp.getSdp() };
3675
+ logger$5.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]", offer);
3676
+ yield this._pc.setRemoteDescription(offer);
3677
+ const answer = yield this._pc.createAnswer();
3678
+ logger$5.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]", answer);
3679
+ yield this._pc.setLocalDescription(answer);
3680
+ }
3681
+ });
3682
+ }
3683
+ getTransportStats() {
3684
+ return __awaiter(this, void 0, void 0, function* () {
3685
+ this.assertNotClosed();
3686
+ return this._pc.getStats();
3687
+ });
3688
+ }
3689
+ send({ track, encodings, codecOptions, codec, onRtpSender }) {
3690
+ var _a;
3691
+ return __awaiter(this, void 0, void 0, function* () {
3692
+ this.assertNotClosed();
3693
+ this.assertSendDirection();
3694
+ logger$5.debug("send() [kind:%s, track.id:%s]", track.kind, track.id);
3695
+ const sendingRtpParameters = utils__namespace.clone(this._sendingRtpParametersByKind[track.kind]);
3696
+ sendingRtpParameters.codecs = ortc__namespace.reduceCodecs(sendingRtpParameters.codecs, codec);
3697
+ if (encodings && encodings.length > 1) {
3698
+ let maxTemporalLayers = 1;
3699
+ for (const encoding of encodings) {
3700
+ const temporalLayers = encoding.scalabilityMode
3701
+ ? scalabilityModes.parse(encoding.scalabilityMode).temporalLayers
3702
+ : 3;
3703
+ if (temporalLayers > maxTemporalLayers) {
3704
+ maxTemporalLayers = temporalLayers;
3705
+ }
3706
+ }
3707
+ encodings.forEach((encoding, idx) => {
3708
+ encoding.rid = `r${idx}`;
3709
+ encoding.scalabilityMode = `L1T${maxTemporalLayers}`;
3710
+ });
3711
+ }
3712
+ const sendingRemoteRtpParameters = utils__namespace.clone(this._sendingRemoteRtpParametersByKind[track.kind]);
3713
+ sendingRemoteRtpParameters.codecs = ortc__namespace.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
3714
+ const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
3715
+ const transceiver = this._pc.addTransceiver(track, {
3716
+ direction: "sendonly",
3717
+ streams: [this._sendStream],
3718
+ sendEncodings: encodings,
3719
+ });
3720
+ if (onRtpSender) {
3721
+ onRtpSender(transceiver.sender);
3722
+ }
3723
+ const offer = yield this._pc.createOffer();
3724
+ let localSdpObject = sdpTransform__namespace.parse(offer.sdp);
3725
+ if (!this._transportReady) {
3726
+ yield this.setupTransport({
3727
+ localDtlsRole: (_a = this._forcedLocalDtlsRole) !== null && _a !== void 0 ? _a : "client",
3728
+ localSdpObject,
3729
+ });
3730
+ }
3731
+ const layers = scalabilityModes.parse((encodings !== null && encodings !== void 0 ? encodings : [{}])[0].scalabilityMode);
3732
+ logger$5.debug("send() | calling pc.setLocalDescription() [offer:%o]", offer);
3733
+ yield this._pc.setLocalDescription(offer);
3734
+ const localId = transceiver.mid;
3735
+ sendingRtpParameters.mid = localId;
3736
+ localSdpObject = sdpTransform__namespace.parse(this._pc.localDescription.sdp);
3737
+ const offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
3738
+ sendingRtpParameters.rtcp.cname = sdpCommonUtils__namespace.getCname({
3739
+ offerMediaObject,
3740
+ });
3741
+ if (!encodings) {
3742
+ sendingRtpParameters.encodings = sdpUnifiedPlanUtils__namespace.getRtpEncodings({
3743
+ offerMediaObject,
3744
+ });
3745
+ }
3746
+ else if (encodings.length === 1) {
3747
+ const newEncodings = sdpUnifiedPlanUtils__namespace.getRtpEncodings({
3748
+ offerMediaObject,
3749
+ });
3750
+ Object.assign(newEncodings[0], encodings[0]);
3751
+ sendingRtpParameters.encodings = newEncodings;
3752
+ }
3753
+ else {
3754
+ sendingRtpParameters.encodings = encodings;
3755
+ }
3756
+ if (sendingRtpParameters.encodings.length > 1 &&
3757
+ (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp8" ||
3758
+ sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/h264")) {
3759
+ for (const encoding of sendingRtpParameters.encodings) {
3760
+ if (encoding.scalabilityMode) {
3761
+ encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
3762
+ }
3763
+ else {
3764
+ encoding.scalabilityMode = "L1T3";
3765
+ }
3766
+ }
3767
+ }
3768
+ this._remoteSdp.send({
3769
+ offerMediaObject,
3770
+ reuseMid: mediaSectionIdx.reuseMid,
3771
+ offerRtpParameters: sendingRtpParameters,
3772
+ answerRtpParameters: sendingRemoteRtpParameters,
3773
+ codecOptions,
3774
+ });
3775
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3776
+ logger$5.debug("send() | calling pc.setRemoteDescription() [answer:%o]", answer);
3777
+ yield this._pc.setRemoteDescription(answer);
3778
+ this._mapMidTransceiver.set(localId, transceiver);
3779
+ return {
3780
+ localId,
3781
+ rtpParameters: sendingRtpParameters,
3782
+ rtpSender: transceiver.sender,
3783
+ };
3784
+ });
3785
+ }
3786
+ stopSending(localId) {
3787
+ return __awaiter(this, void 0, void 0, function* () {
3788
+ this.assertSendDirection();
3789
+ if (this._closed) {
3790
+ return;
3791
+ }
3792
+ logger$5.debug("stopSending() [localId:%s]", localId);
3793
+ const transceiver = this._mapMidTransceiver.get(localId);
3794
+ if (!transceiver) {
3795
+ throw new Error("associated RTCRtpTransceiver not found");
3796
+ }
3797
+ void transceiver.sender.replaceTrack(null);
3798
+ this._pc.removeTrack(transceiver.sender);
3799
+ const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
3800
+ if (mediaSectionClosed) {
3801
+ try {
3802
+ transceiver.stop();
3803
+ }
3804
+ catch (error) { }
3805
+ }
3806
+ const offer = yield this._pc.createOffer();
3807
+ logger$5.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]", offer);
3808
+ yield this._pc.setLocalDescription(offer);
3809
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3810
+ logger$5.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
3811
+ yield this._pc.setRemoteDescription(answer);
3812
+ this._mapMidTransceiver.delete(localId);
3813
+ });
3814
+ }
3815
+ pauseSending(localId) {
3816
+ return __awaiter(this, void 0, void 0, function* () {
3817
+ this.assertNotClosed();
3818
+ this.assertSendDirection();
3819
+ logger$5.debug("pauseSending() [localId:%s]", localId);
3820
+ const transceiver = this._mapMidTransceiver.get(localId);
3821
+ if (!transceiver) {
3822
+ throw new Error("associated RTCRtpTransceiver not found");
3823
+ }
3824
+ transceiver.direction = "inactive";
3825
+ this._remoteSdp.pauseMediaSection(localId);
3826
+ const offer = yield this._pc.createOffer();
3827
+ logger$5.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]", offer);
3828
+ yield this._pc.setLocalDescription(offer);
3829
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3830
+ logger$5.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
3831
+ yield this._pc.setRemoteDescription(answer);
3832
+ });
3833
+ }
3834
+ resumeSending(localId) {
3835
+ return __awaiter(this, void 0, void 0, function* () {
3836
+ this.assertNotClosed();
3837
+ this.assertSendDirection();
3838
+ logger$5.debug("resumeSending() [localId:%s]", localId);
3839
+ const transceiver = this._mapMidTransceiver.get(localId);
3840
+ if (!transceiver) {
3841
+ throw new Error("associated RTCRtpTransceiver not found");
3842
+ }
3843
+ transceiver.direction = "sendonly";
3844
+ this._remoteSdp.resumeSendingMediaSection(localId);
3845
+ const offer = yield this._pc.createOffer();
3846
+ logger$5.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]", offer);
3847
+ yield this._pc.setLocalDescription(offer);
3848
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3849
+ logger$5.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
3850
+ yield this._pc.setRemoteDescription(answer);
3851
+ });
3852
+ }
3853
+ replaceTrack(localId, track) {
3854
+ return __awaiter(this, void 0, void 0, function* () {
3855
+ this.assertNotClosed();
3856
+ this.assertSendDirection();
3857
+ if (track) {
3858
+ logger$5.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
3859
+ }
3860
+ else {
3861
+ logger$5.debug("replaceTrack() [localId:%s, no track]", localId);
3862
+ }
3863
+ const transceiver = this._mapMidTransceiver.get(localId);
3864
+ if (!transceiver) {
3865
+ throw new Error("associated RTCRtpTransceiver not found");
3866
+ }
3867
+ yield transceiver.sender.replaceTrack(track);
3868
+ });
3869
+ }
3870
+ setMaxSpatialLayer(localId, spatialLayer) {
3871
+ return __awaiter(this, void 0, void 0, function* () {
3872
+ this.assertNotClosed();
3873
+ this.assertSendDirection();
3874
+ logger$5.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
3875
+ const transceiver = this._mapMidTransceiver.get(localId);
3876
+ if (!transceiver) {
3877
+ throw new Error("associated RTCRtpTransceiver not found");
3878
+ }
3879
+ const parameters = transceiver.sender.getParameters();
3880
+ parameters.encodings.forEach((encoding, idx) => {
3881
+ if (idx <= spatialLayer) {
3882
+ encoding.active = true;
3883
+ }
3884
+ else {
3885
+ encoding.active = false;
3886
+ }
3887
+ });
3888
+ yield transceiver.sender.setParameters(parameters);
3889
+ this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
3890
+ const offer = yield this._pc.createOffer();
3891
+ logger$5.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]", offer);
3892
+ yield this._pc.setLocalDescription(offer);
3893
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3894
+ logger$5.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]", answer);
3895
+ yield this._pc.setRemoteDescription(answer);
3896
+ });
3897
+ }
3898
+ setRtpEncodingParameters(localId, params) {
3899
+ return __awaiter(this, void 0, void 0, function* () {
3900
+ this.assertNotClosed();
3901
+ this.assertSendDirection();
3902
+ logger$5.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
3903
+ const transceiver = this._mapMidTransceiver.get(localId);
3904
+ if (!transceiver) {
3905
+ throw new Error("associated RTCRtpTransceiver not found");
3906
+ }
3907
+ const parameters = transceiver.sender.getParameters();
3908
+ parameters.encodings.forEach((encoding, idx) => {
3909
+ parameters.encodings[idx] = Object.assign(Object.assign({}, encoding), params);
3910
+ });
3911
+ yield transceiver.sender.setParameters(parameters);
3912
+ this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
3913
+ const offer = yield this._pc.createOffer();
3914
+ logger$5.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]", offer);
3915
+ yield this._pc.setLocalDescription(offer);
3916
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3917
+ logger$5.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]", answer);
3918
+ yield this._pc.setRemoteDescription(answer);
3919
+ });
3920
+ }
3921
+ getSenderStats(localId) {
3922
+ return __awaiter(this, void 0, void 0, function* () {
3923
+ this.assertNotClosed();
3924
+ this.assertSendDirection();
3925
+ const transceiver = this._mapMidTransceiver.get(localId);
3926
+ if (!transceiver) {
3927
+ throw new Error("associated RTCRtpTransceiver not found");
3928
+ }
3929
+ return transceiver.sender.getStats();
3930
+ });
3931
+ }
3932
+ sendDataChannel({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol, }) {
3933
+ var _a;
3934
+ return __awaiter(this, void 0, void 0, function* () {
3935
+ this.assertNotClosed();
3936
+ this.assertSendDirection();
3937
+ const options = {
3938
+ negotiated: true,
3939
+ id: this._nextSendSctpStreamId,
3940
+ ordered,
3941
+ maxPacketLifeTime,
3942
+ maxRetransmits,
3943
+ protocol,
3944
+ };
3945
+ logger$5.debug("sendDataChannel() [options:%o]", options);
3946
+ const dataChannel = this._pc.createDataChannel(label, options);
3947
+ this._nextSendSctpStreamId = ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
3948
+ if (!this._hasDataChannelMediaSection) {
3949
+ const offer = yield this._pc.createOffer();
3950
+ const localSdpObject = sdpTransform__namespace.parse(offer.sdp);
3951
+ const offerMediaObject = localSdpObject.media.find((m) => m.type === "application");
3952
+ if (!this._transportReady) {
3953
+ yield this.setupTransport({
3954
+ localDtlsRole: (_a = this._forcedLocalDtlsRole) !== null && _a !== void 0 ? _a : "client",
3955
+ localSdpObject,
3956
+ });
3957
+ }
3958
+ logger$5.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]", offer);
3959
+ yield this._pc.setLocalDescription(offer);
3960
+ this._remoteSdp.sendSctpAssociation({ offerMediaObject });
3961
+ const answer = { type: "answer", sdp: this._remoteSdp.getSdp() };
3962
+ logger$5.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
3963
+ yield this._pc.setRemoteDescription(answer);
3964
+ this._hasDataChannelMediaSection = true;
3965
+ }
3966
+ const sctpStreamParameters = {
3967
+ streamId: options.id,
3968
+ ordered: options.ordered,
3969
+ maxPacketLifeTime: options.maxPacketLifeTime,
3970
+ maxRetransmits: options.maxRetransmits,
3971
+ };
3972
+ return { dataChannel, sctpStreamParameters };
3973
+ });
3974
+ }
3975
+ receive(optionsList) {
3976
+ var _a, _b;
3977
+ return __awaiter(this, void 0, void 0, function* () {
3978
+ this.assertNotClosed();
3979
+ this.assertRecvDirection();
3980
+ const results = [];
3981
+ const mapLocalId = new Map();
3982
+ for (const options of optionsList) {
3983
+ const { trackId, kind, rtpParameters, streamId } = options;
3984
+ logger$5.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
3985
+ const localId = (_a = rtpParameters.mid) !== null && _a !== void 0 ? _a : String(this._mapMidTransceiver.size);
3986
+ mapLocalId.set(trackId, localId);
3987
+ this._remoteSdp.receive({
3988
+ mid: localId,
3989
+ kind,
3990
+ offerRtpParameters: rtpParameters,
3991
+ streamId: streamId !== null && streamId !== void 0 ? streamId : rtpParameters.rtcp.cname,
3992
+ trackId,
3993
+ });
3994
+ }
3995
+ const offer = { type: "offer", sdp: this._remoteSdp.getSdp() };
3996
+ logger$5.debug("receive() | calling pc.setRemoteDescription() [offer:%o]", offer);
3997
+ yield this._pc.setRemoteDescription(offer);
3998
+ for (const options of optionsList) {
3999
+ const { trackId, onRtpReceiver } = options;
4000
+ if (onRtpReceiver) {
4001
+ const localId = mapLocalId.get(trackId);
4002
+ const transceiver = this._pc.getTransceivers().find((t) => t.mid === localId);
4003
+ if (!transceiver) {
4004
+ throw new Error("transceiver not found");
4005
+ }
4006
+ onRtpReceiver(transceiver.receiver);
4007
+ }
4008
+ }
4009
+ let answer = yield this._pc.createAnswer();
4010
+ const localSdpObject = sdpTransform__namespace.parse(answer.sdp);
4011
+ for (const options of optionsList) {
4012
+ const { trackId, rtpParameters } = options;
4013
+ const localId = mapLocalId.get(trackId);
4014
+ const answerMediaObject = localSdpObject.media.find((m) => String(m.mid) === localId);
4015
+ sdpCommonUtils__namespace.applyCodecParameters({
4016
+ offerRtpParameters: rtpParameters,
4017
+ answerMediaObject,
4018
+ });
4019
+ }
4020
+ answer = { type: "answer", sdp: sdpTransform__namespace.write(localSdpObject) };
4021
+ if (!this._transportReady) {
4022
+ yield this.setupTransport({
4023
+ localDtlsRole: (_b = this._forcedLocalDtlsRole) !== null && _b !== void 0 ? _b : "client",
4024
+ localSdpObject,
4025
+ });
4026
+ }
4027
+ logger$5.debug("receive() | calling pc.setLocalDescription() [answer:%o]", answer);
4028
+ yield this._pc.setLocalDescription(answer);
4029
+ for (const options of optionsList) {
4030
+ const { trackId } = options;
4031
+ const localId = mapLocalId.get(trackId);
4032
+ const transceiver = this._pc.getTransceivers().find((t) => t.mid === localId);
4033
+ if (!transceiver) {
4034
+ throw new Error("new RTCRtpTransceiver not found");
4035
+ }
4036
+ this._mapMidTransceiver.set(localId, transceiver);
4037
+ results.push({
4038
+ localId,
4039
+ track: transceiver.receiver.track,
4040
+ rtpReceiver: transceiver.receiver,
4041
+ });
4042
+ }
4043
+ return results;
4044
+ });
4045
+ }
4046
+ stopReceiving(localIds) {
4047
+ return __awaiter(this, void 0, void 0, function* () {
4048
+ this.assertRecvDirection();
4049
+ if (this._closed) {
4050
+ return;
4051
+ }
4052
+ for (const localId of localIds) {
4053
+ logger$5.debug("stopReceiving() [localId:%s]", localId);
4054
+ const transceiver = this._mapMidTransceiver.get(localId);
4055
+ if (!transceiver) {
4056
+ throw new Error("associated RTCRtpTransceiver not found");
4057
+ }
4058
+ this._remoteSdp.closeMediaSection(transceiver.mid);
4059
+ }
4060
+ const offer = { type: "offer", sdp: this._remoteSdp.getSdp() };
4061
+ logger$5.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
4062
+ yield this._pc.setRemoteDescription(offer);
4063
+ const answer = yield this._pc.createAnswer();
4064
+ logger$5.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
4065
+ yield this._pc.setLocalDescription(answer);
4066
+ for (const localId of localIds) {
4067
+ this._mapMidTransceiver.delete(localId);
4068
+ }
4069
+ });
4070
+ }
4071
+ pauseReceiving(localIds) {
4072
+ return __awaiter(this, void 0, void 0, function* () {
4073
+ this.assertNotClosed();
4074
+ this.assertRecvDirection();
4075
+ for (const localId of localIds) {
4076
+ logger$5.debug("pauseReceiving() [localId:%s]", localId);
4077
+ const transceiver = this._mapMidTransceiver.get(localId);
4078
+ if (!transceiver) {
4079
+ throw new Error("associated RTCRtpTransceiver not found");
4080
+ }
4081
+ transceiver.direction = "inactive";
4082
+ this._remoteSdp.pauseMediaSection(localId);
4083
+ }
4084
+ const offer = { type: "offer", sdp: this._remoteSdp.getSdp() };
4085
+ logger$5.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
4086
+ yield this._pc.setRemoteDescription(offer);
4087
+ const answer = yield this._pc.createAnswer();
4088
+ logger$5.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
4089
+ yield this._pc.setLocalDescription(answer);
4090
+ });
4091
+ }
4092
+ resumeReceiving(localIds) {
4093
+ return __awaiter(this, void 0, void 0, function* () {
4094
+ this.assertNotClosed();
4095
+ this.assertRecvDirection();
4096
+ for (const localId of localIds) {
4097
+ logger$5.debug("resumeReceiving() [localId:%s]", localId);
4098
+ const transceiver = this._mapMidTransceiver.get(localId);
4099
+ if (!transceiver) {
4100
+ throw new Error("associated RTCRtpTransceiver not found");
4101
+ }
4102
+ transceiver.direction = "recvonly";
4103
+ this._remoteSdp.resumeReceivingMediaSection(localId);
4104
+ }
4105
+ const offer = { type: "offer", sdp: this._remoteSdp.getSdp() };
4106
+ logger$5.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
4107
+ yield this._pc.setRemoteDescription(offer);
4108
+ const answer = yield this._pc.createAnswer();
4109
+ logger$5.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
4110
+ yield this._pc.setLocalDescription(answer);
4111
+ });
4112
+ }
4113
+ getReceiverStats(localId) {
4114
+ return __awaiter(this, void 0, void 0, function* () {
4115
+ this.assertNotClosed();
4116
+ this.assertRecvDirection();
4117
+ const transceiver = this._mapMidTransceiver.get(localId);
4118
+ if (!transceiver) {
4119
+ throw new Error("associated RTCRtpTransceiver not found");
4120
+ }
4121
+ return transceiver.receiver.getStats();
4122
+ });
4123
+ }
4124
+ receiveDataChannel({ sctpStreamParameters, label, protocol, }) {
4125
+ var _a;
4126
+ return __awaiter(this, void 0, void 0, function* () {
4127
+ this.assertNotClosed();
4128
+ this.assertRecvDirection();
4129
+ const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
4130
+ const options = {
4131
+ negotiated: true,
4132
+ id: streamId,
4133
+ ordered,
4134
+ maxPacketLifeTime,
4135
+ maxRetransmits,
4136
+ protocol,
4137
+ };
4138
+ logger$5.debug("receiveDataChannel() [options:%o]", options);
4139
+ const dataChannel = this._pc.createDataChannel(label, options);
4140
+ if (!this._hasDataChannelMediaSection) {
4141
+ this._remoteSdp.receiveSctpAssociation();
4142
+ const offer = { type: "offer", sdp: this._remoteSdp.getSdp() };
4143
+ logger$5.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]", offer);
4144
+ yield this._pc.setRemoteDescription(offer);
4145
+ const answer = yield this._pc.createAnswer();
4146
+ if (!this._transportReady) {
4147
+ const localSdpObject = sdpTransform__namespace.parse(answer.sdp);
4148
+ yield this.setupTransport({
4149
+ localDtlsRole: (_a = this._forcedLocalDtlsRole) !== null && _a !== void 0 ? _a : "client",
4150
+ localSdpObject,
4151
+ });
4152
+ }
4153
+ logger$5.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
4154
+ yield this._pc.setLocalDescription(answer);
4155
+ this._hasDataChannelMediaSection = true;
4156
+ }
4157
+ return { dataChannel };
4158
+ });
4159
+ }
4160
+ setupTransport({ localDtlsRole, localSdpObject, }) {
4161
+ return __awaiter(this, void 0, void 0, function* () {
4162
+ if (!localSdpObject) {
4163
+ localSdpObject = sdpTransform__namespace.parse(this._pc.localDescription.sdp);
4164
+ }
4165
+ const dtlsParameters = sdpCommonUtils__namespace.extractDtlsParameters({
4166
+ sdpObject: localSdpObject,
4167
+ });
4168
+ dtlsParameters.role = localDtlsRole;
4169
+ this._remoteSdp.updateDtlsRole(localDtlsRole === "client" ? "server" : "client");
4170
+ yield new Promise((resolve, reject) => {
4171
+ this.safeEmit("@connect", { dtlsParameters }, resolve, reject);
4172
+ });
4173
+ this._transportReady = true;
4174
+ });
4175
+ }
4176
+ assertNotClosed() {
4177
+ if (this._closed) {
4178
+ throw new errors.InvalidStateError("method called in a closed handler");
4179
+ }
4180
+ }
4181
+ assertSendDirection() {
4182
+ if (this._direction !== "send") {
4183
+ throw new Error('method can just be called for handlers with "send" direction');
4184
+ }
4185
+ }
4186
+ assertRecvDirection() {
4187
+ if (this._direction !== "recv") {
4188
+ throw new Error('method can just be called for handlers with "recv" direction');
4189
+ }
4190
+ }
4191
+ }
4192
+
4193
+ const getMediasoupDevice = (features) => {
4194
+ var _a;
4195
+ if (features.isNodeSdk) {
4196
+ return new mediasoupClient.Device({ handlerFactory: Safari12_js.Safari12.createFactory() });
4197
+ }
4198
+ let handlerName = mediasoupClient.detectDevice() || (/applecoremedia|applewebkit|safari/i.test(navigator.userAgent) ? "Safari17" : undefined);
4199
+ if (handlerName === "Safari12" && typeof navigator === "object" && typeof navigator.userAgent === "string") {
4200
+ const uaParser = new uaParserJs.UAParser(navigator.userAgent);
4201
+ const browser = uaParser.getBrowser();
4202
+ const browserVersion = parseInt((_a = browser.major) !== null && _a !== void 0 ? _a : "0");
4203
+ if (browserVersion >= 17 && features.safari17HandlerOn) {
4204
+ handlerName = "Safari17";
4205
+ }
4206
+ }
3500
4207
  if (/iphone|ipad/i.test(navigator.userAgent))
3501
- handlerName = "Safari12";
3502
- return handlerName;
4208
+ handlerName = "Safari17";
4209
+ if (handlerName === "Safari17") {
4210
+ return new mediasoupClient.Device({ handlerFactory: Safari17.createFactory() });
4211
+ }
4212
+ return new mediasoupClient.Device({ handlerName });
3503
4213
  };
3504
4214
 
3505
4215
  const maybeTurnOnly = (transportConfig, features) => {
@@ -3564,7 +4274,7 @@ const OUTBOUND_SCREEN_OUTBOUND_STREAM_ID = uuid.v4();
3564
4274
  if (browserName === "chrome")
3565
4275
  window.document.addEventListener("beforeunload", () => (unloading = true));
3566
4276
  class VegaRtcManager {
3567
- constructor({ selfId, room, emitter, serverSocket, webrtcProvider, features, eventClaim, deviceHandlerFactory, }) {
4277
+ constructor({ selfId, room, emitter, serverSocket, webrtcProvider, features, eventClaim, }) {
3568
4278
  const { session, iceServers, sfuServer, mediaserverConfigTtlSeconds } = room;
3569
4279
  this._selfId = selfId;
3570
4280
  this._room = room;
@@ -3577,12 +4287,7 @@ class VegaRtcManager {
3577
4287
  this._vegaConnection = null;
3578
4288
  this._micAnalyser = null;
3579
4289
  this._micAnalyserDebugger = null;
3580
- if (deviceHandlerFactory) {
3581
- this._mediasoupDevice = new mediasoupClient.Device({ handlerFactory: deviceHandlerFactory });
3582
- }
3583
- else {
3584
- this._mediasoupDevice = new mediasoupClient.Device({ handlerName: getHandler() });
3585
- }
4290
+ this._mediasoupDevice = getMediasoupDevice(features);
3586
4291
  this._routerRtpCapabilities = null;
3587
4292
  this._sendTransport = null;
3588
4293
  this._receiveTransport = null;
@@ -3718,6 +4423,7 @@ class VegaRtcManager {
3718
4423
  this._emitToPWA(rtcManagerEvents.SFU_CONNECTION_CLOSED);
3719
4424
  }
3720
4425
  _join() {
4426
+ var _a, _b;
3721
4427
  return __awaiter(this, void 0, void 0, function* () {
3722
4428
  logger$4.info("join()");
3723
4429
  this._emitToPWA(rtcManagerEvents.SFU_CONNECTION_OPEN);
@@ -3726,10 +4432,10 @@ class VegaRtcManager {
3726
4432
  if (!this._routerRtpCapabilities) {
3727
4433
  modifyMediaCapabilities(routerRtpCapabilities, this._features);
3728
4434
  this._routerRtpCapabilities = routerRtpCapabilities;
3729
- yield this._mediasoupDevice.load({ routerRtpCapabilities });
4435
+ yield ((_a = this._mediasoupDevice) === null || _a === void 0 ? void 0 : _a.load({ routerRtpCapabilities }));
3730
4436
  }
3731
4437
  this._vegaConnection.message("setCapabilities", {
3732
- rtpCapabilities: this._mediasoupDevice.rtpCapabilities,
4438
+ rtpCapabilities: (_b = this._mediasoupDevice) === null || _b === void 0 ? void 0 : _b.rtpCapabilities,
3733
4439
  });
3734
4440
  if (this._colocation)
3735
4441
  this._vegaConnection.message("setColocation", { colocation: this._colocation });
@@ -3751,6 +4457,7 @@ class VegaRtcManager {
3751
4457
  });
3752
4458
  }
3753
4459
  _createTransport(send) {
4460
+ var _a;
3754
4461
  return __awaiter(this, void 0, void 0, function* () {
3755
4462
  const creator = send ? "createSendTransport" : "createRecvTransport";
3756
4463
  const transportOptions = yield this._vegaConnection.request("createTransport", {
@@ -3771,7 +4478,7 @@ class VegaRtcManager {
3771
4478
  });
3772
4479
  transportOptions.iceServers = this._iceServers;
3773
4480
  maybeTurnOnly(transportOptions, this._features);
3774
- const transport = this._mediasoupDevice[creator](transportOptions);
4481
+ const transport = (_a = this._mediasoupDevice) === null || _a === void 0 ? void 0 : _a[creator](transportOptions);
3775
4482
  const onConnectionStateListener = (connectionState) => __awaiter(this, void 0, void 0, function* () {
3776
4483
  logger$4.info(`Transport ConnectionStateChanged ${connectionState}`);
3777
4484
  if (connectionState !== "disconnected" && connectionState !== "failed") {
@@ -3794,25 +4501,23 @@ class VegaRtcManager {
3794
4501
  });
3795
4502
  }
3796
4503
  });
3797
- transport
3798
- .on("connect", ({ dtlsParameters }, callback) => {
4504
+ transport === null || transport === void 0 ? void 0 : transport.on("connect", ({ dtlsParameters }, callback) => {
3799
4505
  var _a;
3800
4506
  (_a = this._vegaConnection) === null || _a === void 0 ? void 0 : _a.message("connectTransport", {
3801
4507
  transportId: transport.id,
3802
4508
  dtlsParameters,
3803
4509
  });
3804
4510
  callback();
3805
- })
3806
- .on("connectionstatechange", onConnectionStateListener);
3807
- transport.observer.once("close", () => {
3808
- transport.removeListener(onConnectionStateListener);
4511
+ }).on("connectionstatechange", onConnectionStateListener);
4512
+ transport === null || transport === void 0 ? void 0 : transport.observer.once("close", () => {
4513
+ transport.removeListener("connectionstatechange", onConnectionStateListener);
3809
4514
  });
3810
4515
  if (send) {
3811
- transport.on("produce", ({ kind, rtpParameters, appData, }, callback, errback) => __awaiter(this, void 0, void 0, function* () {
3812
- var _a;
4516
+ transport === null || transport === void 0 ? void 0 : transport.on("produce", ({ kind, rtpParameters, appData, }, callback, errback) => __awaiter(this, void 0, void 0, function* () {
4517
+ var _b;
3813
4518
  try {
3814
4519
  const { paused } = appData;
3815
- const { id } = yield ((_a = this._vegaConnection) === null || _a === void 0 ? void 0 : _a.request("produce", {
4520
+ const { id } = yield ((_b = this._vegaConnection) === null || _b === void 0 ? void 0 : _b.request("produce", {
3816
4521
  transportId: transport.id,
3817
4522
  kind,
3818
4523
  rtpParameters,
@@ -3825,10 +4530,10 @@ class VegaRtcManager {
3825
4530
  errback(error);
3826
4531
  }
3827
4532
  }));
3828
- transport.on("producedata", ({ appData, sctpStreamParameters, }, callback, errback) => __awaiter(this, void 0, void 0, function* () {
3829
- var _b;
4533
+ transport === null || transport === void 0 ? void 0 : transport.on("producedata", ({ appData, sctpStreamParameters, }, callback, errback) => __awaiter(this, void 0, void 0, function* () {
4534
+ var _c;
3830
4535
  try {
3831
- const { id } = yield ((_b = this._vegaConnection) === null || _b === void 0 ? void 0 : _b.request("produceData", {
4536
+ const { id } = yield ((_c = this._vegaConnection) === null || _c === void 0 ? void 0 : _c.request("produceData", {
3832
4537
  transportId: transport.id,
3833
4538
  sctpStreamParameters,
3834
4539
  appData,
@@ -4921,7 +5626,6 @@ class RtcManagerDispatcher {
4921
5626
  webrtcProvider,
4922
5627
  features,
4923
5628
  eventClaim,
4924
- deviceHandlerFactory: features === null || features === void 0 ? void 0 : features.deviceHandlerFactory,
4925
5629
  };
4926
5630
  const isSfu = !!room.sfuServer;
4927
5631
  roomMode = isSfu ? "group" : "normal";
@@ -6252,7 +6956,7 @@ class BandwidthTester extends EventEmitter {
6252
6956
  this.closed = false;
6253
6957
  this._features = features || {};
6254
6958
  this._vegaConnection = null;
6255
- this._mediasoupDevice = new mediasoupClient.Device({ handlerName: getHandler() });
6959
+ this._mediasoupDevice = getMediasoupDevice(features);
6256
6960
  this._routerRtpCapabilities = null;
6257
6961
  this._sendTransport = null;
6258
6962
  this._receiveTransport = null;
@@ -6321,6 +7025,7 @@ class BandwidthTester extends EventEmitter {
6321
7025
  this.emit("close");
6322
7026
  }
6323
7027
  _start() {
7028
+ var _a, _b;
6324
7029
  return __awaiter(this, void 0, void 0, function* () {
6325
7030
  logger$1.info("_start()");
6326
7031
  this._connectTime = Date.now() - this._startTime;
@@ -6339,10 +7044,10 @@ class BandwidthTester extends EventEmitter {
6339
7044
  if (!this._routerRtpCapabilities) {
6340
7045
  modifyMediaCapabilities(routerRtpCapabilities, this._features);
6341
7046
  this._routerRtpCapabilities = routerRtpCapabilities;
6342
- yield this._mediasoupDevice.load({ routerRtpCapabilities });
7047
+ yield ((_a = this._mediasoupDevice) === null || _a === void 0 ? void 0 : _a.load({ routerRtpCapabilities }));
6343
7048
  }
6344
7049
  this._vegaConnection.message("setCapabilities", {
6345
- rtpCapabilities: this._mediasoupDevice.rtpCapabilities,
7050
+ rtpCapabilities: (_b = this._mediasoupDevice) === null || _b === void 0 ? void 0 : _b.rtpCapabilities,
6346
7051
  });
6347
7052
  yield Promise.all([this._createTransport(true), this._createTransport(false)]);
6348
7053
  yield this._createProducer();
@@ -6373,6 +7078,7 @@ class BandwidthTester extends EventEmitter {
6373
7078
  });
6374
7079
  }
6375
7080
  _createTransport(send) {
7081
+ var _a;
6376
7082
  return __awaiter(this, void 0, void 0, function* () {
6377
7083
  const creator = send ? "createSendTransport" : "createRecvTransport";
6378
7084
  const transportOptions = yield this._vegaConnection.request("createTransport", {
@@ -6383,8 +7089,8 @@ class BandwidthTester extends EventEmitter {
6383
7089
  preferUdp: true,
6384
7090
  });
6385
7091
  transportOptions.iceServers = [{ urls: "stun:any.turn.svc.whereby.com" }];
6386
- const transport = this._mediasoupDevice[creator](transportOptions);
6387
- transport.on("connect", ({ dtlsParameters }, callback) => {
7092
+ const transport = (_a = this._mediasoupDevice) === null || _a === void 0 ? void 0 : _a[creator](transportOptions);
7093
+ transport === null || transport === void 0 ? void 0 : transport.on("connect", ({ dtlsParameters }, callback) => {
6388
7094
  this._vegaConnection.message("connectTransport", {
6389
7095
  transportId: transport.id,
6390
7096
  dtlsParameters,
@@ -6392,7 +7098,7 @@ class BandwidthTester extends EventEmitter {
6392
7098
  callback();
6393
7099
  });
6394
7100
  if (send) {
6395
- transport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => __awaiter(this, void 0, void 0, function* () {
7101
+ transport === null || transport === void 0 ? void 0 : transport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => __awaiter(this, void 0, void 0, function* () {
6396
7102
  try {
6397
7103
  const { paused } = appData;
6398
7104
  const { id } = yield this._vegaConnection.request("produce", {
@@ -7046,10 +7752,10 @@ exports.getConstraints = getConstraints;
7046
7752
  exports.getCurrentPeerConnections = getCurrentPeerConnections;
7047
7753
  exports.getDeviceData = getDeviceData;
7048
7754
  exports.getDisplayMedia = getDisplayMedia;
7049
- exports.getHandler = getHandler;
7050
7755
  exports.getIssuesAndMetrics = getIssuesAndMetrics;
7051
7756
  exports.getMediaConstraints = getMediaConstraints;
7052
7757
  exports.getMediaSettings = getMediaSettings;
7758
+ exports.getMediasoupDevice = getMediasoupDevice;
7053
7759
  exports.getNumFailedStatsReports = getNumFailedStatsReports;
7054
7760
  exports.getNumFailedTrackSsrcLookups = getNumFailedTrackSsrcLookups;
7055
7761
  exports.getNumMissingTrackSsrcLookups = getNumMissingTrackSsrcLookups;