sip-connector 23.2.1 → 23.2.2

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.
@@ -1,20 +1,20 @@
1
1
  import te from "debug";
2
2
  import { TypedEvents as R } from "events-constructor";
3
- import { CancelableRequest as J, isCanceledError as ze } from "@krivega/cancelable-promise";
4
- import { SetTimeoutRequest as Se, resolveRequesterByTimeout as je, requesterByTimeoutsWithFailCalls as Xe, DelayRequester as Ke, hasCanceledError as Ze } from "@krivega/timeout-requester";
5
- import { hasCanceledError as et, repeatedCallsAsync as Ee } from "repeated-calls";
6
- import { createActor as tt, setup as G, assign as _ } from "xstate";
7
- import { createStackPromises as me, isPromiseIsNotActualError as nt } from "stack-promises";
3
+ import { CancelableRequest as J, isCanceledError as Je } from "@krivega/cancelable-promise";
4
+ import { resolveRequesterByTimeout as ze, requesterByTimeoutsWithFailCalls as je, DelayRequester as Xe, hasCanceledError as Ke, SetTimeoutRequest as Se } from "@krivega/timeout-requester";
5
+ import { hasCanceledError as Ze, repeatedCallsAsync as Ee } from "repeated-calls";
6
+ import { createActor as et, setup as G, assign as _ } from "xstate";
7
+ import { createStackPromises as me, isPromiseIsNotActualError as tt } from "stack-promises";
8
8
  import "ua-parser-js";
9
9
  import "sequent-promises";
10
- import st from "lodash";
10
+ import nt from "lodash";
11
11
  const ne = "sip-connector", d = te(ne), re = (n, e) => {
12
12
  d(`${n}:`, e);
13
- }, Si = () => {
14
- te.enable(ne);
15
13
  }, Ei = () => {
14
+ te.enable(ne);
15
+ }, mi = () => {
16
16
  te.enable(`-${ne}`);
17
- }, it = "Error decline with 603", rt = 1006, at = (n) => typeof n == "object" && n !== null && "code" in n && n.code === rt, ot = (n) => n.message === it;
17
+ }, st = "Error decline with 603", it = 1006, rt = (n) => typeof n == "object" && n !== null && "code" in n && n.code === it, at = (n) => n.message === st;
18
18
  var W = /* @__PURE__ */ ((n) => (n.SPECTATOR = "SPECTATOR", n.PARTICIPANT = "PARTICIPANT", n))(W || {}), y = /* @__PURE__ */ ((n) => (n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.ENTER_ROOM = "application/vinteo.webrtc.roomname", n.MIC = "application/vinteo.webrtc.mic", n.USE_LICENSE = "application/vinteo.webrtc.uselic", n.PARTICIPANT_STATE = "application/vinteo.webrtc.partstate", n.NOTIFY = "application/vinteo.webrtc.notify", n))(y || {}), b = /* @__PURE__ */ ((n) => (n.SHARE_STATE = "application/vinteo.webrtc.sharedesktop", n.MAIN_CAM = "application/vinteo.webrtc.maincam", n.CHANNELS = "application/vinteo.webrtc.channels", n.MEDIA_STATE = "application/vinteo.webrtc.mediastate", n.REFUSAL = "application/vinteo.webrtc.refusal", n.STATS = "application/vinteo.webrtc.stats", n))(b || {}), f = /* @__PURE__ */ ((n) => (n.PAUSE_MAIN_CAM = "PAUSEMAINCAM", n.RESUME_MAIN_CAM = "RESUMEMAINCAM", n.MAX_MAIN_CAM_RESOLUTION = "MAXMAINCAMRESOLUTION", n.ADMIN_STOP_MAIN_CAM = "ADMINSTOPMAINCAM", n.ADMIN_START_MAIN_CAM = "ADMINSTARTMAINCAM", n))(f || {}), Q = /* @__PURE__ */ ((n) => (n.ADMIN_STOP_MIC = "ADMINSTOPMIC", n.ADMIN_START_MIC = "ADMINSTARTMIC", n))(Q || {}), pe = /* @__PURE__ */ ((n) => (n.H264 = "H264", n.VP8 = "VP8", n.VP9 = "VP9", n.AV1 = "AV1", n))(pe || {}), l = /* @__PURE__ */ ((n) => (n.CONTENT_TYPE = "content-type", n.CONTENT_ENTER_ROOM = "x-webrtc-enter-room", n.CONTENT_USE_LICENSE = "x-webrtc-use-license", n.PARTICIPANT_NAME = "x-webrtc-participant-name", n.INPUT_CHANNELS = "x-webrtc-input-channels", n.OUTPUT_CHANNELS = "x-webrtc-output-channels", n.MAIN_CAM = "x-webrtc-maincam", n.MIC = "x-webrtc-mic", n.MEDIA_SYNC = "x-webrtc-sync", n.MAIN_CAM_RESOLUTION = "x-webrtc-maincam-resolution", n.MEDIA_STATE = "x-webrtc-media-state", n.MEDIA_TYPE = "x-vinteo-media-type", n.MAIN_CAM_STATE = "x-vinteo-maincam-state", n.MIC_STATE = "x-vinteo-mic-state", n.CONTENT_PARTICIPANT_STATE = "x-webrtc-partstate", n.NOTIFY = "x-vinteo-notify", n.CONTENT_ENABLE_MEDIA_DEVICE = "x-webrtc-request-enable-media-device", n.CONTENTED_STREAM_STATE = "x-webrtc-share-state", n.CONTENTED_STREAM_CODEC = "x-webrtc-share-codec", n.AVAILABLE_INCOMING_BITRATE = "x-webrtc-available-incoming-bitrate", n.AUDIO_TRACK_COUNT = "x-webrtc-audio-track-count", n.VIDEO_TRACK_COUNT = "x-webrtc-video-track-count", n.TRACKS_DIRECTION = "x-webrtc-tracks-direction", n.AUDIO_ID = "x-webrtc-audioid", n))(l || {}), $ = /* @__PURE__ */ ((n) => (n.AVAILABLE_CONTENTED_STREAM = "YOUCANRECEIVECONTENT", n.NOT_AVAILABLE_CONTENTED_STREAM = "CONTENTEND", n.MUST_STOP_PRESENTATION = "YOUMUSTSTOPSENDCONTENT", n))($ || {}), U = /* @__PURE__ */ ((n) => (n.AVAILABLE_CONTENTED_STREAM = "x-webrtc-share-state: YOUCANRECEIVECONTENT", n.NOT_AVAILABLE_CONTENTED_STREAM = "x-webrtc-share-state: CONTENTEND", n.ACK_PERMISSION_TO_START_PRESENTATION = "x-webrtc-share-state: LETMESTARTPRESENTATION", n.STOPPED_CLIENT_PRESENTATION = "x-webrtc-share-state: STOPPRESENTATION", n.ENABLE_MAIN_CAM = "x-webrtc-request-enable-media-device: LETMESTARTMAINCAM", n))(U || {}), Y = /* @__PURE__ */ ((n) => (n.ADMIN_SYNC_FORCED = "1", n.ADMIN_SYNC_NOT_FORCED = "0", n))(Y || {}), Ce = /* @__PURE__ */ ((n) => (n.AUDIO = "AUDIO", n.VIDEO = "VIDEO", n.AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION", n))(Ce || {}), g = /* @__PURE__ */ ((n) => (n.ENTER_ROOM = "enter-room", n.MAIN_CAM_CONTROL = "main-cam-control", n.USE_LICENSE = "use-license", n.NEW_DTMF = "new-dtmf", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "conference:participant-token-issued", n.CONTENTED_STREAM_AVAILABLE = "contented-stream:available", n.CONTENTED_STREAM_NOT_AVAILABLE = "contented-stream:not-available", n.PRESENTATION_MUST_STOP = "presentation:must-stop", n.CHANNELS_ALL = "channels:all", n.CHANNELS_NOTIFY = "channels:notify", n.PARTICIPANT_ADDED_TO_LIST_MODERATORS = "participant:added-to-list-moderators", n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS = "participant:removed-from-list-moderators", n.PARTICIPANT_MOVE_REQUEST_TO_STREAM = "participant:move-request-to-stream", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS = "participant:move-request-to-spectators", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC = "participant:move-request-to-spectators-synthetic", n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID = "participant:move-request-to-spectators-with-audio-id", n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS = "participant:move-request-to-participants", n.PARTICIPATION_ACCEPTING_WORD_REQUEST = "participation:accepting-word-request", n.PARTICIPATION_CANCELLING_WORD_REQUEST = "participation:cancelling-word-request", n.WEBCAST_STARTED = "webcast:started", n.WEBCAST_STOPPED = "webcast:stopped", n.ACCOUNT_CHANGED = "account:changed", n.ACCOUNT_DELETED = "account:deleted", n.ADMIN_START_MAIN_CAM = "admin:start-main-cam", n.ADMIN_STOP_MAIN_CAM = "admin:stop-main-cam", n.ADMIN_START_MIC = "admin:start-mic", n.ADMIN_STOP_MIC = "admin:stop-mic", n.ADMIN_FORCE_SYNC_MEDIA_STATE = "admin:force-sync-media-state", n))(g || {});
19
19
  const Ne = [
20
20
  "enter-room",
@@ -45,15 +45,15 @@ const Ne = [
45
45
  "admin:start-mic",
46
46
  "admin:stop-mic",
47
47
  "admin:force-sync-media-state"
48
- ], ct = () => new R(Ne), dt = (n) => typeof n == "string" && n.trim().length > 0, w = (n, e) => {
48
+ ], ot = () => new R(Ne), ct = (n) => typeof n == "string" && n.trim().length > 0, w = (n, e) => {
49
49
  const t = e.toLowerCase(), s = Object.entries(n).find(([, i]) => typeof i == "string" && i.toLowerCase() === t);
50
50
  return s ? s[1] : void 0;
51
- }, ht = (n) => typeof n == "string" && !Number.isNaN(Number(n)) && Number.isFinite(Number(n)), lt = (n) => {
52
- if (ht(n))
51
+ }, dt = (n) => typeof n == "string" && !Number.isNaN(Number(n)) && Number.isFinite(Number(n)), ht = (n) => {
52
+ if (dt(n))
53
53
  return Number(n);
54
54
  }, N = (n, e) => {
55
55
  const t = n.getHeader(e.toLowerCase());
56
- if (!dt(t))
56
+ if (!ct(t))
57
57
  return;
58
58
  const s = t.toLowerCase();
59
59
  switch (e) {
@@ -74,7 +74,7 @@ const Ne = [
74
74
  case l.AVAILABLE_INCOMING_BITRATE:
75
75
  case l.AUDIO_TRACK_COUNT:
76
76
  case l.VIDEO_TRACK_COUNT:
77
- return lt(s);
77
+ return ht(s);
78
78
  case l.CONTENTED_STREAM_CODEC:
79
79
  return w(pe, s);
80
80
  case l.CONTENT_TYPE:
@@ -96,11 +96,11 @@ const Ne = [
96
96
  }
97
97
  };
98
98
  var I = /* @__PURE__ */ ((n) => (n.CHANNELS = "channels", n.WEBCAST_STARTED = "WebcastStarted", n.WEBCAST_STOPPED = "WebcastStopped", n.ACCOUNT_CHANGED = "accountChanged", n.ACCOUNT_DELETED = "accountDeleted", n.ADDED_TO_LIST_MODERATORS = "addedToListModerators", n.REMOVED_FROM_LIST_MODERATORS = "removedFromListModerators", n.ACCEPTING_WORD_REQUEST = "ParticipationRequestAccepted", n.CANCELLING_WORD_REQUEST = "ParticipationRequestRejected", n.MOVE_REQUEST_TO_STREAM = "ParticipantMovedToWebcast", n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED = "ConferenceParticipantTokenIssued", n))(I || {});
99
- class gt {
99
+ class lt {
100
100
  events;
101
101
  callManager;
102
102
  constructor() {
103
- this.events = ct();
103
+ this.events = ot();
104
104
  }
105
105
  subscribe({
106
106
  connectionManager: e,
@@ -201,7 +201,7 @@ class gt {
201
201
  ...e,
202
202
  extraHeaders: s
203
203
  }).catch((i) => {
204
- if (ot(i))
204
+ if (at(i))
205
205
  throw i;
206
206
  });
207
207
  }
@@ -499,7 +499,7 @@ class q {
499
499
  subscriptions = [];
500
500
  stateChangeListeners = /* @__PURE__ */ new Set();
501
501
  constructor(e) {
502
- this.actor = tt(e), this.actor.start(), this.addSubscription(
502
+ this.actor = et(e), this.actor.start(), this.addSubscription(
503
503
  this.subscribe((t) => {
504
504
  const s = t.value;
505
505
  this.stateChangeListeners.forEach((i) => {
@@ -541,8 +541,8 @@ class q {
541
541
  return this.subscriptions.push(t), t;
542
542
  }
543
543
  }
544
- var ut = /* @__PURE__ */ ((n) => (n.IDLE = "call:idle", n.CONNECTING = "call:connecting", n.ACCEPTED = "call:accepted", n.IN_CALL = "call:inCall", n.ENDED = "call:ended", n.FAILED = "call:failed", n))(ut || {});
545
- const Tt = G({
544
+ var gt = /* @__PURE__ */ ((n) => (n.IDLE = "call:idle", n.CONNECTING = "call:connecting", n.ACCEPTED = "call:accepted", n.IN_CALL = "call:inCall", n.ENDED = "call:ended", n.FAILED = "call:failed", n))(gt || {});
545
+ const ut = G({
546
546
  types: {
547
547
  context: {},
548
548
  events: {}
@@ -625,9 +625,9 @@ const Tt = G({
625
625
  }
626
626
  }
627
627
  });
628
- class St extends q {
628
+ class Tt extends q {
629
629
  constructor(e) {
630
- super(Tt), this.subscribeToEvents(e);
630
+ super(ut), this.subscribeToEvents(e);
631
631
  }
632
632
  get isIdle() {
633
633
  return this.state === "call:idle";
@@ -692,7 +692,7 @@ class St extends q {
692
692
  );
693
693
  }
694
694
  }
695
- var E = /* @__PURE__ */ ((n) => (n.PEER_CONNECTION = "peerconnection", n.CONNECTING = "connecting", n.SENDING = "sending", n.PROGRESS = "progress", n.ACCEPTED = "accepted", n.CONFIRMED = "confirmed", n.ENDED = "ended", n.FAILED = "failed", n.NEW_DTMF = "newDTMF", n.NEW_INFO = "newInfo", n.HOLD = "hold", n.UNHOLD = "unhold", n.MUTED = "muted", n.UNMUTED = "unmuted", n.REINVITE = "reinvite", n.UPDATE = "update", n.REFER = "refer", n.REPLACES = "replaces", n.SDP = "sdp", n.ICE_CANDIDATE = "icecandidate", n.GET_USER_MEDIA_FAILED = "getusermediafailed", n.PEER_CONNECTION_CREATE_OFFER_FAILED = "peerconnection:createofferfailed", n.PEER_CONNECTION_CREATE_ANSWER_FAILED = "peerconnection:createanswerfailed", n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED = "peerconnection:setlocaldescriptionfailed", n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED = "peerconnection:setremotedescriptionfailed", n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n.PEER_CONNECTION_CONFIRMED = "peerconnection:confirmed", n.PEER_CONNECTION_ONTRACK = "peerconnection:ontrack", n.ENDED_FROM_SERVER = "ended:fromserver", n.CALL_STATUS_CHANGED = "call-status-changed", n.REMOTE_TRACKS_CHANGED = "remote-tracks-changed", n.REMOTE_STREAMS_CHANGED = "remote-streams-changed", n))(E || {}), Et = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))(Et || {});
695
+ var E = /* @__PURE__ */ ((n) => (n.PEER_CONNECTION = "peerconnection", n.CONNECTING = "connecting", n.SENDING = "sending", n.PROGRESS = "progress", n.ACCEPTED = "accepted", n.CONFIRMED = "confirmed", n.ENDED = "ended", n.FAILED = "failed", n.NEW_DTMF = "newDTMF", n.NEW_INFO = "newInfo", n.HOLD = "hold", n.UNHOLD = "unhold", n.MUTED = "muted", n.UNMUTED = "unmuted", n.REINVITE = "reinvite", n.UPDATE = "update", n.REFER = "refer", n.REPLACES = "replaces", n.SDP = "sdp", n.ICE_CANDIDATE = "icecandidate", n.GET_USER_MEDIA_FAILED = "getusermediafailed", n.PEER_CONNECTION_CREATE_OFFER_FAILED = "peerconnection:createofferfailed", n.PEER_CONNECTION_CREATE_ANSWER_FAILED = "peerconnection:createanswerfailed", n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED = "peerconnection:setlocaldescriptionfailed", n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED = "peerconnection:setremotedescriptionfailed", n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n.PEER_CONNECTION_CONFIRMED = "peerconnection:confirmed", n.PEER_CONNECTION_ONTRACK = "peerconnection:ontrack", n.ENDED_FROM_SERVER = "ended:fromserver", n.CALL_STATUS_CHANGED = "call-status-changed", n.REMOTE_TRACKS_CHANGED = "remote-tracks-changed", n.REMOTE_STREAMS_CHANGED = "remote-streams-changed", n))(E || {}), St = /* @__PURE__ */ ((n) => (n.LOCAL = "local", n.REMOTE = "remote", n.SYSTEM = "system", n))(St || {});
696
696
  const Ae = [
697
697
  "peerconnection",
698
698
  "connecting",
@@ -724,7 +724,7 @@ const Ae = [
724
724
  "peerconnection:createanswerfailed",
725
725
  "peerconnection:setlocaldescriptionfailed",
726
726
  "peerconnection:setremotedescriptionfailed"
727
- ], mt = [
727
+ ], Et = [
728
728
  "peerconnection:confirmed",
729
729
  "peerconnection:ontrack",
730
730
  "ended:fromserver",
@@ -733,8 +733,8 @@ const Ae = [
733
733
  "remote-streams-changed"
734
734
  ], Re = [
735
735
  ...Ae,
736
- ...mt
737
- ], pt = () => new R(Re), Ct = (n, e) => {
736
+ ...Et
737
+ ], mt = () => new R(Re), pt = (n, e) => {
738
738
  n.getVideoTracks().forEach((s) => {
739
739
  "contentHint" in s && s.contentHint !== e && (s.contentHint = e);
740
740
  });
@@ -746,8 +746,8 @@ const Ae = [
746
746
  if (!n || e === "recvonly" && t === "recvonly")
747
747
  return;
748
748
  const i = t === "recvonly" ? [] : n.getAudioTracks(), r = e === "recvonly" ? [] : n.getVideoTracks(), a = [...i, ...r], o = new MediaStream(a);
749
- return o.getTracks = () => [...o.getAudioTracks(), ...o.getVideoTracks()], s && s !== "none" && Ct(o, s), o;
750
- }, Nt = "api/v2/rtp2webrtc/offer", At = async ({
749
+ return o.getTracks = () => [...o.getAudioTracks(), ...o.getVideoTracks()], s && s !== "none" && pt(o, s), o;
750
+ }, Ct = "api/v2/rtp2webrtc/offer", Nt = async ({
751
751
  serverUrl: n,
752
752
  conferenceNumber: e,
753
753
  quality: t,
@@ -756,7 +756,7 @@ const Ae = [
756
756
  token: r
757
757
  }) => {
758
758
  const a = new URL(
759
- `https://${n.replace(/\/$/, "")}/${Nt}/${encodeURIComponent(e)}`
759
+ `https://${n.replace(/\/$/, "")}/${Ct}/${encodeURIComponent(e)}`
760
760
  );
761
761
  a.searchParams.set("quality", t), a.searchParams.set("audio", String(s));
762
762
  const o = {
@@ -779,39 +779,39 @@ const Ae = [
779
779
  return h;
780
780
  }
781
781
  };
782
- }, Rt = (n, e) => (n.degradationPreference = e.degradationPreference, n), It = (n, e) => {
782
+ }, At = (n, e) => (n.degradationPreference = e.degradationPreference, n), Rt = (n, e) => {
783
783
  n.encodings ??= [];
784
784
  for (let t = n.encodings.length; t < e; t += 1)
785
785
  n.encodings.push({});
786
786
  return n;
787
- }, Ie = (n) => (e, t) => t !== void 0 && e !== t || t === void 0 && e !== n, vt = Ie(), ft = (n, e) => {
788
- if (vt(n, e))
787
+ }, Ie = (n) => (e, t) => t !== void 0 && e !== t || t === void 0 && e !== n, It = Ie(), vt = (n, e) => {
788
+ if (It(n, e))
789
789
  return n;
790
- }, Mt = (n, e) => {
791
- const t = n.maxBitrate, s = ft(e, t);
790
+ }, ft = (n, e) => {
791
+ const t = n.maxBitrate, s = vt(e, t);
792
792
  return s !== void 0 && (n.maxBitrate = s), n;
793
- }, ve = 1, _t = Ie(
793
+ }, ve = 1, Mt = Ie(
794
794
  ve
795
- ), bt = (n, e) => {
795
+ ), _t = (n, e) => {
796
796
  const t = n === void 0 ? void 0 : Math.max(n, ve);
797
- if (t !== void 0 && _t(
797
+ if (t !== void 0 && Mt(
798
798
  t,
799
799
  e
800
800
  ))
801
801
  return t;
802
- }, Ot = (n, e) => {
803
- const t = n.scaleResolutionDownBy, s = bt(
802
+ }, bt = (n, e) => {
803
+ const t = n.scaleResolutionDownBy, s = _t(
804
804
  e,
805
805
  t
806
806
  );
807
807
  return s !== void 0 && (n.scaleResolutionDownBy = s), n;
808
- }, Dt = (n, e) => {
808
+ }, Ot = (n, e) => {
809
809
  const t = e.encodings?.length ?? 0;
810
- return It(n, t), n.encodings.forEach((s, i) => {
810
+ return Rt(n, t), n.encodings.forEach((s, i) => {
811
811
  const r = (e?.encodings ?? [])[i], a = r?.maxBitrate, o = r?.scaleResolutionDownBy;
812
- Mt(s, a), Ot(s, o);
812
+ ft(s, a), bt(s, o);
813
813
  }), n;
814
- }, Pt = (n, e) => {
814
+ }, Dt = (n, e) => {
815
815
  if (n.codecs?.length !== e.codecs?.length)
816
816
  return !0;
817
817
  for (let t = 0; t < (n.codecs?.length ?? 0); t++)
@@ -832,8 +832,8 @@ const Ae = [
832
832
  const t = n.getParameters(), s = JSON.parse(
833
833
  JSON.stringify(t)
834
834
  );
835
- Dt(t, e), Rt(t, e);
836
- const i = Pt(s, t);
835
+ Ot(t, e), At(t, e);
836
+ const i = Dt(s, t);
837
837
  return i && await n.setParameters(t), { parameters: t, isChanged: i };
838
838
  }, fe = async (n, e, t) => {
839
839
  const { isChanged: s, parameters: i } = await K(n, {
@@ -845,442 +845,119 @@ const Ae = [
845
845
  ]
846
846
  });
847
847
  return s && t && t(i), { isChanged: s, parameters: i };
848
- }, yt = (n, e) => n.find((t) => t.track !== null && e.getTracks().includes(t.track)), wt = async (n, e, t) => {
849
- const s = yt(n, e);
848
+ }, Pt = (n, e) => n.find((t) => t.track !== null && e.getTracks().includes(t.track)), yt = async (n, e, t) => {
849
+ const s = Pt(n, e);
850
850
  if (s)
851
851
  return fe(s, { maxBitrate: t });
852
- }, Lt = (n) => [...n.keys()].map((e) => n.get(e)), Ut = (n, e) => Lt(n).find((t) => t?.type === e), Ft = async (n) => n.getStats().then((e) => Ut(e, "codec")?.mimeType);
852
+ }, wt = 10, Lt = 10, x = (n, e) => n.getSenders().filter((t) => t.track?.kind === e), Ut = (n) => n === "audio" ? wt : Lt, Ft = (n) => n.track !== null;
853
853
  class Bt {
854
- // eslint-disable-next-line @typescript-eslint/class-methods-use-this
855
- async getCodecFromSender(e) {
856
- return await Ft(e) ?? "";
857
- }
858
- }
859
- class kt {
860
- stackPromises = me({
861
- noRunIsNotActual: !0
862
- });
854
+ previousBitrates = /* @__PURE__ */ new Map();
863
855
  /**
864
- * Добавляет задачу в очередь и возвращает Promise с результатом
865
- * @param task - Функция для выполнения
866
- * @returns Promise с результатом выполнения задачи
856
+ * Устанавливает минимальный битрейт для указанных типов потоков
857
+ * @param connection - активное RTCPeerConnection
858
+ * @param kinds - типы потоков ('audio' | 'video' | 'all')
867
859
  */
868
- async add(e) {
869
- return this.stackPromises.add(e), this.run();
870
- }
871
- stop() {
872
- this.stackPromises.stop();
860
+ async setMinBitrateForSenders(e, t = "all") {
861
+ const s = [];
862
+ if (!e)
863
+ return;
864
+ (t === "audio" || t === "all") && s.push(...x(e, "audio")), (t === "video" || t === "all") && s.push(...x(e, "video"));
865
+ const i = s.filter(Ft).map(async (r) => {
866
+ const a = r.getParameters();
867
+ this.saveCurrentBitrate(r, a);
868
+ const o = {
869
+ ...a,
870
+ encodings: a.encodings.map((c) => ({
871
+ ...c,
872
+ maxBitrate: Ut(r.track.kind)
873
+ }))
874
+ };
875
+ await K(r, o);
876
+ });
877
+ await Promise.all(i);
873
878
  }
874
879
  /**
875
- * Выполняет задачи из очереди с обработкой ошибок
876
- * @returns Promise с результатом выполнения
880
+ * Восстанавливает предыдущий битрейт для указанных типов потоков
881
+ * @param connection - активное RTCPeerConnection
882
+ * @param kinds - типы потоков ('audio' | 'video' | 'all')
877
883
  */
878
- async run() {
879
- return this.stackPromises().catch((e) => {
880
- d("TaskQueue: error", e);
884
+ async restoreBitrateForSenders(e, t = "all") {
885
+ const s = [];
886
+ if (!e)
887
+ return;
888
+ (t === "audio" || t === "all") && s.push(...x(e, "audio")), (t === "video" || t === "all") && s.push(...x(e, "video"));
889
+ const i = s.map(async (r) => {
890
+ const a = this.getSavedBitrate(r);
891
+ if (a) {
892
+ const c = {
893
+ ...r.getParameters(),
894
+ encodings: a
895
+ };
896
+ await K(r, c), this.clearSavedBitrate(r);
897
+ }
881
898
  });
882
- }
883
- }
884
- class $t {
885
- taskQueue;
886
- onSetParameters;
887
- constructor(e) {
888
- this.onSetParameters = e, this.taskQueue = new kt();
889
- }
890
- async setEncodingsToSender(e, t) {
891
- return this.taskQueue.add(async () => fe(e, t, this.onSetParameters));
892
- }
893
- stop() {
894
- this.taskQueue.stop();
895
- }
896
- }
897
- const Me = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), Gt = 1e6, O = (n) => n * Gt, _e = O(0.06), be = O(4), qt = (n) => n <= 64 ? _e : n <= 128 ? O(0.12) : n <= 256 ? O(0.25) : n <= 384 ? O(0.32) : n <= 426 ? O(0.38) : n <= 640 ? O(0.5) : n <= 848 ? O(0.7) : n <= 1280 ? O(1) : n <= 1920 ? O(2) : be, Vt = "av1", xt = (n) => Me(n, Vt), Ht = 0.6, se = (n, e) => xt(e) ? n * Ht : n, Oe = (n) => se(_e, n), Wt = (n) => se(be, n), ae = (n, e) => {
898
- const t = qt(n);
899
- return se(t, e);
900
- }, j = 1, Qt = ({
901
- videoTrack: n,
902
- targetSize: e
903
- }) => {
904
- const t = n.getSettings(), s = t.width, i = t.height, r = s === void 0 ? j : s / e.width, a = i === void 0 ? j : i / e.height;
905
- return Math.max(r, a, j);
906
- };
907
- class Yt {
908
- ignoreForCodec;
909
- senderFinder;
910
- codecProvider;
911
- parametersSetter;
912
- resultNoChanged = {
913
- isChanged: !1,
914
- parameters: {
915
- encodings: [{}],
916
- transactionId: "0",
917
- codecs: [],
918
- headerExtensions: [],
919
- rtcp: {}
920
- }
921
- };
922
- constructor({
923
- senderFinder: e,
924
- codecProvider: t,
925
- parametersSetter: s
926
- }, i) {
927
- this.senderFinder = e, this.codecProvider = t, this.parametersSetter = s, this.ignoreForCodec = i.ignoreForCodec;
899
+ await Promise.all(i);
928
900
  }
929
901
  /**
930
- * Выполняет балансировку на основе заголовков от сервера
931
- * @param connection - RTCPeerConnection для получения отправителей
932
- * @param headers - Заголовки от сервера с командами управления
933
- * @returns Promise с результатом балансировки
902
+ * Получает сохраненные параметры битрейта для отправителя
934
903
  */
935
- async balance(e, t) {
936
- const s = e.getSenders(), i = this.senderFinder.findVideoSender(s);
937
- if (!i?.track)
938
- return { ...this.resultNoChanged, sender: i };
939
- const r = await this.codecProvider.getCodecFromSender(i);
940
- if (Me(r, this.ignoreForCodec))
941
- return { ...this.resultNoChanged, sender: i };
942
- const { mainCam: a, resolutionMainCam: o } = t ?? {};
943
- return this.processSender(
944
- { mainCam: a, resolutionMainCam: o },
945
- {
946
- sender: i,
947
- codec: r,
948
- videoTrack: i.track
949
- }
950
- ).then((c) => ({ ...c, sender: i }));
904
+ getSavedBitrate(e) {
905
+ return this.previousBitrates.get(e);
951
906
  }
952
907
  /**
953
- * Обрабатывает отправитель в зависимости от команды управления
954
- * @param context - Контекст балансировки
955
- * @returns Promise с результатом обработки
908
+ * Удаляет сохраненные параметры битрейта для отправителя
956
909
  */
957
- async processSender(e, t) {
958
- const { mainCam: s, resolutionMainCam: i } = e;
959
- switch (s) {
960
- case f.PAUSE_MAIN_CAM:
961
- return this.downgradeResolutionSender(t);
962
- case f.RESUME_MAIN_CAM:
963
- return this.setBitrateByTrackResolution(t);
964
- case f.MAX_MAIN_CAM_RESOLUTION:
965
- return i !== void 0 ? this.setResolutionSender(i, t) : this.setBitrateByTrackResolution(t);
966
- case f.ADMIN_STOP_MAIN_CAM:
967
- case f.ADMIN_START_MAIN_CAM:
968
- case void 0:
969
- return this.setBitrateByTrackResolution(t);
970
- default:
971
- return this.setBitrateByTrackResolution(t);
972
- }
910
+ clearSavedBitrate(e) {
911
+ this.previousBitrates.delete(e);
973
912
  }
974
913
  /**
975
- * Понижает разрешение отправителя (пауза камеры)
976
- * @param context - Контекст балансировки
977
- * @returns Promise с результатом
914
+ * Очищает все сохраненные состояния битрейта
978
915
  */
979
- async downgradeResolutionSender(e) {
980
- const { sender: t, codec: s } = e, i = {
981
- scaleResolutionDownBy: 200,
982
- maxBitrate: Oe(s)
983
- };
984
- return this.parametersSetter.setEncodingsToSender(t, i);
916
+ clearAll() {
917
+ this.previousBitrates.clear();
985
918
  }
986
919
  /**
987
- * Устанавливает битрейт на основе разрешения трека
988
- * @param context - Контекст балансировки
989
- * @returns Promise с результатом
920
+ * Проверяет, есть ли сохраненное состояние для отправителя
990
921
  */
991
- async setBitrateByTrackResolution(e) {
992
- const { sender: t, videoTrack: s, codec: i } = e, a = s.getSettings().width, o = a === void 0 ? Wt(i) : ae(a, i);
993
- return this.parametersSetter.setEncodingsToSender(t, {
994
- scaleResolutionDownBy: 1,
995
- maxBitrate: o
996
- });
922
+ hasSavedBitrate(e) {
923
+ return this.previousBitrates.has(e);
997
924
  }
998
925
  /**
999
- * Устанавливает разрешение отправителя на основе заголовка
1000
- * @param resolutionMainCam - Разрешение главной камеры
1001
- * @param context - Контекст балансировки
1002
- * @returns Promise с результатом
926
+ * Возвращает количество сохраненных состояний
1003
927
  */
1004
- async setResolutionSender(e, t) {
1005
- const [s, i] = e.split("x"), { sender: r, videoTrack: a, codec: o } = t, c = {
1006
- width: Number(s),
1007
- height: Number(i)
1008
- }, h = Qt({
1009
- videoTrack: a,
1010
- targetSize: c
1011
- }), T = ae(c.width, o), u = {
1012
- scaleResolutionDownBy: h,
1013
- maxBitrate: T
1014
- };
1015
- return this.parametersSetter.setEncodingsToSender(r, u);
1016
- }
1017
- }
1018
- const Jt = (n) => n.find((e) => e.track?.kind === "video");
1019
- class zt {
1020
- // eslint-disable-next-line @typescript-eslint/class-methods-use-this
1021
- findVideoSender(e) {
1022
- return Jt(e);
1023
- }
1024
- }
1025
- class jt {
1026
- currentSender;
1027
- originalReplaceTrack;
1028
- lastWidth;
1029
- lastHeight;
1030
- maxPollIntervalMs;
1031
- currentPollIntervalMs;
1032
- pollIntervalMs;
1033
- setTimeoutRequest;
1034
- constructor({
1035
- pollIntervalMs: e = 1e3,
1036
- maxPollIntervalMs: t
1037
- }) {
1038
- this.pollIntervalMs = e, this.maxPollIntervalMs = t ?? e * 16, this.currentPollIntervalMs = this.pollIntervalMs, this.setTimeoutRequest = new Se();
928
+ getSavedCount() {
929
+ return this.previousBitrates.size;
1039
930
  }
1040
931
  /**
1041
- * Проверяет актуальный video-sender и (при необходимости) перенастраивает наблюдение.
932
+ * Сохраняет текущие параметры битрейта для отправителя
1042
933
  */
1043
- subscribe(e, t) {
1044
- if (!e) {
1045
- this.detachSender();
1046
- return;
1047
- }
1048
- this.currentSender !== e && (this.detachSender(), this.attachSender(e, t));
934
+ saveCurrentBitrate(e, t) {
935
+ const s = t.encodings.map((i) => ({ ...i }));
936
+ this.previousBitrates.set(e, s);
1049
937
  }
1050
- /** Останавливает всю активность мониторинга */
1051
- unsubscribe() {
1052
- this.detachSender();
938
+ }
939
+ var Me = /* @__PURE__ */ ((n) => (n.BYE = "Terminated", n.WEBRTC_ERROR = "WebRTC Error", n.CANCELED = "Canceled", n.REQUEST_TIMEOUT = "Request Timeout", n.REJECTED = "Rejected", n.REDIRECTED = "Redirected", n.UNAVAILABLE = "Unavailable", n.NOT_FOUND = "Not Found", n.ADDRESS_INCOMPLETE = "Address Incomplete", n.INCOMPATIBLE_SDP = "Incompatible SDP", n.BAD_MEDIA_DESCRIPTION = "Bad Media Description", n))(Me || {});
940
+ class kt {
941
+ events;
942
+ rtcSession;
943
+ disposers = /* @__PURE__ */ new Set();
944
+ onReset;
945
+ // Менеджер состояния битрейта
946
+ bitrateStateManager = new Bt();
947
+ constructor(e, { onReset: t }) {
948
+ this.events = e, this.onReset = t, e.on(E.FAILED, this.handleEnded), e.on(E.ENDED, this.handleEnded);
1053
949
  }
1054
- attachSender(e, t) {
1055
- this.currentSender = e;
1056
- const s = e.replaceTrack.bind(e);
1057
- this.originalReplaceTrack = s, e.replaceTrack = async (i) => {
1058
- await s(i), this.attachTrack(t, i ?? void 0), t();
1059
- }, this.attachTrack(t, e.track);
950
+ get connection() {
951
+ return this.rtcSession?.connection;
1060
952
  }
1061
- detachSender() {
1062
- this.currentSender && this.originalReplaceTrack && (this.currentSender.replaceTrack = this.originalReplaceTrack), this.originalReplaceTrack = void 0, this.currentSender = void 0, this.detachTrack();
953
+ get isCallActive() {
954
+ return this.rtcSession?.isEstablished() === !0;
1063
955
  }
1064
- attachTrack(e, t) {
1065
- if (this.detachTrack(), !t)
1066
- return;
1067
- const { width: s, height: i } = t.getSettings();
1068
- this.lastWidth = s, this.lastHeight = i, this.currentPollIntervalMs = this.pollIntervalMs, this.schedulePoll(t, e);
1069
- }
1070
- /**
1071
- * Периодически опрашивает track с экспоненциальной адаптацией частоты.
1072
- * При отсутствии изменений интервал удваивается до maxPollIntervalMs,
1073
- * при обнаружении изменений сбрасывается до начального.
1074
- */
1075
- schedulePoll(e, t) {
1076
- const s = () => {
1077
- const { width: i, height: r } = e.getSettings();
1078
- i !== this.lastWidth || r !== this.lastHeight ? (this.lastWidth = i, this.lastHeight = r, this.currentPollIntervalMs = this.pollIntervalMs, t()) : this.currentPollIntervalMs = Math.min(
1079
- this.currentPollIntervalMs * 2,
1080
- this.maxPollIntervalMs
1081
- ), this.setTimeoutRequest.request(s, this.currentPollIntervalMs);
1082
- };
1083
- this.setTimeoutRequest.request(s, this.currentPollIntervalMs);
1084
- }
1085
- detachTrack() {
1086
- this.setTimeoutRequest.cancelRequest(), this.lastWidth = void 0, this.lastHeight = void 0;
1087
- }
1088
- }
1089
- class Xt {
1090
- apiManager;
1091
- currentHandler;
1092
- constructor(e) {
1093
- this.apiManager = e;
1094
- }
1095
- /**
1096
- * Подписывается на события управления главной камерой
1097
- * @param handler - Обработчик события
1098
- */
1099
- subscribe(e) {
1100
- this.currentHandler = e, this.apiManager.on("main-cam-control", e);
1101
- }
1102
- /**
1103
- * Отписывается от событий управления главной камерой
1104
- */
1105
- unsubscribe() {
1106
- this.currentHandler && (this.apiManager.off("main-cam-control", this.currentHandler), this.currentHandler = void 0);
1107
- }
1108
- }
1109
- class Kt {
1110
- eventHandler;
1111
- senderBalancer;
1112
- parametersSetterWithQueue;
1113
- getConnection;
1114
- serverHeaders;
1115
- trackMonitor;
1116
- constructor(e, t, {
1117
- ignoreForCodec: s,
1118
- onSetParameters: i,
1119
- pollIntervalMs: r
1120
- } = {}) {
1121
- this.getConnection = t, this.eventHandler = new Xt(e), this.parametersSetterWithQueue = new $t(i), this.senderBalancer = new Yt(
1122
- {
1123
- senderFinder: new zt(),
1124
- codecProvider: new Bt(),
1125
- parametersSetter: this.parametersSetterWithQueue
1126
- },
1127
- {
1128
- ignoreForCodec: s
1129
- }
1130
- ), this.trackMonitor = new jt({ pollIntervalMs: r });
1131
- }
1132
- /**
1133
- * Подписывается на события управления главной камерой
1134
- */
1135
- subscribe() {
1136
- this.eventHandler.subscribe(this.handleMainCamControl);
1137
- }
1138
- /**
1139
- * Отписывается от событий и сбрасывает состояние
1140
- */
1141
- unsubscribe() {
1142
- this.eventHandler.unsubscribe(), this.parametersSetterWithQueue.stop(), this.reset();
1143
- }
1144
- /**
1145
- * Сбрасывает состояние балансировщика
1146
- */
1147
- reset() {
1148
- delete this.serverHeaders, this.trackMonitor.unsubscribe();
1149
- }
1150
- /**
1151
- * Выполняет балансировку на основе текущего состояния
1152
- * @returns Promise с результатом балансировки
1153
- */
1154
- async balance() {
1155
- const e = this.getConnection();
1156
- if (!e)
1157
- throw new Error("connection is not exist");
1158
- const t = await this.senderBalancer.balance(e, this.serverHeaders);
1159
- return this.trackMonitor.subscribe(t.sender, () => {
1160
- this.balance().catch((s) => {
1161
- d("balance on track change: error", s);
1162
- });
1163
- }), t;
1164
- }
1165
- /**
1166
- * Обработчик событий управления главной камерой
1167
- * @param headers - Заголовки от сервера
1168
- */
1169
- handleMainCamControl = (e) => {
1170
- this.serverHeaders = e, this.balance().catch((t) => {
1171
- d("handleMainCamControl: error", t);
1172
- });
1173
- };
1174
- }
1175
- const Zt = 8e3, x = (n, e) => n.getSenders().filter((t) => t.track?.kind === e), en = (n) => n === "audio" ? Zt : Oe(), tn = (n) => n.track !== null;
1176
- class nn {
1177
- previousBitrates = /* @__PURE__ */ new Map();
1178
- /**
1179
- * Устанавливает минимальный битрейт для указанных типов потоков
1180
- * @param connection - активное RTCPeerConnection
1181
- * @param kinds - типы потоков ('audio' | 'video' | 'all')
1182
- */
1183
- async setMinBitrateForSenders(e, t = "all") {
1184
- const s = [];
1185
- if (!e)
1186
- return;
1187
- (t === "audio" || t === "all") && s.push(...x(e, "audio")), (t === "video" || t === "all") && s.push(...x(e, "video"));
1188
- const i = s.filter(tn).map(async (r) => {
1189
- const a = r.getParameters();
1190
- this.saveCurrentBitrate(r, a);
1191
- const o = {
1192
- ...a,
1193
- encodings: a.encodings.map((c) => ({
1194
- ...c,
1195
- maxBitrate: en(r.track.kind)
1196
- }))
1197
- };
1198
- await K(r, o);
1199
- });
1200
- await Promise.all(i);
1201
- }
1202
- /**
1203
- * Восстанавливает предыдущий битрейт для указанных типов потоков
1204
- * @param connection - активное RTCPeerConnection
1205
- * @param kinds - типы потоков ('audio' | 'video' | 'all')
1206
- */
1207
- async restoreBitrateForSenders(e, t = "all") {
1208
- const s = [];
1209
- if (!e)
1210
- return;
1211
- (t === "audio" || t === "all") && s.push(...x(e, "audio")), (t === "video" || t === "all") && s.push(...x(e, "video"));
1212
- const i = s.map(async (r) => {
1213
- const a = this.getSavedBitrate(r);
1214
- if (a) {
1215
- const c = {
1216
- ...r.getParameters(),
1217
- encodings: a
1218
- };
1219
- await K(r, c), this.clearSavedBitrate(r);
1220
- }
1221
- });
1222
- await Promise.all(i);
1223
- }
1224
- /**
1225
- * Получает сохраненные параметры битрейта для отправителя
1226
- */
1227
- getSavedBitrate(e) {
1228
- return this.previousBitrates.get(e);
1229
- }
1230
- /**
1231
- * Удаляет сохраненные параметры битрейта для отправителя
1232
- */
1233
- clearSavedBitrate(e) {
1234
- this.previousBitrates.delete(e);
1235
- }
1236
- /**
1237
- * Очищает все сохраненные состояния битрейта
1238
- */
1239
- clearAll() {
1240
- this.previousBitrates.clear();
1241
- }
1242
- /**
1243
- * Проверяет, есть ли сохраненное состояние для отправителя
1244
- */
1245
- hasSavedBitrate(e) {
1246
- return this.previousBitrates.has(e);
1247
- }
1248
- /**
1249
- * Возвращает количество сохраненных состояний
1250
- */
1251
- getSavedCount() {
1252
- return this.previousBitrates.size;
1253
- }
1254
- /**
1255
- * Сохраняет текущие параметры битрейта для отправителя
1256
- */
1257
- saveCurrentBitrate(e, t) {
1258
- const s = t.encodings.map((i) => ({ ...i }));
1259
- this.previousBitrates.set(e, s);
1260
- }
1261
- }
1262
- var De = /* @__PURE__ */ ((n) => (n.BYE = "Terminated", n.WEBRTC_ERROR = "WebRTC Error", n.CANCELED = "Canceled", n.REQUEST_TIMEOUT = "Request Timeout", n.REJECTED = "Rejected", n.REDIRECTED = "Redirected", n.UNAVAILABLE = "Unavailable", n.NOT_FOUND = "Not Found", n.ADDRESS_INCOMPLETE = "Address Incomplete", n.INCOMPATIBLE_SDP = "Incompatible SDP", n.BAD_MEDIA_DESCRIPTION = "Bad Media Description", n))(De || {});
1263
- class sn {
1264
- events;
1265
- rtcSession;
1266
- disposers = /* @__PURE__ */ new Set();
1267
- onReset;
1268
- // Менеджер состояния битрейта
1269
- bitrateStateManager = new nn();
1270
- constructor(e, { onReset: t }) {
1271
- this.events = e, this.onReset = t, e.on(E.FAILED, this.handleEnded), e.on(E.ENDED, this.handleEnded);
1272
- }
1273
- get connection() {
1274
- return this.rtcSession?.connection;
1275
- }
1276
- get isCallActive() {
1277
- return this.rtcSession?.isEstablished() === !0;
1278
- }
1279
- getEstablishedRTCSession = () => this.rtcSession?.isEstablished() === !0 ? this.rtcSession : void 0;
1280
- async renegotiate() {
1281
- if (this.rtcSession === void 0)
1282
- throw new Error("No rtcSession established");
1283
- return this.rtcSession.renegotiate();
956
+ getEstablishedRTCSession = () => this.rtcSession?.isEstablished() === !0 ? this.rtcSession : void 0;
957
+ async renegotiate() {
958
+ if (this.rtcSession === void 0)
959
+ throw new Error("No rtcSession established");
960
+ return this.rtcSession.renegotiate();
1284
961
  }
1285
962
  startCall = async (e, t, {
1286
963
  number: s,
@@ -1327,7 +1004,7 @@ class sn {
1327
1004
  const { rtcSession: e } = this;
1328
1005
  if (e && !e.isEnded())
1329
1006
  return e.terminateAsync({
1330
- cause: De.CANCELED
1007
+ cause: Me.CANCELED
1331
1008
  }).finally(() => {
1332
1009
  this.reset();
1333
1010
  });
@@ -1451,7 +1128,7 @@ class sn {
1451
1128
  delete this.rtcSession, this.unsubscribeFromSessionEvents(), this.bitrateStateManager.clearAll(), this.onReset();
1452
1129
  };
1453
1130
  }
1454
- class rn {
1131
+ class $t {
1455
1132
  config;
1456
1133
  tools;
1457
1134
  connection;
@@ -1504,18 +1181,18 @@ class rn {
1504
1181
  return this.connection.addTransceiver(e, t);
1505
1182
  }
1506
1183
  }
1507
- const Pe = (n) => n.getSettings(), an = (n, e) => {
1508
- const t = Pe(n);
1184
+ const _e = (n) => n.getSettings(), Gt = (n, e) => {
1185
+ const t = _e(n);
1509
1186
  let s = e;
1510
1187
  s ??= n.label;
1511
1188
  let i = t?.msid;
1512
1189
  return i ??= s, i ??= n.id, i;
1513
- }, on = (n, e) => {
1514
- const t = Pe(n);
1190
+ }, qt = (n, e) => {
1191
+ const t = _e(n);
1515
1192
  let s = e;
1516
1193
  return s ??= t?.msid, s ??= n.label, (s && s.length > 0 ? s : void 0) ?? n.id;
1517
1194
  };
1518
- class oe {
1195
+ class ae {
1519
1196
  participantGroups = /* @__PURE__ */ new Map();
1520
1197
  trackToGroup = /* @__PURE__ */ new Map();
1521
1198
  trackDisposers = /* @__PURE__ */ new Map();
@@ -1532,7 +1209,7 @@ class oe {
1532
1209
  onRemoved: t,
1533
1210
  streamHint: s
1534
1211
  } = {}) {
1535
- const i = on(e, s), r = an(e, s);
1212
+ const i = qt(e, s), r = Gt(e, s);
1536
1213
  if (this.trackToGroup.has(e.id))
1537
1214
  return { isAddedTrack: !1, isAddedStream: !1 };
1538
1215
  const a = this.getParticipantGroups(i), o = a.get(r), c = !o;
@@ -1600,16 +1277,16 @@ class oe {
1600
1277
  return this.participantGroups.set(e, s), s;
1601
1278
  }
1602
1279
  }
1603
- const X = {
1280
+ const j = {
1604
1281
  type: "participant"
1605
- }, cn = {
1282
+ }, Vt = {
1606
1283
  type: "spectator_synthetic"
1607
- }, dn = (n) => ({
1284
+ }, xt = (n) => ({
1608
1285
  type: "spectator",
1609
1286
  recvParams: n
1610
1287
  });
1611
1288
  class M {
1612
- role = X;
1289
+ role = j;
1613
1290
  onRoleChanged;
1614
1291
  constructor(e) {
1615
1292
  this.onRoleChanged = e;
@@ -1627,13 +1304,13 @@ class M {
1627
1304
  return this.role;
1628
1305
  }
1629
1306
  setCallRoleParticipant() {
1630
- this.changeRole(X);
1307
+ this.changeRole(j);
1631
1308
  }
1632
1309
  setCallRoleSpectatorSynthetic() {
1633
- this.changeRole(cn);
1310
+ this.changeRole(Vt);
1634
1311
  }
1635
1312
  setCallRoleSpectator(e) {
1636
- this.changeRole(dn(e));
1313
+ this.changeRole(xt(e));
1637
1314
  }
1638
1315
  changeRole(e) {
1639
1316
  const t = this.role;
@@ -1644,7 +1321,7 @@ class M {
1644
1321
  M.hasSpectator(e) && M.hasSpectator(t) && t.recvParams.audioId !== e.recvParams.audioId && this.setRole(e);
1645
1322
  }
1646
1323
  reset() {
1647
- this.role = X;
1324
+ this.role = j;
1648
1325
  }
1649
1326
  hasParticipant() {
1650
1327
  return M.hasParticipant(this.role);
@@ -1660,13 +1337,13 @@ class M {
1660
1337
  this.role = e, this.onRoleChanged?.({ previous: t, next: e });
1661
1338
  }
1662
1339
  }
1663
- const hn = (n, e) => {
1340
+ const Ht = (n, e) => {
1664
1341
  if (!n || !e)
1665
1342
  return n === e;
1666
1343
  const t = n.mainStream?.id, s = e.mainStream?.id, i = n.contentedStream?.id, r = e.contentedStream?.id;
1667
1344
  return t === s && i === r;
1668
1345
  };
1669
- class ln {
1346
+ class Wt {
1670
1347
  lastEmittedStreams;
1671
1348
  /**
1672
1349
  * Проверяет, изменились ли streams с последнего сохраненного состояния
@@ -1674,7 +1351,7 @@ class ln {
1674
1351
  * @returns true, если streams изменились
1675
1352
  */
1676
1353
  hasChanged(e) {
1677
- return !hn(this.lastEmittedStreams, e);
1354
+ return !Ht(this.lastEmittedStreams, e);
1678
1355
  }
1679
1356
  /**
1680
1357
  * Сохраняет текущие streams как последнее эмитнутое состояние
@@ -1697,8 +1374,8 @@ class ln {
1697
1374
  this.lastEmittedStreams = void 0;
1698
1375
  }
1699
1376
  }
1700
- const gn = "default", un = "dual", Tn = "content_", Sn = (n) => `${Tn}${n.toLowerCase()}`, En = (n) => [...n.getTracks()].some((e) => e.label.includes(un));
1701
- class mn {
1377
+ const Qt = "default", Yt = "dual", Jt = "content_", zt = (n) => `${Jt}${n.toLowerCase()}`, jt = (n) => [...n.getTracks()].some((e) => e.label.includes(Yt));
1378
+ class Xt {
1702
1379
  mainRemoteStreamsManager;
1703
1380
  recvRemoteStreamsManager;
1704
1381
  constructor(e, t) {
@@ -1715,7 +1392,7 @@ class mn {
1715
1392
  }) {
1716
1393
  const t = this.mainRemoteStreamsManager;
1717
1394
  return { manager: t, getRemoteStreams: () => {
1718
- const i = t.getStreams(), r = i.find((o) => !En(o)), a = e.isAvailable ? i.find((o) => o !== r) : void 0;
1395
+ const i = t.getStreams(), r = i.find((o) => !jt(o)), a = e.isAvailable ? i.find((o) => o !== r) : void 0;
1719
1396
  return { mainStream: r, contentedStream: a };
1720
1397
  } };
1721
1398
  }
@@ -1724,7 +1401,7 @@ class mn {
1724
1401
  }) {
1725
1402
  const t = this.recvRemoteStreamsManager;
1726
1403
  return { manager: t, getRemoteStreams: () => {
1727
- const r = t.getStreams(gn)[0], a = this.getRecvRemoteContentedStream({ stateInfo: e });
1404
+ const r = t.getStreams(Qt)[0], a = this.getRecvRemoteContentedStream({ stateInfo: e });
1728
1405
  return { mainStream: r, contentedStream: a };
1729
1406
  } };
1730
1407
  }
@@ -1733,20 +1410,20 @@ class mn {
1733
1410
  }) {
1734
1411
  if (!e.isAvailable || e.codec === void 0)
1735
1412
  return;
1736
- const t = Sn(e.codec);
1413
+ const t = zt(e.codec);
1737
1414
  return this.recvRemoteStreamsManager.getStreams(t)[0];
1738
1415
  }
1739
1416
  }
1740
- const ce = (n) => n.streams[0]?.id;
1741
- class pn {
1417
+ const oe = (n) => n.streams[0]?.id;
1418
+ class Kt {
1742
1419
  events;
1743
1420
  callStateMachine;
1744
1421
  isPendingCall = !1;
1745
1422
  isPendingAnswer = !1;
1746
1423
  rtcSession;
1747
1424
  conferenceStateManager;
1748
- mainRemoteStreamsManager = new oe();
1749
- recvRemoteStreamsManager = new oe();
1425
+ mainRemoteStreamsManager = new ae();
1426
+ recvRemoteStreamsManager = new ae();
1750
1427
  streamsManagerProvider;
1751
1428
  contentedStreamManager;
1752
1429
  roleManager = new M((e) => {
@@ -1755,9 +1432,9 @@ class pn {
1755
1432
  mcuSession;
1756
1433
  recvSession;
1757
1434
  disposeRecvSessionTrackListener;
1758
- streamsChangeTracker = new ln();
1435
+ streamsChangeTracker = new Wt();
1759
1436
  constructor(e, t) {
1760
- this.conferenceStateManager = e, this.contentedStreamManager = t, this.events = pt(), this.mcuSession = new sn(this.events, { onReset: this.reset }), this.callStateMachine = new St(this.events), this.streamsManagerProvider = new mn(
1437
+ this.conferenceStateManager = e, this.contentedStreamManager = t, this.events = mt(), this.mcuSession = new kt(this.events, { onReset: this.reset }), this.callStateMachine = new Tt(this.events), this.streamsManagerProvider = new Xt(
1761
1438
  this.mainRemoteStreamsManager,
1762
1439
  this.recvRemoteStreamsManager
1763
1440
  ), this.subscribeCallStatusChange(), this.subscribeMcuRemoteTrackEvents(), this.subscribeContentedStreamEvents();
@@ -1859,7 +1536,7 @@ class pn {
1859
1536
  }
1860
1537
  subscribeMcuRemoteTrackEvents() {
1861
1538
  this.on(E.PEER_CONNECTION_ONTRACK, (e) => {
1862
- this.addRemoteTrack(this.mainRemoteStreamsManager, e.track, ce(e));
1539
+ this.addRemoteTrack(this.mainRemoteStreamsManager, e.track, oe(e));
1863
1540
  });
1864
1541
  }
1865
1542
  addRemoteTrack(e, t, s) {
@@ -1912,7 +1589,7 @@ class pn {
1912
1589
  }
1913
1590
  attachRecvSessionTracks(e) {
1914
1591
  const { peerConnection: t } = e, s = (i) => {
1915
- this.addRemoteTrack(this.recvRemoteStreamsManager, i.track, ce(i));
1592
+ this.addRemoteTrack(this.recvRemoteStreamsManager, i.track, oe(i));
1916
1593
  };
1917
1594
  t.addEventListener("track", s), this.disposeRecvSessionTrackListener = () => {
1918
1595
  t.removeEventListener("track", s);
@@ -1926,7 +1603,7 @@ class pn {
1926
1603
  const i = {
1927
1604
  quality: "high",
1928
1605
  audioChannel: e
1929
- }, r = new rn(i, { sendOffer: t });
1606
+ }, r = new $t(i, { sendOffer: t });
1930
1607
  this.recvSession = r, this.recvRemoteStreamsManager.reset(), this.attachRecvSessionTracks(r), r.call(s).catch(() => {
1931
1608
  this.stopRecvSession();
1932
1609
  });
@@ -1961,15 +1638,15 @@ class pn {
1961
1638
  }
1962
1639
  }
1963
1640
  var P = /* @__PURE__ */ ((n) => (n.START_PRESENTATION = "presentation:start", n.STARTED_PRESENTATION = "presentation:started", n.END_PRESENTATION = "presentation:end", n.ENDED_PRESENTATION = "presentation:ended", n.FAILED_PRESENTATION = "presentation:failed", n))(P || {});
1964
- const ye = [
1641
+ const be = [
1965
1642
  "presentation:start",
1966
1643
  "presentation:started",
1967
1644
  "presentation:end",
1968
1645
  "presentation:ended",
1969
1646
  "presentation:failed"
1970
- ], Cn = () => new R(ye);
1971
- var Nn = /* @__PURE__ */ ((n) => (n.IDLE = "presentation:idle", n.STARTING = "presentation:starting", n.ACTIVE = "presentation:active", n.STOPPING = "presentation:stopping", n.FAILED = "presentation:failed", n))(Nn || {});
1972
- const An = G({
1647
+ ], Zt = () => new R(be);
1648
+ var en = /* @__PURE__ */ ((n) => (n.IDLE = "presentation:idle", n.STARTING = "presentation:starting", n.ACTIVE = "presentation:active", n.STOPPING = "presentation:stopping", n.FAILED = "presentation:failed", n))(en || {});
1649
+ const tn = G({
1973
1650
  types: {
1974
1651
  context: {},
1975
1652
  events: {}
@@ -2294,9 +1971,9 @@ const An = G({
2294
1971
  }
2295
1972
  }
2296
1973
  });
2297
- class Rn extends q {
1974
+ class nn extends q {
2298
1975
  constructor(e) {
2299
- super(An), this.subscribeCallEvents(e);
1976
+ super(tn), this.subscribeCallEvents(e);
2300
1977
  }
2301
1978
  get isIdle() {
2302
1979
  return this.state === "presentation:idle";
@@ -2366,8 +2043,8 @@ class Rn extends q {
2366
2043
  );
2367
2044
  }
2368
2045
  }
2369
- const In = 1, mi = (n) => et(n);
2370
- class vn {
2046
+ const sn = 1, pi = (n) => Ze(n);
2047
+ class rn {
2371
2048
  events;
2372
2049
  presentationStateMachine;
2373
2050
  promisePendingStartPresentation;
@@ -2380,7 +2057,7 @@ class vn {
2380
2057
  callManager: e,
2381
2058
  maxBitrate: t
2382
2059
  }) {
2383
- this.callManager = e, this.maxBitrate = t, this.events = Cn(), this.presentationStateMachine = new Rn(this.callManager.events), this.subscribe();
2060
+ this.callManager = e, this.maxBitrate = t, this.events = Zt(), this.presentationStateMachine = new nn(this.callManager.events), this.subscribe();
2384
2061
  }
2385
2062
  get presentationActor() {
2386
2063
  return this.presentationStateMachine.actorRef;
@@ -2478,7 +2155,7 @@ class vn {
2478
2155
  stream: s,
2479
2156
  presentationOptions: i,
2480
2157
  options: r = {
2481
- callLimit: In
2158
+ callLimit: sn
2482
2159
  }
2483
2160
  }) {
2484
2161
  const a = async () => this.sendPresentation(
@@ -2524,7 +2201,7 @@ class vn {
2524
2201
  if (!e || !t || s === void 0)
2525
2202
  return;
2526
2203
  const i = e.getSenders();
2527
- await wt(i, t, s);
2204
+ await yt(i, t, s);
2528
2205
  };
2529
2206
  getRtcSessionProtected = () => {
2530
2207
  const e = this.callManager.getEstablishedRTCSession();
@@ -2545,7 +2222,7 @@ class vn {
2545
2222
  delete this.streamPresentationCurrent;
2546
2223
  }
2547
2224
  }
2548
- class fn {
2225
+ class an {
2549
2226
  data;
2550
2227
  getUa;
2551
2228
  constructor(e) {
@@ -2632,7 +2309,7 @@ class fn {
2632
2309
  }
2633
2310
  }
2634
2311
  var m = /* @__PURE__ */ ((n) => (n.CONNECTING = "connecting", n.CONNECTED = "connected", n.DISCONNECTED = "disconnected", n.DISCONNECTING = "disconnecting", n.NEW_RTC_SESSION = "newRTCSession", n.REGISTERED = "registered", n.UNREGISTERED = "unregistered", n.REGISTRATION_FAILED = "registrationFailed", n.NEW_MESSAGE = "newMessage", n.SIP_EVENT = "sipEvent", n.CONNECT_STARTED = "connect-started", n.CONNECT_SUCCEEDED = "connect-succeeded", n.CONNECT_FAILED = "connect-failed", n.CONNECT_PARAMETERS_RESOLVE_SUCCESS = "connect-parameters-resolve-success", n.CONNECT_PARAMETERS_RESOLVE_FAILED = "connect-parameters-resolve-failed", n.CONNECTED_WITH_CONFIGURATION = "connected-with-configuration", n))(m || {});
2635
- const we = [
2312
+ const Oe = [
2636
2313
  "connecting",
2637
2314
  "connected",
2638
2315
  "disconnected",
@@ -2642,7 +2319,7 @@ const we = [
2642
2319
  "registrationFailed",
2643
2320
  "newMessage",
2644
2321
  "sipEvent"
2645
- ], Mn = [
2322
+ ], on = [
2646
2323
  "disconnecting",
2647
2324
  "connect-started",
2648
2325
  "connect-succeeded",
@@ -2650,12 +2327,12 @@ const we = [
2650
2327
  "connect-parameters-resolve-success",
2651
2328
  "connect-parameters-resolve-failed",
2652
2329
  "connected-with-configuration"
2653
- ], Le = [...we, ...Mn], _n = () => new R(Le);
2654
- function bn(n) {
2330
+ ], De = [...Oe, ...on], cn = () => new R(De);
2331
+ function dn(n) {
2655
2332
  return (e) => `sip:${e}@${n}`;
2656
2333
  }
2657
- const On = (n, e) => () => Math.floor(Math.random() * (e - n)) + n, Ue = (n) => n.trim().replaceAll(" ", "_"), Dn = On(1e5, 99999999), Pn = 3;
2658
- class yn {
2334
+ const hn = (n, e) => () => Math.floor(Math.random() * (e - n)) + n, Pe = (n) => n.trim().replaceAll(" ", "_"), ln = hn(1e5, 99999999), gn = 3;
2335
+ class un {
2659
2336
  cancelableConnectWithRepeatedCalls;
2660
2337
  JsSIP;
2661
2338
  events;
@@ -2681,7 +2358,7 @@ class yn {
2681
2358
  }
2682
2359
  let r = !1;
2683
2360
  const a = this.getConnectionConfiguration();
2684
- e !== void 0 && e !== a?.displayName && (r = i.set("display_name", Ue(e)), this.updateConnectionConfiguration("displayName", e));
2361
+ e !== void 0 && e !== a?.displayName && (r = i.set("display_name", Pe(e)), this.updateConnectionConfiguration("displayName", e));
2685
2362
  const o = r;
2686
2363
  o ? t(o) : s(new Error("nothing changed"));
2687
2364
  });
@@ -2699,9 +2376,9 @@ class yn {
2699
2376
  cancelRequests() {
2700
2377
  this.cancelConnectWithRepeatedCalls();
2701
2378
  }
2702
- connectWithDuplicatedCalls = async (e, { callLimit: t = Pn } = {}) => {
2379
+ connectWithDuplicatedCalls = async (e, { callLimit: t = gn } = {}) => {
2703
2380
  const s = async () => this.connectInner(e), i = (r) => {
2704
- const c = this.getUa()?.isConnected() === !0 && this.hasEqualConnectionConfiguration(e), h = r != null && !at(r);
2381
+ const c = this.getUa()?.isConnected() === !0 && this.hasEqualConnectionConfiguration(e), h = r != null && !rt(r);
2705
2382
  return c || h;
2706
2383
  };
2707
2384
  return this.stateMachine.startConnect(), this.cancelableConnectWithRepeatedCalls = Ee({
@@ -2809,8 +2486,8 @@ class yn {
2809
2486
  });
2810
2487
  }
2811
2488
  }
2812
- var wn = /* @__PURE__ */ ((n) => (n.IDLE = "connection:idle", n.PREPARING = "connection:preparing", n.CONNECTING = "connection:connecting", n.CONNECTED = "connection:connected", n.REGISTERED = "connection:registered", n.ESTABLISHED = "connection:established", n.DISCONNECTED = "connection:disconnected", n.FAILED = "connection:failed", n))(wn || {}), Fe = /* @__PURE__ */ ((n) => (n.START_CONNECT = "START_CONNECT", n.START_INIT_UA = "START_INIT_UA", n.UA_CONNECTED = "UA_CONNECTED", n.UA_REGISTERED = "UA_REGISTERED", n.UA_UNREGISTERED = "UA_UNREGISTERED", n.UA_DISCONNECTED = "UA_DISCONNECTED", n.CONNECTION_FAILED = "CONNECTION_FAILED", n.RESET = "RESET", n))(Fe || {});
2813
- const Ln = Object.values(Fe), Un = G({
2489
+ var Tn = /* @__PURE__ */ ((n) => (n.IDLE = "connection:idle", n.PREPARING = "connection:preparing", n.CONNECTING = "connection:connecting", n.CONNECTED = "connection:connected", n.REGISTERED = "connection:registered", n.ESTABLISHED = "connection:established", n.DISCONNECTED = "connection:disconnected", n.FAILED = "connection:failed", n))(Tn || {}), ye = /* @__PURE__ */ ((n) => (n.START_CONNECT = "START_CONNECT", n.START_INIT_UA = "START_INIT_UA", n.UA_CONNECTED = "UA_CONNECTED", n.UA_REGISTERED = "UA_REGISTERED", n.UA_UNREGISTERED = "UA_UNREGISTERED", n.UA_DISCONNECTED = "UA_DISCONNECTED", n.CONNECTION_FAILED = "CONNECTION_FAILED", n.RESET = "RESET", n))(ye || {});
2490
+ const Sn = Object.values(ye), En = G({
2814
2491
  types: {
2815
2492
  context: {},
2816
2493
  events: {}
@@ -3190,11 +2867,11 @@ const Ln = Object.values(Fe), Un = G({
3190
2867
  }
3191
2868
  }
3192
2869
  });
3193
- class Fn extends q {
2870
+ class mn extends q {
3194
2871
  events;
3195
2872
  unsubscribeFromEvents;
3196
2873
  constructor(e) {
3197
- super(Un), this.events = e, this.subscribeToEvents();
2874
+ super(En), this.events = e, this.subscribeToEvents();
3198
2875
  }
3199
2876
  get isIdle() {
3200
2877
  return this.hasState(
@@ -3276,7 +2953,7 @@ class Fn extends q {
3276
2953
  return this.getSnapshot().can({ type: e });
3277
2954
  }
3278
2955
  getValidEvents() {
3279
- return Ln.filter((e) => this.canTransition(e));
2956
+ return Sn.filter((e) => this.canTransition(e));
3280
2957
  }
3281
2958
  hasState(e) {
3282
2959
  return this.getSnapshot().matches(e);
@@ -3348,7 +3025,7 @@ class Fn extends q {
3348
3025
  this.toFailed(e instanceof Error ? e : void 0);
3349
3026
  };
3350
3027
  }
3351
- class Bn {
3028
+ class pn {
3352
3029
  events;
3353
3030
  getUaProtected;
3354
3031
  constructor(e) {
@@ -3385,7 +3062,7 @@ class Bn {
3385
3062
  };
3386
3063
  }
3387
3064
  }
3388
- class kn {
3065
+ class Cn {
3389
3066
  uaFactory;
3390
3067
  getUaProtected;
3391
3068
  constructor(e) {
@@ -3450,7 +3127,7 @@ class kn {
3450
3127
  });
3451
3128
  }
3452
3129
  }
3453
- const $n = (n) => {
3130
+ const Nn = (n) => {
3454
3131
  const e = [];
3455
3132
  return n !== void 0 && n !== "" && e.push(`X-Vinteo-Remote: ${n}`), e;
3456
3133
  };
@@ -3479,10 +3156,10 @@ class F {
3479
3156
  throw new Error("user is required for authorized connection");
3480
3157
  }
3481
3158
  static resolveAuthorizationUser(e, t) {
3482
- return e && t !== void 0 && t.trim() !== "" ? t.trim() : `${Dn()}`;
3159
+ return e && t !== void 0 && t.trim() !== "" ? t.trim() : `${ln()}`;
3483
3160
  }
3484
3161
  static buildExtraHeaders(e, t) {
3485
- const s = e !== void 0 && e !== "" ? $n(e) : [];
3162
+ const s = e !== void 0 && e !== "" ? Nn(e) : [];
3486
3163
  return t === void 0 ? s : [...s, ...t];
3487
3164
  }
3488
3165
  createConfiguration({
@@ -3506,13 +3183,13 @@ class F {
3506
3183
  sipServerIp: r,
3507
3184
  sipServerUrl: s
3508
3185
  });
3509
- const S = F.resolveAuthorizationUser(a, e), C = bn(r), D = C(S), A = new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);
3186
+ const S = F.resolveAuthorizationUser(a, e), C = dn(r), D = C(S), A = new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);
3510
3187
  return {
3511
3188
  configuration: {
3512
3189
  password: t,
3513
3190
  register: a,
3514
3191
  uri: D,
3515
- display_name: Ue(i),
3192
+ display_name: Pe(i),
3516
3193
  user_agent: u,
3517
3194
  sdpSemantics: "unified-plan",
3518
3195
  sockets: [A],
@@ -3541,13 +3218,13 @@ class F {
3541
3218
  extraHeaders: e.extraHeaders
3542
3219
  });
3543
3220
  return t.eachTriggers((a, o) => {
3544
- const c = we.find((h) => h === o);
3221
+ const c = Oe.find((h) => h === o);
3545
3222
  c && r.on(c, a);
3546
3223
  }), { ua: r, helpers: i };
3547
3224
  }
3548
3225
  }
3549
- const Be = "Not ready for connection", Gn = (n) => n instanceof Error && n.message === Be, qn = () => new Error(Be), Vn = async (n) => typeof n == "function" ? n() : n;
3550
- class xn {
3226
+ const we = "Not ready for connection", An = (n) => n instanceof Error && n.message === we, Rn = () => new Error(we), In = async (n) => typeof n == "function" ? n() : n;
3227
+ class vn {
3551
3228
  events;
3552
3229
  ua;
3553
3230
  socket;
@@ -3559,15 +3236,15 @@ class xn {
3559
3236
  configurationManager;
3560
3237
  JsSIP;
3561
3238
  constructor({ JsSIP: e }) {
3562
- this.JsSIP = e, this.events = _n(), this.uaFactory = new F(e), this.registrationManager = new Bn({
3239
+ this.JsSIP = e, this.events = cn(), this.uaFactory = new F(e), this.registrationManager = new pn({
3563
3240
  events: this.events,
3564
3241
  getUaProtected: this.getUaProtected
3565
- }), this.stateMachine = new Fn(this.events), this.configurationManager = new fn({
3242
+ }), this.stateMachine = new mn(this.events), this.configurationManager = new an({
3566
3243
  getUa: this.getUa
3567
- }), this.sipOperations = new kn({
3244
+ }), this.sipOperations = new Cn({
3568
3245
  uaFactory: this.uaFactory,
3569
3246
  getUaProtected: this.getUaProtected
3570
- }), this.connectionFlow = new yn({
3247
+ }), this.connectionFlow = new un({
3571
3248
  JsSIP: this.JsSIP,
3572
3249
  events: this.events,
3573
3250
  uaFactory: this.uaFactory,
@@ -3672,7 +3349,7 @@ class xn {
3672
3349
  getUa = () => this.ua;
3673
3350
  connectWithProcessError = async (e, t) => {
3674
3351
  if (!(t?.hasReadyForConnection?.() ?? !0))
3675
- throw qn();
3352
+ throw Rn();
3676
3353
  return this.processConnect(e, t).catch(async (i) => {
3677
3354
  const r = i;
3678
3355
  return this.disconnect().then(() => {
@@ -3682,7 +3359,7 @@ class xn {
3682
3359
  });
3683
3360
  });
3684
3361
  };
3685
- processConnect = async (e, t) => (this.events.trigger(m.CONNECT_STARTED, {}), Vn(e).then((s) => (this.events.trigger(m.CONNECT_PARAMETERS_RESOLVE_SUCCESS, s), s)).catch((s) => {
3362
+ processConnect = async (e, t) => (this.events.trigger(m.CONNECT_STARTED, {}), In(e).then((s) => (this.events.trigger(m.CONNECT_PARAMETERS_RESOLVE_SUCCESS, s), s)).catch((s) => {
3686
3363
  throw this.events.trigger(m.CONNECT_PARAMETERS_RESOLVE_FAILED, s), s;
3687
3364
  }).then(async (s) => this.connectionFlow.connect(s, t)).then((s) => (this.events.trigger(m.CONNECT_SUCCEEDED, {
3688
3365
  ...s
@@ -3691,7 +3368,7 @@ class xn {
3691
3368
  throw this.events.trigger(m.CONNECT_FAILED, i), i;
3692
3369
  }));
3693
3370
  }
3694
- class Hn {
3371
+ class fn {
3695
3372
  connectionManager;
3696
3373
  stackPromises = me({
3697
3374
  noRunIsNotActual: !0
@@ -3705,11 +3382,11 @@ class Hn {
3705
3382
  this.stackPromises.stop();
3706
3383
  }
3707
3384
  }
3708
- const de = 0, Wn = 30;
3709
- class Qn {
3710
- countInner = de;
3711
- initialCount = de;
3712
- limitInner = Wn;
3385
+ const ce = 0, Mn = 30;
3386
+ class _n {
3387
+ countInner = ce;
3388
+ initialCount = ce;
3389
+ limitInner = Mn;
3713
3390
  isInProgress = !1;
3714
3391
  onStatusChange;
3715
3392
  constructor({
@@ -3742,7 +3419,7 @@ class Qn {
3742
3419
  this.countInner = this.initialCount, this.finishAttempt();
3743
3420
  }
3744
3421
  }
3745
- class Yn {
3422
+ class bn {
3746
3423
  connectionManager;
3747
3424
  interval;
3748
3425
  checkTelephonyByTimeout = void 0;
@@ -3758,7 +3435,7 @@ class Yn {
3758
3435
  onSuccessRequest: t,
3759
3436
  onFailRequest: s
3760
3437
  }) {
3761
- this.stop(), this.cancelableBeforeRequest = new J(e), this.checkTelephonyByTimeout = je({
3438
+ this.stop(), this.cancelableBeforeRequest = new J(e), this.checkTelephonyByTimeout = ze({
3762
3439
  isDontStopOnFail: !0,
3763
3440
  requestInterval: this.interval,
3764
3441
  request: async () => {
@@ -3779,7 +3456,7 @@ class Yn {
3779
3456
  }
3780
3457
  }
3781
3458
  var v = /* @__PURE__ */ ((n) => (n.BEFORE_ATTEMPT = "before-attempt", n.SUCCESS = "success", n.FAILED_ALL_ATTEMPTS = "failed-all-attempts", n.CANCELLED_ATTEMPTS = "cancelled-attempts", n.CHANGED_ATTEMPT_STATUS = "changed-attempt-status", n.STOP_ATTEMPTS_BY_ERROR = "stop-attempts-by-error", n.LIMIT_REACHED_ATTEMPTS = "limit-reached-attempts", n))(v || {});
3782
- const ke = [
3459
+ const Le = [
3783
3460
  "before-attempt",
3784
3461
  "success",
3785
3462
  "failed-all-attempts",
@@ -3787,8 +3464,8 @@ const ke = [
3787
3464
  "changed-attempt-status",
3788
3465
  "stop-attempts-by-error",
3789
3466
  "limit-reached-attempts"
3790
- ], Jn = () => new R(ke);
3791
- class ie {
3467
+ ], On = () => new R(Le);
3468
+ class se {
3792
3469
  callManager;
3793
3470
  disposers = [];
3794
3471
  constructor({ callManager: e }) {
@@ -3813,15 +3490,15 @@ class ie {
3813
3490
  this.callManager.isCallActive ? e?.() : t();
3814
3491
  }
3815
3492
  }
3816
- const zn = 15e3, jn = 2;
3817
- class Xn {
3493
+ const Dn = 15e3, Pn = 2;
3494
+ class yn {
3818
3495
  connectionManager;
3819
3496
  pingServerByTimeoutWithFailCalls;
3820
3497
  constructor({ connectionManager: e }) {
3821
- this.connectionManager = e, this.pingServerByTimeoutWithFailCalls = Xe(jn, {
3498
+ this.connectionManager = e, this.pingServerByTimeoutWithFailCalls = je(Pn, {
3822
3499
  whenPossibleRequest: async () => {
3823
3500
  },
3824
- requestInterval: zn,
3501
+ requestInterval: Dn,
3825
3502
  request: async () => (d("ping"), this.connectionManager.ping().then(() => {
3826
3503
  d("ping success");
3827
3504
  }))
@@ -3834,16 +3511,16 @@ class Xn {
3834
3511
  this.pingServerByTimeoutWithFailCalls.stop();
3835
3512
  }
3836
3513
  }
3837
- class Kn {
3514
+ class wn {
3838
3515
  pingServerRequester;
3839
3516
  notActiveCallSubscriber;
3840
3517
  constructor({
3841
3518
  connectionManager: e,
3842
3519
  callManager: t
3843
3520
  }) {
3844
- this.pingServerRequester = new Xn({
3521
+ this.pingServerRequester = new yn({
3845
3522
  connectionManager: e
3846
- }), this.notActiveCallSubscriber = new ie({ callManager: t });
3523
+ }), this.notActiveCallSubscriber = new se({ callManager: t });
3847
3524
  }
3848
3525
  start({ onFailRequest: e }) {
3849
3526
  d("start"), this.notActiveCallSubscriber.subscribe({
@@ -3862,7 +3539,7 @@ class Kn {
3862
3539
  this.notActiveCallSubscriber.unsubscribe();
3863
3540
  }
3864
3541
  }
3865
- class Zn {
3542
+ class Ln {
3866
3543
  connectionManager;
3867
3544
  isRegistrationFailed = !1;
3868
3545
  disposers = [];
@@ -3871,7 +3548,7 @@ class Zn {
3871
3548
  connectionManager: e,
3872
3549
  callManager: t
3873
3550
  }) {
3874
- this.connectionManager = e, this.notActiveCallSubscriber = new ie({ callManager: t });
3551
+ this.connectionManager = e, this.notActiveCallSubscriber = new se({ callManager: t });
3875
3552
  }
3876
3553
  subscribe(e) {
3877
3554
  this.unsubscribe(), this.disposers.push(
@@ -3898,12 +3575,12 @@ class Zn {
3898
3575
  this.isRegistrationFailed = !1;
3899
3576
  }
3900
3577
  }
3901
- const es = 3e3, ts = 15e3, he = {
3578
+ const Un = 3e3, Fn = 15e3, de = {
3902
3579
  LIMIT_REACHED: "Limit reached",
3903
3580
  FAILED_TO_RECONNECT: "Failed to reconnect"
3904
- }, ns = async () => {
3905
- }, ss = (n) => !0;
3906
- class is {
3581
+ }, Bn = async () => {
3582
+ }, kn = (n) => !0;
3583
+ class $n {
3907
3584
  events;
3908
3585
  connectionManager;
3909
3586
  connectionQueueManager;
@@ -3923,21 +3600,21 @@ class is {
3923
3600
  connectionManager: t,
3924
3601
  callManager: s
3925
3602
  }, i) {
3926
- const r = i?.onBeforeRetry ?? ns, a = i?.canRetryOnError ?? ss;
3927
- this.connectionQueueManager = e, this.connectionManager = t, this.onBeforeRetry = r, this.canRetryOnError = a, this.networkInterfacesSubscriber = i?.networkInterfacesSubscriber, this.resumeFromSleepModeSubscriber = i?.resumeFromSleepModeSubscriber, this.events = Jn(), this.checkTelephonyRequester = new Yn({
3603
+ const r = i?.onBeforeRetry ?? Bn, a = i?.canRetryOnError ?? kn;
3604
+ this.connectionQueueManager = e, this.connectionManager = t, this.onBeforeRetry = r, this.canRetryOnError = a, this.networkInterfacesSubscriber = i?.networkInterfacesSubscriber, this.resumeFromSleepModeSubscriber = i?.resumeFromSleepModeSubscriber, this.events = On(), this.checkTelephonyRequester = new bn({
3928
3605
  connectionManager: t,
3929
- interval: i?.checkTelephonyRequestInterval ?? ts
3930
- }), this.pingServerIfNotActiveCallRequester = new Kn({
3606
+ interval: i?.checkTelephonyRequestInterval ?? Fn
3607
+ }), this.pingServerIfNotActiveCallRequester = new wn({
3931
3608
  connectionManager: t,
3932
3609
  callManager: s
3933
- }), this.registrationFailedOutOfCallSubscriber = new Zn({
3610
+ }), this.registrationFailedOutOfCallSubscriber = new Ln({
3934
3611
  connectionManager: t,
3935
3612
  callManager: s
3936
- }), this.attemptsState = new Qn({
3613
+ }), this.attemptsState = new _n({
3937
3614
  onStatusChange: this.emitStatusChange
3938
- }), this.cancelableRequestBeforeRetry = new J(r), this.delayBetweenAttempts = new Ke(
3939
- i?.timeoutBetweenAttempts ?? es
3940
- ), this.notActiveCallSubscriber = new ie({ callManager: s });
3615
+ }), this.cancelableRequestBeforeRetry = new J(r), this.delayBetweenAttempts = new Xe(
3616
+ i?.timeoutBetweenAttempts ?? Un
3617
+ ), this.notActiveCallSubscriber = new se({ callManager: s });
3941
3618
  }
3942
3619
  start(e) {
3943
3620
  d("auto connector start"), this.restartConnectionAttempts(e), this.subscribeToNotActiveCall(e);
@@ -4002,7 +3679,7 @@ class is {
4002
3679
  }
4003
3680
  }
4004
3681
  handleConnectionError(e, t) {
4005
- if (Gn(e)) {
3682
+ if (An(e)) {
4006
3683
  this.attemptsState.finishAttempt(), this.events.trigger(v.STOP_ATTEMPTS_BY_ERROR, e);
4007
3684
  return;
4008
3685
  }
@@ -4010,14 +3687,14 @@ class is {
4010
3687
  d("executeConnectionAttempt: error does not allow retry", e), this.attemptsState.finishAttempt(), this.events.trigger(v.STOP_ATTEMPTS_BY_ERROR, e);
4011
3688
  return;
4012
3689
  }
4013
- if (nt(e)) {
3690
+ if (tt(e)) {
4014
3691
  d("executeConnectionAttempt: not actual error", e), this.attemptsState.finishAttempt(), this.events.trigger(v.CANCELLED_ATTEMPTS, e);
4015
3692
  return;
4016
3693
  }
4017
3694
  d("executeConnectionAttempt: error", e), this.scheduleReconnect(t);
4018
3695
  }
4019
3696
  handleLimitReached(e) {
4020
- this.attemptsState.finishAttempt(), this.events.trigger(v.LIMIT_REACHED_ATTEMPTS, new Error(he.LIMIT_REACHED)), this.startCheckTelephony(e);
3697
+ this.attemptsState.finishAttempt(), this.events.trigger(v.LIMIT_REACHED_ATTEMPTS, new Error(de.LIMIT_REACHED)), this.startCheckTelephony(e);
4021
3698
  }
4022
3699
  handleSucceededAttempt(e) {
4023
3700
  d("handleSucceededAttempt"), this.subscribeToConnectTriggers(e), this.events.trigger(v.SUCCESS);
@@ -4078,8 +3755,8 @@ class is {
4078
3755
  }
4079
3756
  scheduleReconnect(e) {
4080
3757
  d("scheduleReconnect"), this.delayBetweenAttempts.request().then(async () => (d("scheduleReconnect: delayBetweenAttempts success"), this.cancelableRequestBeforeRetry.request())).then(async () => (d("scheduleReconnect: onBeforeRetry success"), this.attemptConnection(e))).catch((t) => {
4081
- const s = t instanceof Error ? t : new Error(he.FAILED_TO_RECONNECT);
4082
- this.attemptsState.finishAttempt(), ze(t) || Ze(t) ? this.events.trigger(v.CANCELLED_ATTEMPTS, s) : this.events.trigger(v.FAILED_ALL_ATTEMPTS, s), d("scheduleReconnect: error", t);
3758
+ const s = t instanceof Error ? t : new Error(de.FAILED_TO_RECONNECT);
3759
+ this.attemptsState.finishAttempt(), Je(t) || Ke(t) ? this.events.trigger(v.CANCELLED_ATTEMPTS, s) : this.events.trigger(v.FAILED_ALL_ATTEMPTS, s), d("scheduleReconnect: error", t);
4083
3760
  });
4084
3761
  }
4085
3762
  isConnectionUnavailable() {
@@ -4091,12 +3768,12 @@ class is {
4091
3768
  };
4092
3769
  }
4093
3770
  var Z = /* @__PURE__ */ ((n) => (n.STATE_CHANGED = "state-changed", n.STATE_RESET = "state-reset", n))(Z || {});
4094
- const $e = ["state-changed", "state-reset"], rs = () => new R($e);
4095
- class as {
3771
+ const Ue = ["state-changed", "state-reset"], Gn = () => new R(Ue);
3772
+ class qn {
4096
3773
  events;
4097
3774
  state = {};
4098
3775
  constructor() {
4099
- this.events = rs();
3776
+ this.events = Gn();
4100
3777
  }
4101
3778
  getState() {
4102
3779
  return { ...this.state };
@@ -4146,7 +3823,7 @@ class as {
4146
3823
  this.events.off(e, t);
4147
3824
  }
4148
3825
  }
4149
- const os = G({
3826
+ const Vn = G({
4150
3827
  types: {
4151
3828
  context: {},
4152
3829
  events: {}
@@ -4187,9 +3864,9 @@ const os = G({
4187
3864
  }
4188
3865
  }
4189
3866
  });
4190
- class cs extends q {
3867
+ class xn extends q {
4191
3868
  constructor() {
4192
- super(os);
3869
+ super(Vn);
4193
3870
  }
4194
3871
  get isAvailable() {
4195
3872
  return this.state === "contented-stream:available";
@@ -4231,16 +3908,16 @@ class cs extends q {
4231
3908
  }
4232
3909
  }
4233
3910
  var ee = /* @__PURE__ */ ((n) => (n.AVAILABLE = "available", n.NOT_AVAILABLE = "not-available", n))(ee || {});
4234
- const ds = [
3911
+ const Hn = [
4235
3912
  "available",
4236
3913
  "not-available"
4237
3914
  /* NOT_AVAILABLE */
4238
- ], hs = () => new R(ds);
4239
- class ls {
3915
+ ], Wn = () => new R(Hn);
3916
+ class Qn {
4240
3917
  events;
4241
3918
  stateMachine;
4242
3919
  constructor() {
4243
- this.events = hs(), this.stateMachine = new cs(), this.proxyEvents();
3920
+ this.events = Wn(), this.stateMachine = new xn(), this.proxyEvents();
4244
3921
  }
4245
3922
  get isAvailable() {
4246
3923
  return this.stateMachine.isAvailable;
@@ -4274,14 +3951,14 @@ class ls {
4274
3951
  }
4275
3952
  }
4276
3953
  var k = /* @__PURE__ */ ((n) => (n.RINGING = "ringing", n.DECLINED_INCOMING_CALL = "declinedIncomingCall", n.TERMINATED_INCOMING_CALL = "terminatedIncomingCall", n.FAILED_INCOMING_CALL = "failedIncomingCall", n))(k || {});
4277
- const Ge = [
3954
+ const Fe = [
4278
3955
  "ringing",
4279
3956
  "declinedIncomingCall",
4280
3957
  "terminatedIncomingCall",
4281
3958
  "failedIncomingCall"
4282
- ], gs = () => new R(Ge);
4283
- var us = /* @__PURE__ */ ((n) => (n.IDLE = "incoming:idle", n.RINGING = "incoming:ringing", n.CONSUMED = "incoming:consumed", n.DECLINED = "incoming:declined", n.TERMINATED = "incoming:terminated", n.FAILED = "incoming:failed", n))(us || {});
4284
- const Ts = G({
3959
+ ], Yn = () => new R(Fe);
3960
+ var Jn = /* @__PURE__ */ ((n) => (n.IDLE = "incoming:idle", n.RINGING = "incoming:ringing", n.CONSUMED = "incoming:consumed", n.DECLINED = "incoming:declined", n.TERMINATED = "incoming:terminated", n.FAILED = "incoming:failed", n))(Jn || {});
3961
+ const zn = G({
4285
3962
  types: {
4286
3963
  context: {},
4287
3964
  events: {}
@@ -4613,9 +4290,9 @@ const Ts = G({
4613
4290
  }
4614
4291
  }
4615
4292
  });
4616
- class Ss extends q {
4293
+ class jn extends q {
4617
4294
  constructor({ incomingEvents: e, connectionEvents: t }) {
4618
- super(Ts), this.subscribeIncomingEvents(e), this.subscribeConnectionEvents(t);
4295
+ super(zn), this.subscribeIncomingEvents(e), this.subscribeConnectionEvents(t);
4619
4296
  }
4620
4297
  get isIdle() {
4621
4298
  return this.state === "incoming:idle";
@@ -4700,14 +4377,14 @@ class Ss extends q {
4700
4377
  this.send({ type: "INCOMING.CLEAR" });
4701
4378
  }
4702
4379
  }
4703
- const Es = 486, ms = 487;
4704
- class ps {
4380
+ const Xn = 486, Kn = 487;
4381
+ class Zn {
4705
4382
  events;
4706
4383
  incomingStateMachine;
4707
4384
  incomingRTCSession;
4708
4385
  connectionManager;
4709
4386
  constructor(e) {
4710
- this.connectionManager = e, this.events = gs(), this.incomingStateMachine = new Ss({
4387
+ this.connectionManager = e, this.events = Yn(), this.incomingStateMachine = new jn({
4711
4388
  incomingEvents: this.events,
4712
4389
  connectionEvents: this.connectionManager.events
4713
4390
  }), this.start();
@@ -4743,7 +4420,7 @@ class ps {
4743
4420
  return this.incomingStateMachine.toConsumed(), this.removeIncomingSession(), e;
4744
4421
  };
4745
4422
  async declineToIncomingCall({
4746
- statusCode: e = ms
4423
+ statusCode: e = Kn
4747
4424
  } = {}) {
4748
4425
  return new Promise((t, s) => {
4749
4426
  try {
@@ -4755,7 +4432,7 @@ class ps {
4755
4432
  });
4756
4433
  }
4757
4434
  async busyIncomingCall() {
4758
- return this.declineToIncomingCall({ statusCode: Es });
4435
+ return this.declineToIncomingCall({ statusCode: Xn });
4759
4436
  }
4760
4437
  on(e, t) {
4761
4438
  return this.events.on(e, t);
@@ -4795,26 +4472,26 @@ class ps {
4795
4472
  delete this.incomingRTCSession;
4796
4473
  }
4797
4474
  }
4798
- var qe = /* @__PURE__ */ ((n) => (n.SNAPSHOT_CHANGED = "snapshot-changed", n))(qe || {});
4799
- const Ve = ["snapshot-changed"], Cs = () => new R(Ve), Ns = (n, e) => Object.is(n, e), le = (n) => ({
4475
+ var Be = /* @__PURE__ */ ((n) => (n.SNAPSHOT_CHANGED = "snapshot-changed", n))(Be || {});
4476
+ const ke = ["snapshot-changed"], es = () => new R(ke), ts = (n, e) => Object.is(n, e), he = (n) => ({
4800
4477
  connection: n.connection.getSnapshot(),
4801
4478
  call: n.call.getSnapshot(),
4802
4479
  incoming: n.incoming.getSnapshot(),
4803
4480
  presentation: n.presentation.getSnapshot()
4804
4481
  });
4805
- class As {
4482
+ class ns {
4806
4483
  events;
4807
4484
  actors;
4808
4485
  currentSnapshot;
4809
4486
  subscribers = /* @__PURE__ */ new Set();
4810
4487
  actorSubscriptions = [];
4811
4488
  constructor(e) {
4812
- this.events = Cs(), this.actors = {
4489
+ this.events = es(), this.actors = {
4813
4490
  connection: e.connectionManager.connectionActor,
4814
4491
  call: e.callManager.callActor,
4815
4492
  incoming: e.incomingCallManager.incomingActor,
4816
4493
  presentation: e.presentationManager.presentationActor
4817
- }, this.currentSnapshot = le(this.actors), this.actorSubscriptions.push(
4494
+ }, this.currentSnapshot = he(this.actors), this.actorSubscriptions.push(
4818
4495
  this.actors.connection.subscribe(this.notifySubscribers),
4819
4496
  this.actors.call.subscribe(this.notifySubscribers),
4820
4497
  this.actors.incoming.subscribe(this.notifySubscribers),
@@ -4825,7 +4502,7 @@ class As {
4825
4502
  return this.currentSnapshot;
4826
4503
  }
4827
4504
  subscribe(e, t, s) {
4828
- const i = typeof t == "function", r = i ? e : (T) => T, a = i ? t : e, o = (i ? s : void 0) ?? Ns, c = r(this.currentSnapshot), h = {
4505
+ const i = typeof t == "function", r = i ? e : (T) => T, a = i ? t : e, o = (i ? s : void 0) ?? ts, c = r(this.currentSnapshot), h = {
4829
4506
  selector: r,
4830
4507
  listener: a,
4831
4508
  equals: o,
@@ -4848,12 +4525,12 @@ class As {
4848
4525
  }
4849
4526
  notifySubscribers = () => {
4850
4527
  const e = this.currentSnapshot;
4851
- this.currentSnapshot = le(this.actors);
4528
+ this.currentSnapshot = he(this.actors);
4852
4529
  for (const t of this.subscribers) {
4853
4530
  const s = t.selector(this.currentSnapshot);
4854
4531
  t.equals(t.current, s) || (t.current = s, t.listener(s));
4855
4532
  }
4856
- this.events.trigger(qe.SNAPSHOT_CHANGED, {
4533
+ this.events.trigger(Be.SNAPSHOT_CHANGED, {
4857
4534
  previous: e,
4858
4535
  current: this.currentSnapshot
4859
4536
  });
@@ -4861,10 +4538,10 @@ class As {
4861
4538
  }
4862
4539
  const B = 1e3;
4863
4540
  var p = /* @__PURE__ */ ((n) => (n.INBOUND_RTP = "inbound-rtp", n.REMOTE_OUTBOUND_RTP = "remote-outbound-rtp", n.MEDIA_SOURCE = "media-source", n.OUTBOUND_RTP = "outbound-rtp", n.REMOTE_INBOUND_RTP = "remote-inbound-rtp", n.CODEC = "codec", n.CANDIDATE_PAIR = "candidate-pair", n.CERTIFICATE = "certificate", n.TRANSPORT = "transport", n.LOCAL_CANDIDATE = "local-candidate", n.REMOTE_CANDIDATE = "remote-candidate", n))(p || {});
4864
- const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in window ? performance.now() : Date.now(), V = (n) => [...n.keys()].reduce((e, t) => {
4541
+ const $e = ["collected"], ss = () => new R($e), le = () => "performance" in window ? performance.now() : Date.now(), V = (n) => [...n.keys()].reduce((e, t) => {
4865
4542
  const s = n.get(t);
4866
4543
  return s === void 0 ? e : { ...e, [s.type]: s };
4867
- }, {}), Is = (n) => {
4544
+ }, {}), is = (n) => {
4868
4545
  if (!n)
4869
4546
  return {
4870
4547
  outboundRtp: void 0,
@@ -4879,7 +4556,7 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
4879
4556
  mediaSource: e[p.MEDIA_SOURCE],
4880
4557
  remoteInboundRtp: e[p.REMOTE_INBOUND_RTP]
4881
4558
  };
4882
- }, ue = (n) => {
4559
+ }, ge = (n) => {
4883
4560
  if (!n)
4884
4561
  return {
4885
4562
  outboundRtp: void 0,
@@ -4894,7 +4571,7 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
4894
4571
  mediaSource: e[p.MEDIA_SOURCE],
4895
4572
  remoteInboundRtp: e[p.REMOTE_INBOUND_RTP]
4896
4573
  };
4897
- }, Te = ({
4574
+ }, ue = ({
4898
4575
  videoReceiversStats: n,
4899
4576
  synchronizationSourcesVideo: e
4900
4577
  }) => {
@@ -4910,7 +4587,7 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
4910
4587
  codec: t[p.CODEC],
4911
4588
  synchronizationSources: e
4912
4589
  };
4913
- }, vs = ({
4590
+ }, rs = ({
4914
4591
  audioReceiverStats: n,
4915
4592
  synchronizationSourcesAudio: e
4916
4593
  }) => {
@@ -4928,7 +4605,7 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
4928
4605
  remoteOutboundRtp: t[p.REMOTE_OUTBOUND_RTP],
4929
4606
  synchronizationSources: e
4930
4607
  };
4931
- }, He = (n) => {
4608
+ }, Ge = (n) => {
4932
4609
  if (!n)
4933
4610
  return {
4934
4611
  candidatePair: void 0,
@@ -4945,39 +4622,39 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
4945
4622
  remoteCandidate: e[p.REMOTE_CANDIDATE],
4946
4623
  transport: e[p.TRANSPORT]
4947
4624
  };
4948
- }, fs = ({
4625
+ }, as = ({
4949
4626
  audioSenderStats: n,
4950
4627
  videoSenderFirstStats: e,
4951
4628
  videoSenderSecondStats: t
4952
4629
  }) => ({
4953
- video: ue(e),
4954
- secondVideo: ue(t),
4955
- audio: Is(n),
4956
- additional: He(
4630
+ video: ge(e),
4631
+ secondVideo: ge(t),
4632
+ audio: is(n),
4633
+ additional: Ge(
4957
4634
  n ?? e ?? t
4958
4635
  )
4959
- }), Ms = ({
4636
+ }), os = ({
4960
4637
  audioReceiverStats: n,
4961
4638
  videoReceiverFirstStats: e,
4962
4639
  videoReceiverSecondStats: t,
4963
4640
  synchronizationSources: s
4964
4641
  }) => ({
4965
- video: Te({
4642
+ video: ue({
4966
4643
  videoReceiversStats: e,
4967
4644
  synchronizationSourcesVideo: s.video
4968
4645
  }),
4969
- secondVideo: Te({
4646
+ secondVideo: ue({
4970
4647
  videoReceiversStats: t,
4971
4648
  synchronizationSourcesVideo: s.video
4972
4649
  }),
4973
- audio: vs({
4650
+ audio: rs({
4974
4651
  audioReceiverStats: n,
4975
4652
  synchronizationSourcesAudio: s.audio
4976
4653
  }),
4977
- additional: He(
4654
+ additional: Ge(
4978
4655
  n ?? e ?? t
4979
4656
  )
4980
- }), _s = ({
4657
+ }), cs = ({
4981
4658
  audioSenderStats: n,
4982
4659
  videoSenderFirstStats: e,
4983
4660
  videoSenderSecondStats: t,
@@ -4986,11 +4663,11 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
4986
4663
  videoReceiverSecondStats: r,
4987
4664
  synchronizationSources: a
4988
4665
  }) => {
4989
- const o = fs({
4666
+ const o = as({
4990
4667
  audioSenderStats: n,
4991
4668
  videoSenderFirstStats: e,
4992
4669
  videoSenderSecondStats: t
4993
- }), c = Ms({
4670
+ }), c = os({
4994
4671
  audioReceiverStats: s,
4995
4672
  videoReceiverFirstStats: i,
4996
4673
  videoReceiverSecondStats: r,
@@ -5000,7 +4677,7 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
5000
4677
  outbound: o,
5001
4678
  inbound: c
5002
4679
  };
5003
- }, bs = async (n) => {
4680
+ }, ds = async (n) => {
5004
4681
  const e = "audio", t = "video", s = n.getSenders(), i = s.find((S) => S.track?.kind === e), r = s.filter((S) => S.track?.kind === t), a = n.getReceivers(), o = a.find((S) => S.track.kind === e), c = a.filter((S) => S.track.kind === t), h = {
5005
4682
  trackIdentifier: o?.track.id,
5006
4683
  item: o?.getSynchronizationSources()[0]
@@ -5025,7 +4702,7 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
5025
4702
  A,
5026
4703
  L,
5027
4704
  z,
5028
- Je
4705
+ Ye
5029
4706
  ] = S;
5030
4707
  return {
5031
4708
  synchronizationSources: u,
@@ -5034,25 +4711,25 @@ const xe = ["collected"], Rs = () => new R(xe), ge = () => "performance" in wind
5034
4711
  videoSenderSecondStats: A,
5035
4712
  audioReceiverStats: L,
5036
4713
  videoReceiverFirstStats: z,
5037
- videoReceiverSecondStats: Je
4714
+ videoReceiverSecondStats: Ye
5038
4715
  };
5039
4716
  });
5040
- }, Os = (n) => {
4717
+ }, hs = (n) => {
5041
4718
  d(String(n));
5042
4719
  };
5043
- class Ds {
4720
+ class ls {
5044
4721
  events;
5045
4722
  setTimeoutRequest;
5046
- requesterAllStatistics = new J(bs);
4723
+ requesterAllStatistics = new J(ds);
5047
4724
  constructor() {
5048
- this.events = Rs(), this.setTimeoutRequest = new Se();
4725
+ this.events = ss(), this.setTimeoutRequest = new Se();
5049
4726
  }
5050
4727
  get requested() {
5051
4728
  return this.setTimeoutRequest.requested;
5052
4729
  }
5053
4730
  start(e, {
5054
4731
  interval: t = B,
5055
- onError: s = Os
4732
+ onError: s = hs
5056
4733
  } = {}) {
5057
4734
  this.stop(), this.setTimeoutRequest.request(() => {
5058
4735
  this.collectStatistics(e, {
@@ -5081,10 +4758,10 @@ class Ds {
5081
4758
  collectStatistics = (e, {
5082
4759
  onError: t
5083
4760
  }) => {
5084
- const s = ge();
4761
+ const s = le();
5085
4762
  this.requestAllStatistics(e).then((i) => {
5086
- this.events.trigger("collected", _s(i));
5087
- const a = ge() - s;
4763
+ this.events.trigger("collected", cs(i));
4764
+ const a = le() - s;
5088
4765
  let o = B;
5089
4766
  a > 48 ? o = B * 4 : a > 32 ? o = B * 3 : a > 16 && (o = B * 2), this.start(e, {
5090
4767
  onError: t,
@@ -5101,8 +4778,8 @@ class Ds {
5101
4778
  return this.requesterAllStatistics.request(t);
5102
4779
  };
5103
4780
  }
5104
- const Ps = 500;
5105
- class ys {
4781
+ const gs = 500;
4782
+ class us {
5106
4783
  statsPeerConnection;
5107
4784
  availableStats;
5108
4785
  previousAvailableStats;
@@ -5112,7 +4789,7 @@ class ys {
5112
4789
  callManager: e,
5113
4790
  apiManager: t
5114
4791
  }) {
5115
- this.callManager = e, this.apiManager = t, this.statsPeerConnection = new Ds(), this.subscribe();
4792
+ this.callManager = e, this.apiManager = t, this.statsPeerConnection = new ls(), this.subscribe();
5116
4793
  }
5117
4794
  get events() {
5118
4795
  return this.statsPeerConnection.events;
@@ -5162,7 +4839,7 @@ class ys {
5162
4839
  return this.previousInboundRtp?.packetsReceived;
5163
4840
  }
5164
4841
  get isReceivingPackets() {
5165
- const e = this.packetsReceived !== void 0 && this.packetsReceived >= Ps, t = this.packetsReceived !== this.previousPacketsReceived;
4842
+ const e = this.packetsReceived !== void 0 && this.packetsReceived >= gs, t = this.packetsReceived !== this.previousPacketsReceived;
5166
4843
  return e && t;
5167
4844
  }
5168
4845
  on(e, t) {
@@ -5202,31 +4879,354 @@ class ys {
5202
4879
  });
5203
4880
  }
5204
4881
  }
5205
- const ws = (n, e) => n.filter((s) => e.some((i) => i.clockRate === s.clockRate && i.mimeType === s.mimeType && i.channels === s.channels && i.sdpFmtpLine === s.sdpFmtpLine)), Ls = (n) => {
4882
+ const Ts = (n, e) => n.filter((s) => e.some((i) => i.clockRate === s.clockRate && i.mimeType === s.mimeType && i.channels === s.channels && i.sdpFmtpLine === s.sdpFmtpLine)), Ss = (n) => {
5206
4883
  const e = RTCRtpSender.getCapabilities(n), t = RTCRtpReceiver.getCapabilities(n), s = e === null ? [] : e.codecs, i = t === null ? [] : t.codecs;
5207
- return ws(s, i);
5208
- }, Us = (n, e) => e === void 0 || e.length === 0 ? n : n.sort((t, s) => {
4884
+ return Ts(s, i);
4885
+ }, Es = (n, e) => e === void 0 || e.length === 0 ? n : n.sort((t, s) => {
5209
4886
  const i = e.indexOf(t.mimeType), r = e.indexOf(s.mimeType), a = i === -1 ? Number.MAX_VALUE : i, o = r === -1 ? Number.MAX_VALUE : r;
5210
4887
  return a - o;
5211
- }), Fs = (n, e) => e === void 0 || e.length === 0 ? n : n.filter((t) => !e.includes(t.mimeType)), Bs = (n, {
4888
+ }), ms = (n, e) => e === void 0 || e.length === 0 ? n : n.filter((t) => !e.includes(t.mimeType)), ps = (n, {
5212
4889
  preferredMimeTypesVideoCodecs: e,
5213
4890
  excludeMimeTypesVideoCodecs: t
5214
4891
  }) => {
5215
4892
  try {
5216
4893
  if (typeof n.setCodecPreferences == "function" && n.sender.track?.kind === "video" && (e !== void 0 && e.length > 0 || t !== void 0 && t.length > 0)) {
5217
- const s = Ls("video"), i = Fs(s, t), r = Us(i, e);
4894
+ const s = Ss("video"), i = ms(s, t), r = Es(i, e);
5218
4895
  n.setCodecPreferences(r);
5219
4896
  }
5220
4897
  } catch (s) {
5221
4898
  d("setCodecPreferences error", s);
5222
4899
  }
5223
- }, We = [
4900
+ }, Cs = (n) => [...n.keys()].map((e) => n.get(e)), Ns = (n, e) => Cs(n).find((t) => t?.type === e), As = async (n) => n.getStats().then((e) => Ns(e, "codec")?.mimeType);
4901
+ class Rs {
4902
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
4903
+ async getCodecFromSender(e) {
4904
+ return await As(e) ?? "";
4905
+ }
4906
+ }
4907
+ class Is {
4908
+ stackPromises = me({
4909
+ noRunIsNotActual: !0
4910
+ });
4911
+ /**
4912
+ * Добавляет задачу в очередь и возвращает Promise с результатом
4913
+ * @param task - Функция для выполнения
4914
+ * @returns Promise с результатом выполнения задачи
4915
+ */
4916
+ async add(e) {
4917
+ return this.stackPromises.add(e), this.run();
4918
+ }
4919
+ stop() {
4920
+ this.stackPromises.stop();
4921
+ }
4922
+ /**
4923
+ * Выполняет задачи из очереди с обработкой ошибок
4924
+ * @returns Promise с результатом выполнения
4925
+ */
4926
+ async run() {
4927
+ return this.stackPromises().catch((e) => {
4928
+ d("TaskQueue: error", e);
4929
+ });
4930
+ }
4931
+ }
4932
+ class vs {
4933
+ taskQueue;
4934
+ onSetParameters;
4935
+ constructor(e) {
4936
+ this.onSetParameters = e, this.taskQueue = new Is();
4937
+ }
4938
+ async setEncodingsToSender(e, t) {
4939
+ return this.taskQueue.add(async () => fe(e, t, this.onSetParameters));
4940
+ }
4941
+ stop() {
4942
+ this.taskQueue.stop();
4943
+ }
4944
+ }
4945
+ const qe = (n, e) => n !== void 0 && e !== void 0 && n.toLowerCase().includes(e.toLowerCase()), fs = 1e6, O = (n) => n * fs, Ve = O(0.06), xe = O(4), Ms = (n) => n <= 64 ? Ve : n <= 128 ? O(0.12) : n <= 256 ? O(0.25) : n <= 384 ? O(0.32) : n <= 426 ? O(0.38) : n <= 640 ? O(0.5) : n <= 848 ? O(0.7) : n <= 1280 ? O(1) : n <= 1920 ? O(2) : xe, _s = "av1", bs = (n) => qe(n, _s), Os = 0.6, ie = (n, e) => bs(e) ? n * Os : n, Ds = (n) => ie(Ve, n), Ps = (n) => ie(xe, n), Te = (n, e) => {
4946
+ const t = Ms(n);
4947
+ return ie(t, e);
4948
+ }, X = 1, ys = ({
4949
+ videoTrack: n,
4950
+ targetSize: e
4951
+ }) => {
4952
+ const t = n.getSettings(), s = t.width, i = t.height, r = s === void 0 ? X : s / e.width, a = i === void 0 ? X : i / e.height;
4953
+ return Math.max(r, a, X);
4954
+ };
4955
+ class ws {
4956
+ ignoreForCodec;
4957
+ senderFinder;
4958
+ codecProvider;
4959
+ parametersSetter;
4960
+ resultNoChanged = {
4961
+ isChanged: !1,
4962
+ parameters: {
4963
+ encodings: [{}],
4964
+ transactionId: "0",
4965
+ codecs: [],
4966
+ headerExtensions: [],
4967
+ rtcp: {}
4968
+ }
4969
+ };
4970
+ constructor({
4971
+ senderFinder: e,
4972
+ codecProvider: t,
4973
+ parametersSetter: s
4974
+ }, i) {
4975
+ this.senderFinder = e, this.codecProvider = t, this.parametersSetter = s, this.ignoreForCodec = i.ignoreForCodec;
4976
+ }
4977
+ /**
4978
+ * Выполняет балансировку на основе заголовков от сервера
4979
+ * @param connection - RTCPeerConnection для получения отправителей
4980
+ * @param headers - Заголовки от сервера с командами управления
4981
+ * @returns Promise с результатом балансировки
4982
+ */
4983
+ async balance(e, t) {
4984
+ const s = e.getSenders(), i = this.senderFinder.findVideoSender(s);
4985
+ if (!i?.track)
4986
+ return { ...this.resultNoChanged, sender: i };
4987
+ const r = await this.codecProvider.getCodecFromSender(i);
4988
+ if (qe(r, this.ignoreForCodec))
4989
+ return { ...this.resultNoChanged, sender: i };
4990
+ const { mainCam: a, resolutionMainCam: o } = t ?? {};
4991
+ return this.processSender(
4992
+ { mainCam: a, resolutionMainCam: o },
4993
+ {
4994
+ sender: i,
4995
+ codec: r,
4996
+ videoTrack: i.track
4997
+ }
4998
+ ).then((c) => ({ ...c, sender: i }));
4999
+ }
5000
+ /**
5001
+ * Обрабатывает отправитель в зависимости от команды управления
5002
+ * @param context - Контекст балансировки
5003
+ * @returns Promise с результатом обработки
5004
+ */
5005
+ async processSender(e, t) {
5006
+ const { mainCam: s, resolutionMainCam: i } = e;
5007
+ switch (s) {
5008
+ case f.PAUSE_MAIN_CAM:
5009
+ return this.downgradeResolutionSender(t);
5010
+ case f.RESUME_MAIN_CAM:
5011
+ return this.setBitrateByTrackResolution(t);
5012
+ case f.MAX_MAIN_CAM_RESOLUTION:
5013
+ return i !== void 0 ? this.setResolutionSender(i, t) : this.setBitrateByTrackResolution(t);
5014
+ case f.ADMIN_STOP_MAIN_CAM:
5015
+ case f.ADMIN_START_MAIN_CAM:
5016
+ case void 0:
5017
+ return this.setBitrateByTrackResolution(t);
5018
+ default:
5019
+ return this.setBitrateByTrackResolution(t);
5020
+ }
5021
+ }
5022
+ /**
5023
+ * Понижает разрешение отправителя (пауза камеры)
5024
+ * @param context - Контекст балансировки
5025
+ * @returns Promise с результатом
5026
+ */
5027
+ async downgradeResolutionSender(e) {
5028
+ const { sender: t, codec: s } = e, i = {
5029
+ scaleResolutionDownBy: 200,
5030
+ maxBitrate: Ds(s)
5031
+ };
5032
+ return this.parametersSetter.setEncodingsToSender(t, i);
5033
+ }
5034
+ /**
5035
+ * Устанавливает битрейт на основе разрешения трека
5036
+ * @param context - Контекст балансировки
5037
+ * @returns Promise с результатом
5038
+ */
5039
+ async setBitrateByTrackResolution(e) {
5040
+ const { sender: t, videoTrack: s, codec: i } = e, a = s.getSettings().width, o = a === void 0 ? Ps(i) : Te(a, i);
5041
+ return this.parametersSetter.setEncodingsToSender(t, {
5042
+ scaleResolutionDownBy: 1,
5043
+ maxBitrate: o
5044
+ });
5045
+ }
5046
+ /**
5047
+ * Устанавливает разрешение отправителя на основе заголовка
5048
+ * @param resolutionMainCam - Разрешение главной камеры
5049
+ * @param context - Контекст балансировки
5050
+ * @returns Promise с результатом
5051
+ */
5052
+ async setResolutionSender(e, t) {
5053
+ const [s, i] = e.split("x"), { sender: r, videoTrack: a, codec: o } = t, c = {
5054
+ width: Number(s),
5055
+ height: Number(i)
5056
+ }, h = ys({
5057
+ videoTrack: a,
5058
+ targetSize: c
5059
+ }), T = Te(c.width, o), u = {
5060
+ scaleResolutionDownBy: h,
5061
+ maxBitrate: T
5062
+ };
5063
+ return this.parametersSetter.setEncodingsToSender(r, u);
5064
+ }
5065
+ }
5066
+ const Ls = (n) => n.find((e) => e.track?.kind === "video");
5067
+ class Us {
5068
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
5069
+ findVideoSender(e) {
5070
+ return Ls(e);
5071
+ }
5072
+ }
5073
+ class Fs {
5074
+ currentSender;
5075
+ originalReplaceTrack;
5076
+ lastWidth;
5077
+ lastHeight;
5078
+ maxPollIntervalMs;
5079
+ currentPollIntervalMs;
5080
+ pollIntervalMs;
5081
+ setTimeoutRequest;
5082
+ constructor({
5083
+ pollIntervalMs: e = 1e3,
5084
+ maxPollIntervalMs: t
5085
+ }) {
5086
+ this.pollIntervalMs = e, this.maxPollIntervalMs = t ?? e * 16, this.currentPollIntervalMs = this.pollIntervalMs, this.setTimeoutRequest = new Se();
5087
+ }
5088
+ /**
5089
+ * Проверяет актуальный video-sender и (при необходимости) перенастраивает наблюдение.
5090
+ */
5091
+ subscribe(e, t) {
5092
+ if (!e) {
5093
+ this.detachSender();
5094
+ return;
5095
+ }
5096
+ this.currentSender !== e && (this.detachSender(), this.attachSender(e, t));
5097
+ }
5098
+ /** Останавливает всю активность мониторинга */
5099
+ unsubscribe() {
5100
+ this.detachSender();
5101
+ }
5102
+ attachSender(e, t) {
5103
+ this.currentSender = e;
5104
+ const s = e.replaceTrack.bind(e);
5105
+ this.originalReplaceTrack = s, e.replaceTrack = async (i) => {
5106
+ await s(i), this.attachTrack(t, i ?? void 0), t();
5107
+ }, this.attachTrack(t, e.track);
5108
+ }
5109
+ detachSender() {
5110
+ this.currentSender && this.originalReplaceTrack && (this.currentSender.replaceTrack = this.originalReplaceTrack), this.originalReplaceTrack = void 0, this.currentSender = void 0, this.detachTrack();
5111
+ }
5112
+ attachTrack(e, t) {
5113
+ if (this.detachTrack(), !t)
5114
+ return;
5115
+ const { width: s, height: i } = t.getSettings();
5116
+ this.lastWidth = s, this.lastHeight = i, this.currentPollIntervalMs = this.pollIntervalMs, this.schedulePoll(t, e);
5117
+ }
5118
+ /**
5119
+ * Периодически опрашивает track с экспоненциальной адаптацией частоты.
5120
+ * При отсутствии изменений интервал удваивается до maxPollIntervalMs,
5121
+ * при обнаружении изменений сбрасывается до начального.
5122
+ */
5123
+ schedulePoll(e, t) {
5124
+ const s = () => {
5125
+ const { width: i, height: r } = e.getSettings();
5126
+ i !== this.lastWidth || r !== this.lastHeight ? (this.lastWidth = i, this.lastHeight = r, this.currentPollIntervalMs = this.pollIntervalMs, t()) : this.currentPollIntervalMs = Math.min(
5127
+ this.currentPollIntervalMs * 2,
5128
+ this.maxPollIntervalMs
5129
+ ), this.setTimeoutRequest.request(s, this.currentPollIntervalMs);
5130
+ };
5131
+ this.setTimeoutRequest.request(s, this.currentPollIntervalMs);
5132
+ }
5133
+ detachTrack() {
5134
+ this.setTimeoutRequest.cancelRequest(), this.lastWidth = void 0, this.lastHeight = void 0;
5135
+ }
5136
+ }
5137
+ class Bs {
5138
+ apiManager;
5139
+ currentHandler;
5140
+ constructor(e) {
5141
+ this.apiManager = e;
5142
+ }
5143
+ /**
5144
+ * Подписывается на события управления главной камерой
5145
+ * @param handler - Обработчик события
5146
+ */
5147
+ subscribe(e) {
5148
+ this.currentHandler = e, this.apiManager.on("main-cam-control", e);
5149
+ }
5150
+ /**
5151
+ * Отписывается от событий управления главной камерой
5152
+ */
5153
+ unsubscribe() {
5154
+ this.currentHandler && (this.apiManager.off("main-cam-control", this.currentHandler), this.currentHandler = void 0);
5155
+ }
5156
+ }
5157
+ class ks {
5158
+ eventHandler;
5159
+ senderBalancer;
5160
+ parametersSetterWithQueue;
5161
+ getConnection;
5162
+ serverHeaders;
5163
+ trackMonitor;
5164
+ constructor(e, t, {
5165
+ ignoreForCodec: s,
5166
+ onSetParameters: i,
5167
+ pollIntervalMs: r
5168
+ } = {}) {
5169
+ this.getConnection = t, this.eventHandler = new Bs(e), this.parametersSetterWithQueue = new vs(i), this.senderBalancer = new ws(
5170
+ {
5171
+ senderFinder: new Us(),
5172
+ codecProvider: new Rs(),
5173
+ parametersSetter: this.parametersSetterWithQueue
5174
+ },
5175
+ {
5176
+ ignoreForCodec: s
5177
+ }
5178
+ ), this.trackMonitor = new Fs({ pollIntervalMs: r });
5179
+ }
5180
+ /**
5181
+ * Подписывается на события управления главной камерой
5182
+ */
5183
+ subscribe() {
5184
+ this.eventHandler.subscribe(this.handleMainCamControl);
5185
+ }
5186
+ /**
5187
+ * Отписывается от событий и сбрасывает состояние
5188
+ */
5189
+ unsubscribe() {
5190
+ this.eventHandler.unsubscribe(), this.parametersSetterWithQueue.stop(), this.reset();
5191
+ }
5192
+ /**
5193
+ * Сбрасывает состояние балансировщика
5194
+ */
5195
+ reset() {
5196
+ delete this.serverHeaders, this.trackMonitor.unsubscribe();
5197
+ }
5198
+ /**
5199
+ * Выполняет балансировку на основе текущего состояния
5200
+ * @returns Promise с результатом балансировки
5201
+ */
5202
+ async balance() {
5203
+ const e = this.getConnection();
5204
+ if (!e)
5205
+ throw new Error("connection is not exist");
5206
+ const t = await this.senderBalancer.balance(e, this.serverHeaders);
5207
+ return this.trackMonitor.subscribe(t.sender, () => {
5208
+ this.balance().catch((s) => {
5209
+ d("balance on track change: error", s);
5210
+ });
5211
+ }), t;
5212
+ }
5213
+ /**
5214
+ * Обработчик событий управления главной камерой
5215
+ * @param headers - Заголовки от сервера
5216
+ */
5217
+ handleMainCamControl = (e) => {
5218
+ this.serverHeaders = e, this.balance().catch((t) => {
5219
+ d("handleMainCamControl: error", t);
5220
+ });
5221
+ };
5222
+ }
5223
+ const He = [
5224
5224
  "balancing-scheduled",
5225
5225
  "balancing-started",
5226
5226
  "balancing-stopped",
5227
5227
  "parameters-updated"
5228
- ], ks = () => new R(We);
5229
- class $s {
5228
+ ], $s = () => new R(He);
5229
+ class Gs {
5230
5230
  isBalancingActive = !1;
5231
5231
  events;
5232
5232
  callManager;
@@ -5234,7 +5234,7 @@ class $s {
5234
5234
  videoSendingBalancer;
5235
5235
  startBalancingTimer;
5236
5236
  constructor(e, t, s = {}) {
5237
- this.events = ks(), this.callManager = e, this.balancingStartDelay = s.balancingStartDelay ?? 1e4, this.videoSendingBalancer = new Kt(
5237
+ this.events = $s(), this.callManager = e, this.balancingStartDelay = s.balancingStartDelay ?? 1e4, this.videoSendingBalancer = new ks(
5238
5238
  t,
5239
5239
  () => e.connection,
5240
5240
  {
@@ -5304,13 +5304,13 @@ class $s {
5304
5304
  this.startBalancingTimer && (clearTimeout(this.startBalancingTimer), this.startBalancingTimer = void 0);
5305
5305
  }
5306
5306
  }
5307
- const Qe = "no-inbound-frames", Ye = [Qe], Gs = () => new R(Ye);
5308
- class qs {
5307
+ const We = "no-inbound-frames", Qe = [We], qs = () => new R(Qe);
5308
+ class Vs {
5309
5309
  events;
5310
5310
  statsManager;
5311
5311
  callManager;
5312
5312
  constructor(e, t) {
5313
- this.statsManager = e, this.callManager = t, this.events = Gs(), this.subscribe();
5313
+ this.statsManager = e, this.callManager = t, this.events = qs(), this.subscribe();
5314
5314
  }
5315
5315
  get mainVideoTrack() {
5316
5316
  return this.callManager.getMainRemoteStream()?.getVideoTracks()[0];
@@ -5323,20 +5323,20 @@ class qs {
5323
5323
  return this.events.on(e, t);
5324
5324
  }
5325
5325
  handleStatsCollected = () => {
5326
- this.hasNoIncomingFrames() && this.events.trigger(Qe, {});
5326
+ this.hasNoIncomingFrames() && this.events.trigger(We, {});
5327
5327
  };
5328
5328
  hasNoIncomingFrames = () => this.statsManager.isInvalidInboundFrames && this.isMutedMainVideoTrack;
5329
5329
  subscribe() {
5330
5330
  this.statsManager.on("collected", this.handleStatsCollected);
5331
5331
  }
5332
5332
  }
5333
- const Vs = 3e3;
5334
- class xs {
5333
+ const xs = 3e3;
5334
+ class Hs {
5335
5335
  renegotiateRequester;
5336
5336
  renegotiateThrottled;
5337
5337
  callManager;
5338
- constructor(e, t = Vs) {
5339
- this.callManager = e, this.renegotiateRequester = new J(e.renegotiate.bind(e)), this.renegotiateThrottled = st.throttle(
5338
+ constructor(e, t = xs) {
5339
+ this.callManager = e, this.renegotiateRequester = new J(e.renegotiate.bind(e)), this.renegotiateThrottled = nt.throttle(
5340
5340
  this.requestRenegotiate.bind(this),
5341
5341
  t
5342
5342
  ), this.subscribe();
@@ -5364,12 +5364,11 @@ class xs {
5364
5364
  d("cancel recover main stream"), this.renegotiateThrottled.cancel(), this.renegotiateRequester.cancelRequest();
5365
5365
  }
5366
5366
  }
5367
- const Hs = 1e6, Ws = ke.map((n) => `auto-connect:${n}`), Qs = Le.map((n) => `connection:${n}`), Ys = Re.map((n) => `call:${n}`), Js = $e.map((n) => `conference-state:${n}`), zs = Ne.map((n) => `api:${n}`), js = Ge.map((n) => `incoming-call:${n}`), Xs = ye.map((n) => `presentation:${n}`), Ks = xe.map((n) => `stats:${n}`), Zs = We.map((n) => `video-balancer:${n}`), ei = Ye.map((n) => `main-stream-health:${n}`), ti = Ve.map((n) => `session:${n}`), ni = [
5367
+ const Ws = 1e6, Qs = Le.map((n) => `auto-connect:${n}`), Ys = De.map((n) => `connection:${n}`), Js = Re.map((n) => `call:${n}`), zs = Ue.map((n) => `conference-state:${n}`), js = Ne.map((n) => `api:${n}`), Xs = Fe.map((n) => `incoming-call:${n}`), Ks = be.map((n) => `presentation:${n}`), Zs = $e.map((n) => `stats:${n}`), ei = He.map((n) => `video-balancer:${n}`), ti = Qe.map((n) => `main-stream-health:${n}`), ni = ke.map((n) => `session:${n}`), si = [
5368
5368
  "disconnected-from-out-of-call",
5369
5369
  "connected-with-configuration-from-out-of-call",
5370
5370
  "stopped-presentation-by-server-command"
5371
- ], si = [
5372
- ...Ws,
5371
+ ], ii = [
5373
5372
  ...Qs,
5374
5373
  ...Ys,
5375
5374
  ...Js,
@@ -5380,9 +5379,10 @@ const Hs = 1e6, Ws = ke.map((n) => `auto-connect:${n}`), Qs = Le.map((n) => `con
5380
5379
  ...Zs,
5381
5380
  ...ei,
5382
5381
  ...ti,
5383
- ...ni
5384
- ], ii = () => new R(si);
5385
- class pi {
5382
+ ...ni,
5383
+ ...si
5384
+ ], ri = () => new R(ii);
5385
+ class Ci {
5386
5386
  events;
5387
5387
  connectionManager;
5388
5388
  connectionQueueManager;
@@ -5406,26 +5406,26 @@ class pi {
5406
5406
  videoBalancerOptions: i,
5407
5407
  autoConnectorOptions: r
5408
5408
  } = {}) {
5409
- this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.events = ii(), this.apiManager = new gt(), this.connectionManager = new xn({ JsSIP: e }), this.connectionQueueManager = new Hn({
5409
+ this.preferredMimeTypesVideoCodecs = t, this.excludeMimeTypesVideoCodecs = s, this.events = ri(), this.apiManager = new lt(), this.connectionManager = new vn({ JsSIP: e }), this.connectionQueueManager = new fn({
5410
5410
  connectionManager: this.connectionManager
5411
- }), this.conferenceStateManager = new as(), this.contentedStreamManager = new ls(), this.callManager = new pn(this.conferenceStateManager, this.contentedStreamManager), this.incomingCallManager = new ps(this.connectionManager), this.presentationManager = new vn({
5411
+ }), this.conferenceStateManager = new qn(), this.contentedStreamManager = new Qn(), this.callManager = new Kt(this.conferenceStateManager, this.contentedStreamManager), this.incomingCallManager = new Zn(this.connectionManager), this.presentationManager = new rn({
5412
5412
  callManager: this.callManager,
5413
- maxBitrate: Hs
5414
- }), this.statsManager = new ys({
5413
+ maxBitrate: Ws
5414
+ }), this.statsManager = new us({
5415
5415
  callManager: this.callManager,
5416
5416
  apiManager: this.apiManager
5417
- }), this.autoConnectorManager = new is(
5417
+ }), this.autoConnectorManager = new $n(
5418
5418
  {
5419
5419
  connectionQueueManager: this.connectionQueueManager,
5420
5420
  connectionManager: this.connectionManager,
5421
5421
  callManager: this.callManager
5422
5422
  },
5423
5423
  r
5424
- ), this.videoSendingBalancerManager = new $s(
5424
+ ), this.videoSendingBalancerManager = new Gs(
5425
5425
  this.callManager,
5426
5426
  this.apiManager,
5427
5427
  i
5428
- ), this.mainStreamHealthMonitor = new qs(this.statsManager, this.callManager), this.mainStreamRecovery = new xs(this.callManager), this.sessionManager = new As({
5428
+ ), this.mainStreamHealthMonitor = new Vs(this.statsManager, this.callManager), this.mainStreamRecovery = new Hs(this.callManager), this.sessionManager = new ns({
5429
5429
  connectionManager: this.connectionManager,
5430
5430
  callManager: this.callManager,
5431
5431
  incomingCallManager: this.incomingCallManager,
@@ -5634,7 +5634,7 @@ class pi {
5634
5634
  if (i === void 0)
5635
5635
  throw new Error("No sipServerUrl for sendOffer");
5636
5636
  const r = this.conferenceStateManager.getToken();
5637
- return At({
5637
+ return Nt({
5638
5638
  serverUrl: i,
5639
5639
  offer: t,
5640
5640
  token: r,
@@ -5644,7 +5644,7 @@ class pi {
5644
5644
  });
5645
5645
  };
5646
5646
  setCodecPreferences(e) {
5647
- Bs(e, {
5647
+ ps(e, {
5648
5648
  preferredMimeTypesVideoCodecs: this.preferredMimeTypesVideoCodecs,
5649
5649
  excludeMimeTypesVideoCodecs: this.excludeMimeTypesVideoCodecs
5650
5650
  });
@@ -5669,24 +5669,24 @@ class pi {
5669
5669
  };
5670
5670
  }
5671
5671
  export {
5672
- De as E,
5673
- Et as O,
5674
- pi as S,
5672
+ Me as E,
5673
+ St as O,
5674
+ Ci as S,
5675
5675
  fe as a,
5676
5676
  K as b,
5677
- wn as c,
5678
- ut as d,
5679
- us as e,
5677
+ Tn as c,
5678
+ gt as d,
5679
+ Jn as e,
5680
5680
  Ce as f,
5681
- Ei as g,
5682
- Gn as h,
5683
- Si as i,
5684
- mi as j,
5681
+ mi as g,
5682
+ An as h,
5683
+ Ei as i,
5684
+ pi as j,
5685
5685
  p as k,
5686
5686
  d as l,
5687
- Ds as m,
5688
- Ft as n,
5689
- Nn as o,
5687
+ ls as m,
5688
+ As as n,
5689
+ en as o,
5690
5690
  H as p,
5691
- At as s
5691
+ Nt as s
5692
5692
  };