@whereby.com/media 1.12.2 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -907,13 +907,13 @@ const metrics = [
907
907
  id: "turn-usage",
908
908
  global: true,
909
909
  enabled: ({ stats }) => !!Object.values(stats.candidatePairs).length,
910
- value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.usingTurn)
910
+ value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.usingTurn),
911
911
  },
912
912
  {
913
913
  id: "turn-tls-usage",
914
914
  global: true,
915
915
  enabled: ({ stats }) => !!Object.values(stats.candidatePairs).length,
916
- value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.turnProtocol === 'tls')
916
+ value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.turnProtocol === "tls"),
917
917
  },
918
918
  {
919
919
  id: "concealment",
@@ -1421,6 +1421,10 @@ class VegaConnection extends EventEmitter.EventEmitter {
1421
1421
  var _a;
1422
1422
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
1423
1423
  }
1424
+ isConnected() {
1425
+ var _a, _b;
1426
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN || ((_b = this.socket) === null || _b === void 0 ? void 0 : _b.readyState) === WebSocket.CONNECTING;
1427
+ }
1424
1428
  _onOpen() {
1425
1429
  logger$9.info("Connected");
1426
1430
  this.emit("open");
@@ -2542,10 +2546,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2542
2546
  if (hasPassedOnRoomSessionId &&
2543
2547
  newRoomSessionIdValue &&
2544
2548
  newRoomSessionIdValue !== oldRoomSessionIdValue) {
2545
- if (ws) {
2546
- ws.close();
2547
- return;
2548
- }
2549
+ ws === null || ws === void 0 ? void 0 : ws.close();
2549
2550
  }
2550
2551
  if (newRoomSessionIdValue)
2551
2552
  hasPassedOnRoomSessionId = true;
@@ -2577,7 +2578,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2577
2578
  else if (args[0] === "customEvent" && args[2].type === "featureFlags") {
2578
2579
  featureFlags = args;
2579
2580
  }
2580
- if (ws.readyState === WebSocket.OPEN) {
2581
+ if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.OPEN) {
2581
2582
  connectionAttempt = 0;
2582
2583
  ws.send(JSON.stringify(args));
2583
2584
  }
@@ -2591,7 +2592,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2591
2592
  else {
2592
2593
  buffer.push(args);
2593
2594
  }
2594
- if (ws.readyState === WebSocket.CLOSED && connectionShouldBeOpen) {
2595
+ if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.CLOSED && connectionShouldBeOpen) {
2595
2596
  setTimeout(() => {
2596
2597
  if (ws.readyState === WebSocket.CLOSED && connectionShouldBeOpen) {
2597
2598
  connection.connect();
@@ -2601,16 +2602,12 @@ function rtcStatsConnection(wsURL, logger = console) {
2601
2602
  },
2602
2603
  close: () => {
2603
2604
  connectionShouldBeOpen = false;
2604
- if (ws) {
2605
- ws.close();
2606
- }
2605
+ ws === null || ws === void 0 ? void 0 : ws.close();
2607
2606
  },
2608
2607
  connect: () => {
2609
2608
  connectionShouldBeOpen = true;
2610
2609
  connectionAttempt += 1;
2611
- if (ws) {
2612
- ws.close();
2613
- }
2610
+ ws === null || ws === void 0 ? void 0 : ws.close();
2614
2611
  connection.connected = true;
2615
2612
  ws = new WebSocket(wsURL + window.location.pathname, RTCSTATS_PROTOCOL_VERSION);
2616
2613
  ws.onerror = (e) => {
@@ -2662,7 +2659,6 @@ function rtcStatsConnection(wsURL, logger = console) {
2662
2659
  };
2663
2660
  },
2664
2661
  };
2665
- connection.connect();
2666
2662
  return connection;
2667
2663
  }
2668
2664
  const server = rtcStatsConnection(process.env.RTCSTATS_URL || "wss://rtcstats.srv.whereby.com");
@@ -4159,7 +4155,6 @@ class P2pRtcManager {
4159
4155
  this._videoTrackBeingMonitored = track;
4160
4156
  }
4161
4157
  _connect(clientId) {
4162
- this.rtcStatsReconnect();
4163
4158
  let session = this._getSession(clientId);
4164
4159
  let initialBandwidth = (session && session.bandwidth) || 0;
4165
4160
  if (session) {
@@ -5119,6 +5114,9 @@ class VegaRtcManager {
5119
5114
  }), this._serverSocket.on(PROTOCOL_RESPONSES.ROOM_JOINED, () => {
5120
5115
  if (this._screenVideoTrack)
5121
5116
  this._emitScreenshareStarted();
5117
+ if (this._features.sfuReconnectV2On && !this._vegaConnection.isConnected() && this._reconnect) {
5118
+ this._connect();
5119
+ }
5122
5120
  }));
5123
5121
  this._connect();
5124
5122
  }
@@ -5129,6 +5127,17 @@ class VegaRtcManager {
5129
5127
  });
5130
5128
  }
5131
5129
  _connect() {
5130
+ if (this._features.sfuReconnectV2On) {
5131
+ if (!this._serverSocket.isConnected()) {
5132
+ const reconnectThresholdInMs = this._serverSocket.getReconnectThreshold();
5133
+ if (!reconnectThresholdInMs)
5134
+ return;
5135
+ if (Date.now() > (this._serverSocket.disconnectTimestamp || 0) + reconnectThresholdInMs)
5136
+ return;
5137
+ }
5138
+ if (this._reconnectTimeOut)
5139
+ clearTimeout(this._reconnectTimeOut);
5140
+ }
5132
5141
  const host = this._features.sfuServerOverrideHost || [this._sfuServer.url];
5133
5142
  const searchParams = new URLSearchParams(Object.assign({ clientId: this._selfId, organizationId: this._room.organizationId, roomName: this._room.name, eventClaim: this._room.isClaimed ? this._eventClaim : null, lowBw: "true" }, Object.keys(this._features || {})
5134
5143
  .filter((featureKey) => this._features[featureKey] && /^sfu/.test(featureKey))
@@ -5956,7 +5965,6 @@ class VegaRtcManager {
5956
5965
  }
5957
5966
  acceptNewStream({ streamId, clientId }) {
5958
5967
  logger$1.info("acceptNewStream()", { streamId, clientId });
5959
- this.rtcStatsReconnect();
5960
5968
  const clientState = this._getOrCreateClientState(clientId);
5961
5969
  const isScreenShare = streamId !== clientId;
5962
5970
  if (isScreenShare) {
@@ -6364,6 +6372,7 @@ class RtcManagerDispatcher {
6364
6372
  else {
6365
6373
  rtcManager = new P2pRtcManager(config);
6366
6374
  }
6375
+ rtcManager.rtcStatsReconnect();
6367
6376
  rtcManager.setupSocketListeners();
6368
6377
  emitter.emit(EVENTS.RTC_MANAGER_CREATED, { rtcManager });
6369
6378
  this.currentManager = rtcManager;
@@ -6473,6 +6482,7 @@ const logger = new Logger();
6473
6482
  class ReconnectManager extends EventEmitter {
6474
6483
  constructor(socket) {
6475
6484
  super();
6485
+ this.reconnectThresholdInMs = 0;
6476
6486
  this._socket = socket;
6477
6487
  this._clients = {};
6478
6488
  this._signalDisconnectTime = undefined;
@@ -6498,6 +6508,7 @@ class ReconnectManager extends EventEmitter {
6498
6508
  _onRoomJoined(payload) {
6499
6509
  var _a, _b;
6500
6510
  return __awaiter(this, void 0, void 0, function* () {
6511
+ this.reconnectThresholdInMs = (payload.disconnectTimeout || 0) * 0.8;
6501
6512
  if (!((_a = payload.room) === null || _a === void 0 ? void 0 : _a.clients)) {
6502
6513
  this.emit(PROTOCOL_RESPONSES.ROOM_JOINED, payload);
6503
6514
  return;
@@ -6751,6 +6762,7 @@ class ServerSocket {
6751
6762
  }
6752
6763
  });
6753
6764
  this._socket.on("disconnect", () => {
6765
+ this.disconnectTimestamp = Date.now();
6754
6766
  if (this.noopKeepaliveInterval) {
6755
6767
  clearInterval(this.noopKeepaliveInterval);
6756
6768
  this.noopKeepaliveInterval = null;
@@ -6834,6 +6846,10 @@ class ServerSocket {
6834
6846
  var _a;
6835
6847
  return (_a = this._reconnectManager) === null || _a === void 0 ? void 0 : _a.metrics;
6836
6848
  }
6849
+ getReconnectThreshold() {
6850
+ var _a;
6851
+ return (_a = this._reconnectManager) === null || _a === void 0 ? void 0 : _a.reconnectThresholdInMs;
6852
+ }
6837
6853
  }
6838
6854
 
6839
6855
  const defaultSubdomainPattern = /^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,77 @@
1
1
  import EventEmitter, { EventEmitter as EventEmitter$1 } from 'events';
2
2
  import * as mediasoup_client_lib_Device from 'mediasoup-client/lib/Device';
3
3
 
4
- declare const getIssuesAndMetrics: () => any;
5
- declare function subscribeIssues(subscription: any): {
6
- stop(): void;
4
+ interface MetricData {
5
+ ticks: number;
6
+ sum: number;
7
+ avg: number;
8
+ min: number;
9
+ max: number;
10
+ }
11
+ interface MetricDataAggregated {
12
+ ticks: number;
13
+ sum: number;
14
+ min: number;
15
+ max: number;
16
+ avg: number;
17
+ curTicks: number;
18
+ curMin: number;
19
+ curMax: number;
20
+ curAvg: number;
21
+ curSum: number;
22
+ totTicks: number;
23
+ totMin: number;
24
+ totMax: number;
25
+ totAvg: number;
26
+ totSum: number;
27
+ }
28
+ type AggregatedMetrics = {
29
+ [aggregatedMetricKey: string]: MetricDataAggregated;
30
+ };
31
+ interface IssueData {
32
+ active: boolean;
33
+ ticks: number;
34
+ registered: number;
35
+ initial: number;
36
+ periods: number;
37
+ current: number;
38
+ longest: number;
39
+ }
40
+ interface IssueDataAggregated {
41
+ active: boolean;
42
+ ticks: number;
43
+ registered: number;
44
+ initial: number;
45
+ curTicks: number;
46
+ curRegistered: number;
47
+ }
48
+ type AggregatedIssues = {
49
+ [aggregatedIssueKey: string]: IssueDataAggregated;
50
+ };
51
+ type IssuesAndMetrics = {
52
+ issues: {
53
+ [issueKey: string]: IssueData;
54
+ };
55
+ metrics: {
56
+ [metricKey: string]: MetricData;
57
+ };
58
+ };
59
+ type IssuesAndMetricsAggregated = {
60
+ issues: AggregatedIssues;
61
+ metrics: AggregatedMetrics;
62
+ };
63
+ type IssuesAndMetricsByView = {
64
+ [clientId: string]: IssuesAndMetrics | IssuesAndMetricsAggregated;
65
+ aggregated: IssuesAndMetricsAggregated;
66
+ };
67
+ declare const getIssuesAndMetrics: () => {
68
+ [x: string]: IssuesAndMetrics | IssuesAndMetricsAggregated;
69
+ aggregated: IssuesAndMetricsAggregated;
70
+ };
71
+ declare function subscribeIssues(subscription: {
72
+ onUpdatedIssues: (issuesAndMetricsByView: IssuesAndMetricsByView, statsByView: any, clients: any) => void;
73
+ }): {
74
+ stop: () => void;
7
75
  };
8
76
 
9
77
  declare function startPerformanceMonitor({ onMetricsUpdated, onTerminated, isHidden, }: {
@@ -159,6 +227,7 @@ declare class ReconnectManager extends EventEmitter {
159
227
  evaluationFailed: number;
160
228
  roomJoined: number;
161
229
  };
230
+ reconnectThresholdInMs: number;
162
231
  constructor(socket: any);
163
232
  _onRoomJoined(payload: any): Promise<void>;
164
233
  _onClientLeft(payload: any): void;
@@ -187,6 +256,7 @@ declare class ServerSocket {
187
256
  _reconnectManager?: ReconnectManager | null;
188
257
  noopKeepaliveInterval: any;
189
258
  _wasConnectedUsingWebsocket?: boolean;
259
+ disconnectTimestamp: number | undefined;
190
260
  constructor(hostName: string, optionsOverrides?: any, glitchFree?: boolean);
191
261
  setRtcManager(rtcManager?: RtcManager): void;
192
262
  connect(): void;
@@ -208,6 +278,7 @@ declare class ServerSocket {
208
278
  evaluationFailed: number;
209
279
  roomJoined: number;
210
280
  } | undefined;
281
+ getReconnectThreshold(): number | undefined;
211
282
  }
212
283
 
213
284
  declare const maybeTurnOnly: (transportConfig: any, features: {
@@ -524,6 +595,7 @@ interface RtcManager {
524
595
  disconnect(streamId: string, activeBreakout: boolean | null, eventClaim?: string): void;
525
596
  disconnectAll(): void;
526
597
  rtcStatsDisconnect(): void;
598
+ rtcStatsReconnect(): void;
527
599
  replaceTrack(oldTrack: CustomMediaStreamTrack, newTrack: CustomMediaStreamTrack): void;
528
600
  removeStream(streamId: string, _stream: MediaStream, requestedByClientId: string | null): void;
529
601
  shouldAcceptStreamsFromBothSides?: () => boolean;
@@ -1008,6 +1080,7 @@ declare class VegaConnection extends EventEmitter$1 {
1008
1080
  _setupSocket(): void;
1009
1081
  _tearDown(): void;
1010
1082
  close(): void;
1083
+ isConnected(): boolean;
1011
1084
  _onOpen(): void;
1012
1085
  _onMessage(event: MessageEvent): void;
1013
1086
  _onClose(): void;
@@ -1083,7 +1156,7 @@ declare class VegaRtcManager implements RtcManager {
1083
1156
  _room: any;
1084
1157
  _roomSessionId: any;
1085
1158
  _emitter: any;
1086
- _serverSocket: any;
1159
+ _serverSocket: ServerSocket;
1087
1160
  _webrtcProvider: any;
1088
1161
  _features: any;
1089
1162
  _eventClaim?: any;
@@ -1418,4 +1491,4 @@ declare class RtcStream {
1418
1491
  static getTypeFromId(id: string): string;
1419
1492
  }
1420
1493
 
1421
- export { type AddSpotlightRequest, type AudioEnableRequest, type AudioEnableRequestedEvent, type AudioEnabledEvent, BandwidthTester, type ChatMessage, type ClientKickedEvent, type ClientLeftEvent, type ClientMetadataPayload, type ClientMetadataReceivedEvent, type ClientRole, type ClientUnableToJoinEvent, type CloudRecordingStartedEvent, type Credentials, type CustomMediaStreamTrack, EVENTS, type GetConstraintsOptions, type GetDeviceDataResult, type GetMediaConstraintsOptions, type GetStreamOptions, type GetStreamResult, type GetUpdatedDevicesResult, type IdentifyDeviceRequest, type JoinRoomRequest, KNOCK_MESSAGES, KalmanFilter, type KnockAcceptedEvent, type KnockRejectedEvent, type KnockRoomRequest, type KnockerLeftEvent, type LiveTranscriptionStartedEvent, type LiveTranscriptionStoppedEvent, Logger, MAXIMUM_TURN_BANDWIDTH, MAXIMUM_TURN_BANDWIDTH_UNLIMITED, MEDIA_JITTER_BUFFER_TARGET, type NewClientEvent, NoDevicesError, P2pRtcManager, PROTOCOL_ERRORS, PROTOCOL_EVENTS, PROTOCOL_REQUESTS, PROTOCOL_RESPONSES, RELAY_MESSAGES, ReconnectManager, type RemoveSpotlightRequest, type RoleName, type RoomJoinedEvent, type RoomKnockedEvent, type RoomLockedEvent, type RoomSessionEndedEvent, type RtcClientConnectionStatusChangedPayload, RtcEventNames, type RtcEvents, type RtcLocalStreamTrackAddedPayload, type RtcLocalStreamTrackRemovedPayload, type RtcManager, type RtcManagerCreatedPayload, RtcManagerDispatcher, RtcStream, type RtcStreamAddedPayload, STREAM_TYPES, type ScreenshareStartedEvent, type ScreenshareStoppedEvent, type SendClientMetadataRequest, ServerSocket, Session, SfuV2Parser, type SignalClient, type SignalEvents, type SignalKnocker, type SignalRequests, type SocketConf, type SocketManager, type Spotlight, type SpotlightAddedEvent, type SpotlightRemovedEvent, type StatsMonitorOptions, type StatsMonitorState, TYPES, type TurnTransportProtocol, VegaConnection, VegaMediaQualityMonitor, VegaRtcManager, type VideoEnabledEvent, addAbsCaptureTimeExtMap, addExtMap, assert, buildDeviceList, calculateStd, captureAudioSsrcMetrics, captureCandidatePairInfoMetrics, captureCommonSsrcMetrics, captureSsrcInfo, captureVideoSsrcMetrics, changeMediaDirection, compareLocalDevices, createACFCalculator, createMicAnalyser, createWorker, deprioritizeH264, detectMicrophoneNotWorking, enumerate, filterMidExtension, filterMsidSemantic, fromLocation, generateByteString, getConstraints, getCurrentPeerConnections, getDeviceData, getDisplayMedia, getHandler, getIssuesAndMetrics, getMediaConstraints, getMediaSettings, getOptimalBitrate, getPeerConnectionIndex, getStats, getStream, getStream2, getUpdatedDevices, getUpdatedStats, getUserMedia, hasGetDisplayMedia, ipRegex, isMobile, isRelayed, maybeRejectNoH264, maybeTurnOnly, modifyMediaCapabilities, removePeerConnection, replaceSSRCs, replaceTracksInStream, _default as rtcManagerEvents, rtcStats, setClientProvider, setCodecPreferenceSDP, setPeerConnectionsForTests, setVideoBandwidthUsingSetParameters, standardDeviation, startPerformanceMonitor, stopStreamTracks, subscribeIssues, subscribeStats, variance };
1494
+ export { type AddSpotlightRequest, type AudioEnableRequest, type AudioEnableRequestedEvent, type AudioEnabledEvent, BandwidthTester, type ChatMessage, type ClientKickedEvent, type ClientLeftEvent, type ClientMetadataPayload, type ClientMetadataReceivedEvent, type ClientRole, type ClientUnableToJoinEvent, type CloudRecordingStartedEvent, type Credentials, type CustomMediaStreamTrack, EVENTS, type GetConstraintsOptions, type GetDeviceDataResult, type GetMediaConstraintsOptions, type GetStreamOptions, type GetStreamResult, type GetUpdatedDevicesResult, type IdentifyDeviceRequest, type IssuesAndMetricsByView, type JoinRoomRequest, KNOCK_MESSAGES, KalmanFilter, type KnockAcceptedEvent, type KnockRejectedEvent, type KnockRoomRequest, type KnockerLeftEvent, type LiveTranscriptionStartedEvent, type LiveTranscriptionStoppedEvent, Logger, MAXIMUM_TURN_BANDWIDTH, MAXIMUM_TURN_BANDWIDTH_UNLIMITED, MEDIA_JITTER_BUFFER_TARGET, type NewClientEvent, NoDevicesError, P2pRtcManager, PROTOCOL_ERRORS, PROTOCOL_EVENTS, PROTOCOL_REQUESTS, PROTOCOL_RESPONSES, RELAY_MESSAGES, ReconnectManager, type RemoveSpotlightRequest, type RoleName, type RoomJoinedEvent, type RoomKnockedEvent, type RoomLockedEvent, type RoomSessionEndedEvent, type RtcClientConnectionStatusChangedPayload, RtcEventNames, type RtcEvents, type RtcLocalStreamTrackAddedPayload, type RtcLocalStreamTrackRemovedPayload, type RtcManager, type RtcManagerCreatedPayload, RtcManagerDispatcher, RtcStream, type RtcStreamAddedPayload, STREAM_TYPES, type ScreenshareStartedEvent, type ScreenshareStoppedEvent, type SendClientMetadataRequest, ServerSocket, Session, SfuV2Parser, type SignalClient, type SignalEvents, type SignalKnocker, type SignalRequests, type SocketConf, type SocketManager, type Spotlight, type SpotlightAddedEvent, type SpotlightRemovedEvent, type StatsMonitorOptions, type StatsMonitorState, TYPES, type TurnTransportProtocol, VegaConnection, VegaMediaQualityMonitor, VegaRtcManager, type VideoEnabledEvent, addAbsCaptureTimeExtMap, addExtMap, assert, buildDeviceList, calculateStd, captureAudioSsrcMetrics, captureCandidatePairInfoMetrics, captureCommonSsrcMetrics, captureSsrcInfo, captureVideoSsrcMetrics, changeMediaDirection, compareLocalDevices, createACFCalculator, createMicAnalyser, createWorker, deprioritizeH264, detectMicrophoneNotWorking, enumerate, filterMidExtension, filterMsidSemantic, fromLocation, generateByteString, getConstraints, getCurrentPeerConnections, getDeviceData, getDisplayMedia, getHandler, getIssuesAndMetrics, getMediaConstraints, getMediaSettings, getOptimalBitrate, getPeerConnectionIndex, getStats, getStream, getStream2, getUpdatedDevices, getUpdatedStats, getUserMedia, hasGetDisplayMedia, ipRegex, isMobile, isRelayed, maybeRejectNoH264, maybeTurnOnly, modifyMediaCapabilities, removePeerConnection, replaceSSRCs, replaceTracksInStream, _default as rtcManagerEvents, rtcStats, setClientProvider, setCodecPreferenceSDP, setPeerConnectionsForTests, setVideoBandwidthUsingSetParameters, standardDeviation, startPerformanceMonitor, stopStreamTracks, subscribeIssues, subscribeStats, variance };
package/dist/index.d.mts CHANGED
@@ -1,9 +1,77 @@
1
1
  import EventEmitter, { EventEmitter as EventEmitter$1 } from 'events';
2
2
  import * as mediasoup_client_lib_Device from 'mediasoup-client/lib/Device';
3
3
 
4
- declare const getIssuesAndMetrics: () => any;
5
- declare function subscribeIssues(subscription: any): {
6
- stop(): void;
4
+ interface MetricData {
5
+ ticks: number;
6
+ sum: number;
7
+ avg: number;
8
+ min: number;
9
+ max: number;
10
+ }
11
+ interface MetricDataAggregated {
12
+ ticks: number;
13
+ sum: number;
14
+ min: number;
15
+ max: number;
16
+ avg: number;
17
+ curTicks: number;
18
+ curMin: number;
19
+ curMax: number;
20
+ curAvg: number;
21
+ curSum: number;
22
+ totTicks: number;
23
+ totMin: number;
24
+ totMax: number;
25
+ totAvg: number;
26
+ totSum: number;
27
+ }
28
+ type AggregatedMetrics = {
29
+ [aggregatedMetricKey: string]: MetricDataAggregated;
30
+ };
31
+ interface IssueData {
32
+ active: boolean;
33
+ ticks: number;
34
+ registered: number;
35
+ initial: number;
36
+ periods: number;
37
+ current: number;
38
+ longest: number;
39
+ }
40
+ interface IssueDataAggregated {
41
+ active: boolean;
42
+ ticks: number;
43
+ registered: number;
44
+ initial: number;
45
+ curTicks: number;
46
+ curRegistered: number;
47
+ }
48
+ type AggregatedIssues = {
49
+ [aggregatedIssueKey: string]: IssueDataAggregated;
50
+ };
51
+ type IssuesAndMetrics = {
52
+ issues: {
53
+ [issueKey: string]: IssueData;
54
+ };
55
+ metrics: {
56
+ [metricKey: string]: MetricData;
57
+ };
58
+ };
59
+ type IssuesAndMetricsAggregated = {
60
+ issues: AggregatedIssues;
61
+ metrics: AggregatedMetrics;
62
+ };
63
+ type IssuesAndMetricsByView = {
64
+ [clientId: string]: IssuesAndMetrics | IssuesAndMetricsAggregated;
65
+ aggregated: IssuesAndMetricsAggregated;
66
+ };
67
+ declare const getIssuesAndMetrics: () => {
68
+ [x: string]: IssuesAndMetrics | IssuesAndMetricsAggregated;
69
+ aggregated: IssuesAndMetricsAggregated;
70
+ };
71
+ declare function subscribeIssues(subscription: {
72
+ onUpdatedIssues: (issuesAndMetricsByView: IssuesAndMetricsByView, statsByView: any, clients: any) => void;
73
+ }): {
74
+ stop: () => void;
7
75
  };
8
76
 
9
77
  declare function startPerformanceMonitor({ onMetricsUpdated, onTerminated, isHidden, }: {
@@ -159,6 +227,7 @@ declare class ReconnectManager extends EventEmitter {
159
227
  evaluationFailed: number;
160
228
  roomJoined: number;
161
229
  };
230
+ reconnectThresholdInMs: number;
162
231
  constructor(socket: any);
163
232
  _onRoomJoined(payload: any): Promise<void>;
164
233
  _onClientLeft(payload: any): void;
@@ -187,6 +256,7 @@ declare class ServerSocket {
187
256
  _reconnectManager?: ReconnectManager | null;
188
257
  noopKeepaliveInterval: any;
189
258
  _wasConnectedUsingWebsocket?: boolean;
259
+ disconnectTimestamp: number | undefined;
190
260
  constructor(hostName: string, optionsOverrides?: any, glitchFree?: boolean);
191
261
  setRtcManager(rtcManager?: RtcManager): void;
192
262
  connect(): void;
@@ -208,6 +278,7 @@ declare class ServerSocket {
208
278
  evaluationFailed: number;
209
279
  roomJoined: number;
210
280
  } | undefined;
281
+ getReconnectThreshold(): number | undefined;
211
282
  }
212
283
 
213
284
  declare const maybeTurnOnly: (transportConfig: any, features: {
@@ -524,6 +595,7 @@ interface RtcManager {
524
595
  disconnect(streamId: string, activeBreakout: boolean | null, eventClaim?: string): void;
525
596
  disconnectAll(): void;
526
597
  rtcStatsDisconnect(): void;
598
+ rtcStatsReconnect(): void;
527
599
  replaceTrack(oldTrack: CustomMediaStreamTrack, newTrack: CustomMediaStreamTrack): void;
528
600
  removeStream(streamId: string, _stream: MediaStream, requestedByClientId: string | null): void;
529
601
  shouldAcceptStreamsFromBothSides?: () => boolean;
@@ -1008,6 +1080,7 @@ declare class VegaConnection extends EventEmitter$1 {
1008
1080
  _setupSocket(): void;
1009
1081
  _tearDown(): void;
1010
1082
  close(): void;
1083
+ isConnected(): boolean;
1011
1084
  _onOpen(): void;
1012
1085
  _onMessage(event: MessageEvent): void;
1013
1086
  _onClose(): void;
@@ -1083,7 +1156,7 @@ declare class VegaRtcManager implements RtcManager {
1083
1156
  _room: any;
1084
1157
  _roomSessionId: any;
1085
1158
  _emitter: any;
1086
- _serverSocket: any;
1159
+ _serverSocket: ServerSocket;
1087
1160
  _webrtcProvider: any;
1088
1161
  _features: any;
1089
1162
  _eventClaim?: any;
@@ -1418,4 +1491,4 @@ declare class RtcStream {
1418
1491
  static getTypeFromId(id: string): string;
1419
1492
  }
1420
1493
 
1421
- export { type AddSpotlightRequest, type AudioEnableRequest, type AudioEnableRequestedEvent, type AudioEnabledEvent, BandwidthTester, type ChatMessage, type ClientKickedEvent, type ClientLeftEvent, type ClientMetadataPayload, type ClientMetadataReceivedEvent, type ClientRole, type ClientUnableToJoinEvent, type CloudRecordingStartedEvent, type Credentials, type CustomMediaStreamTrack, EVENTS, type GetConstraintsOptions, type GetDeviceDataResult, type GetMediaConstraintsOptions, type GetStreamOptions, type GetStreamResult, type GetUpdatedDevicesResult, type IdentifyDeviceRequest, type JoinRoomRequest, KNOCK_MESSAGES, KalmanFilter, type KnockAcceptedEvent, type KnockRejectedEvent, type KnockRoomRequest, type KnockerLeftEvent, type LiveTranscriptionStartedEvent, type LiveTranscriptionStoppedEvent, Logger, MAXIMUM_TURN_BANDWIDTH, MAXIMUM_TURN_BANDWIDTH_UNLIMITED, MEDIA_JITTER_BUFFER_TARGET, type NewClientEvent, NoDevicesError, P2pRtcManager, PROTOCOL_ERRORS, PROTOCOL_EVENTS, PROTOCOL_REQUESTS, PROTOCOL_RESPONSES, RELAY_MESSAGES, ReconnectManager, type RemoveSpotlightRequest, type RoleName, type RoomJoinedEvent, type RoomKnockedEvent, type RoomLockedEvent, type RoomSessionEndedEvent, type RtcClientConnectionStatusChangedPayload, RtcEventNames, type RtcEvents, type RtcLocalStreamTrackAddedPayload, type RtcLocalStreamTrackRemovedPayload, type RtcManager, type RtcManagerCreatedPayload, RtcManagerDispatcher, RtcStream, type RtcStreamAddedPayload, STREAM_TYPES, type ScreenshareStartedEvent, type ScreenshareStoppedEvent, type SendClientMetadataRequest, ServerSocket, Session, SfuV2Parser, type SignalClient, type SignalEvents, type SignalKnocker, type SignalRequests, type SocketConf, type SocketManager, type Spotlight, type SpotlightAddedEvent, type SpotlightRemovedEvent, type StatsMonitorOptions, type StatsMonitorState, TYPES, type TurnTransportProtocol, VegaConnection, VegaMediaQualityMonitor, VegaRtcManager, type VideoEnabledEvent, addAbsCaptureTimeExtMap, addExtMap, assert, buildDeviceList, calculateStd, captureAudioSsrcMetrics, captureCandidatePairInfoMetrics, captureCommonSsrcMetrics, captureSsrcInfo, captureVideoSsrcMetrics, changeMediaDirection, compareLocalDevices, createACFCalculator, createMicAnalyser, createWorker, deprioritizeH264, detectMicrophoneNotWorking, enumerate, filterMidExtension, filterMsidSemantic, fromLocation, generateByteString, getConstraints, getCurrentPeerConnections, getDeviceData, getDisplayMedia, getHandler, getIssuesAndMetrics, getMediaConstraints, getMediaSettings, getOptimalBitrate, getPeerConnectionIndex, getStats, getStream, getStream2, getUpdatedDevices, getUpdatedStats, getUserMedia, hasGetDisplayMedia, ipRegex, isMobile, isRelayed, maybeRejectNoH264, maybeTurnOnly, modifyMediaCapabilities, removePeerConnection, replaceSSRCs, replaceTracksInStream, _default as rtcManagerEvents, rtcStats, setClientProvider, setCodecPreferenceSDP, setPeerConnectionsForTests, setVideoBandwidthUsingSetParameters, standardDeviation, startPerformanceMonitor, stopStreamTracks, subscribeIssues, subscribeStats, variance };
1494
+ export { type AddSpotlightRequest, type AudioEnableRequest, type AudioEnableRequestedEvent, type AudioEnabledEvent, BandwidthTester, type ChatMessage, type ClientKickedEvent, type ClientLeftEvent, type ClientMetadataPayload, type ClientMetadataReceivedEvent, type ClientRole, type ClientUnableToJoinEvent, type CloudRecordingStartedEvent, type Credentials, type CustomMediaStreamTrack, EVENTS, type GetConstraintsOptions, type GetDeviceDataResult, type GetMediaConstraintsOptions, type GetStreamOptions, type GetStreamResult, type GetUpdatedDevicesResult, type IdentifyDeviceRequest, type IssuesAndMetricsByView, type JoinRoomRequest, KNOCK_MESSAGES, KalmanFilter, type KnockAcceptedEvent, type KnockRejectedEvent, type KnockRoomRequest, type KnockerLeftEvent, type LiveTranscriptionStartedEvent, type LiveTranscriptionStoppedEvent, Logger, MAXIMUM_TURN_BANDWIDTH, MAXIMUM_TURN_BANDWIDTH_UNLIMITED, MEDIA_JITTER_BUFFER_TARGET, type NewClientEvent, NoDevicesError, P2pRtcManager, PROTOCOL_ERRORS, PROTOCOL_EVENTS, PROTOCOL_REQUESTS, PROTOCOL_RESPONSES, RELAY_MESSAGES, ReconnectManager, type RemoveSpotlightRequest, type RoleName, type RoomJoinedEvent, type RoomKnockedEvent, type RoomLockedEvent, type RoomSessionEndedEvent, type RtcClientConnectionStatusChangedPayload, RtcEventNames, type RtcEvents, type RtcLocalStreamTrackAddedPayload, type RtcLocalStreamTrackRemovedPayload, type RtcManager, type RtcManagerCreatedPayload, RtcManagerDispatcher, RtcStream, type RtcStreamAddedPayload, STREAM_TYPES, type ScreenshareStartedEvent, type ScreenshareStoppedEvent, type SendClientMetadataRequest, ServerSocket, Session, SfuV2Parser, type SignalClient, type SignalEvents, type SignalKnocker, type SignalRequests, type SocketConf, type SocketManager, type Spotlight, type SpotlightAddedEvent, type SpotlightRemovedEvent, type StatsMonitorOptions, type StatsMonitorState, TYPES, type TurnTransportProtocol, VegaConnection, VegaMediaQualityMonitor, VegaRtcManager, type VideoEnabledEvent, addAbsCaptureTimeExtMap, addExtMap, assert, buildDeviceList, calculateStd, captureAudioSsrcMetrics, captureCandidatePairInfoMetrics, captureCommonSsrcMetrics, captureSsrcInfo, captureVideoSsrcMetrics, changeMediaDirection, compareLocalDevices, createACFCalculator, createMicAnalyser, createWorker, deprioritizeH264, detectMicrophoneNotWorking, enumerate, filterMidExtension, filterMsidSemantic, fromLocation, generateByteString, getConstraints, getCurrentPeerConnections, getDeviceData, getDisplayMedia, getHandler, getIssuesAndMetrics, getMediaConstraints, getMediaSettings, getOptimalBitrate, getPeerConnectionIndex, getStats, getStream, getStream2, getUpdatedDevices, getUpdatedStats, getUserMedia, hasGetDisplayMedia, ipRegex, isMobile, isRelayed, maybeRejectNoH264, maybeTurnOnly, modifyMediaCapabilities, removePeerConnection, replaceSSRCs, replaceTracksInStream, _default as rtcManagerEvents, rtcStats, setClientProvider, setCodecPreferenceSDP, setPeerConnectionsForTests, setVideoBandwidthUsingSetParameters, standardDeviation, startPerformanceMonitor, stopStreamTracks, subscribeIssues, subscribeStats, variance };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,77 @@
1
1
  import EventEmitter, { EventEmitter as EventEmitter$1 } from 'events';
2
2
  import * as mediasoup_client_lib_Device from 'mediasoup-client/lib/Device';
3
3
 
4
- declare const getIssuesAndMetrics: () => any;
5
- declare function subscribeIssues(subscription: any): {
6
- stop(): void;
4
+ interface MetricData {
5
+ ticks: number;
6
+ sum: number;
7
+ avg: number;
8
+ min: number;
9
+ max: number;
10
+ }
11
+ interface MetricDataAggregated {
12
+ ticks: number;
13
+ sum: number;
14
+ min: number;
15
+ max: number;
16
+ avg: number;
17
+ curTicks: number;
18
+ curMin: number;
19
+ curMax: number;
20
+ curAvg: number;
21
+ curSum: number;
22
+ totTicks: number;
23
+ totMin: number;
24
+ totMax: number;
25
+ totAvg: number;
26
+ totSum: number;
27
+ }
28
+ type AggregatedMetrics = {
29
+ [aggregatedMetricKey: string]: MetricDataAggregated;
30
+ };
31
+ interface IssueData {
32
+ active: boolean;
33
+ ticks: number;
34
+ registered: number;
35
+ initial: number;
36
+ periods: number;
37
+ current: number;
38
+ longest: number;
39
+ }
40
+ interface IssueDataAggregated {
41
+ active: boolean;
42
+ ticks: number;
43
+ registered: number;
44
+ initial: number;
45
+ curTicks: number;
46
+ curRegistered: number;
47
+ }
48
+ type AggregatedIssues = {
49
+ [aggregatedIssueKey: string]: IssueDataAggregated;
50
+ };
51
+ type IssuesAndMetrics = {
52
+ issues: {
53
+ [issueKey: string]: IssueData;
54
+ };
55
+ metrics: {
56
+ [metricKey: string]: MetricData;
57
+ };
58
+ };
59
+ type IssuesAndMetricsAggregated = {
60
+ issues: AggregatedIssues;
61
+ metrics: AggregatedMetrics;
62
+ };
63
+ type IssuesAndMetricsByView = {
64
+ [clientId: string]: IssuesAndMetrics | IssuesAndMetricsAggregated;
65
+ aggregated: IssuesAndMetricsAggregated;
66
+ };
67
+ declare const getIssuesAndMetrics: () => {
68
+ [x: string]: IssuesAndMetrics | IssuesAndMetricsAggregated;
69
+ aggregated: IssuesAndMetricsAggregated;
70
+ };
71
+ declare function subscribeIssues(subscription: {
72
+ onUpdatedIssues: (issuesAndMetricsByView: IssuesAndMetricsByView, statsByView: any, clients: any) => void;
73
+ }): {
74
+ stop: () => void;
7
75
  };
8
76
 
9
77
  declare function startPerformanceMonitor({ onMetricsUpdated, onTerminated, isHidden, }: {
@@ -159,6 +227,7 @@ declare class ReconnectManager extends EventEmitter {
159
227
  evaluationFailed: number;
160
228
  roomJoined: number;
161
229
  };
230
+ reconnectThresholdInMs: number;
162
231
  constructor(socket: any);
163
232
  _onRoomJoined(payload: any): Promise<void>;
164
233
  _onClientLeft(payload: any): void;
@@ -187,6 +256,7 @@ declare class ServerSocket {
187
256
  _reconnectManager?: ReconnectManager | null;
188
257
  noopKeepaliveInterval: any;
189
258
  _wasConnectedUsingWebsocket?: boolean;
259
+ disconnectTimestamp: number | undefined;
190
260
  constructor(hostName: string, optionsOverrides?: any, glitchFree?: boolean);
191
261
  setRtcManager(rtcManager?: RtcManager): void;
192
262
  connect(): void;
@@ -208,6 +278,7 @@ declare class ServerSocket {
208
278
  evaluationFailed: number;
209
279
  roomJoined: number;
210
280
  } | undefined;
281
+ getReconnectThreshold(): number | undefined;
211
282
  }
212
283
 
213
284
  declare const maybeTurnOnly: (transportConfig: any, features: {
@@ -524,6 +595,7 @@ interface RtcManager {
524
595
  disconnect(streamId: string, activeBreakout: boolean | null, eventClaim?: string): void;
525
596
  disconnectAll(): void;
526
597
  rtcStatsDisconnect(): void;
598
+ rtcStatsReconnect(): void;
527
599
  replaceTrack(oldTrack: CustomMediaStreamTrack, newTrack: CustomMediaStreamTrack): void;
528
600
  removeStream(streamId: string, _stream: MediaStream, requestedByClientId: string | null): void;
529
601
  shouldAcceptStreamsFromBothSides?: () => boolean;
@@ -1008,6 +1080,7 @@ declare class VegaConnection extends EventEmitter$1 {
1008
1080
  _setupSocket(): void;
1009
1081
  _tearDown(): void;
1010
1082
  close(): void;
1083
+ isConnected(): boolean;
1011
1084
  _onOpen(): void;
1012
1085
  _onMessage(event: MessageEvent): void;
1013
1086
  _onClose(): void;
@@ -1083,7 +1156,7 @@ declare class VegaRtcManager implements RtcManager {
1083
1156
  _room: any;
1084
1157
  _roomSessionId: any;
1085
1158
  _emitter: any;
1086
- _serverSocket: any;
1159
+ _serverSocket: ServerSocket;
1087
1160
  _webrtcProvider: any;
1088
1161
  _features: any;
1089
1162
  _eventClaim?: any;
@@ -1418,4 +1491,4 @@ declare class RtcStream {
1418
1491
  static getTypeFromId(id: string): string;
1419
1492
  }
1420
1493
 
1421
- export { type AddSpotlightRequest, type AudioEnableRequest, type AudioEnableRequestedEvent, type AudioEnabledEvent, BandwidthTester, type ChatMessage, type ClientKickedEvent, type ClientLeftEvent, type ClientMetadataPayload, type ClientMetadataReceivedEvent, type ClientRole, type ClientUnableToJoinEvent, type CloudRecordingStartedEvent, type Credentials, type CustomMediaStreamTrack, EVENTS, type GetConstraintsOptions, type GetDeviceDataResult, type GetMediaConstraintsOptions, type GetStreamOptions, type GetStreamResult, type GetUpdatedDevicesResult, type IdentifyDeviceRequest, type JoinRoomRequest, KNOCK_MESSAGES, KalmanFilter, type KnockAcceptedEvent, type KnockRejectedEvent, type KnockRoomRequest, type KnockerLeftEvent, type LiveTranscriptionStartedEvent, type LiveTranscriptionStoppedEvent, Logger, MAXIMUM_TURN_BANDWIDTH, MAXIMUM_TURN_BANDWIDTH_UNLIMITED, MEDIA_JITTER_BUFFER_TARGET, type NewClientEvent, NoDevicesError, P2pRtcManager, PROTOCOL_ERRORS, PROTOCOL_EVENTS, PROTOCOL_REQUESTS, PROTOCOL_RESPONSES, RELAY_MESSAGES, ReconnectManager, type RemoveSpotlightRequest, type RoleName, type RoomJoinedEvent, type RoomKnockedEvent, type RoomLockedEvent, type RoomSessionEndedEvent, type RtcClientConnectionStatusChangedPayload, RtcEventNames, type RtcEvents, type RtcLocalStreamTrackAddedPayload, type RtcLocalStreamTrackRemovedPayload, type RtcManager, type RtcManagerCreatedPayload, RtcManagerDispatcher, RtcStream, type RtcStreamAddedPayload, STREAM_TYPES, type ScreenshareStartedEvent, type ScreenshareStoppedEvent, type SendClientMetadataRequest, ServerSocket, Session, SfuV2Parser, type SignalClient, type SignalEvents, type SignalKnocker, type SignalRequests, type SocketConf, type SocketManager, type Spotlight, type SpotlightAddedEvent, type SpotlightRemovedEvent, type StatsMonitorOptions, type StatsMonitorState, TYPES, type TurnTransportProtocol, VegaConnection, VegaMediaQualityMonitor, VegaRtcManager, type VideoEnabledEvent, addAbsCaptureTimeExtMap, addExtMap, assert, buildDeviceList, calculateStd, captureAudioSsrcMetrics, captureCandidatePairInfoMetrics, captureCommonSsrcMetrics, captureSsrcInfo, captureVideoSsrcMetrics, changeMediaDirection, compareLocalDevices, createACFCalculator, createMicAnalyser, createWorker, deprioritizeH264, detectMicrophoneNotWorking, enumerate, filterMidExtension, filterMsidSemantic, fromLocation, generateByteString, getConstraints, getCurrentPeerConnections, getDeviceData, getDisplayMedia, getHandler, getIssuesAndMetrics, getMediaConstraints, getMediaSettings, getOptimalBitrate, getPeerConnectionIndex, getStats, getStream, getStream2, getUpdatedDevices, getUpdatedStats, getUserMedia, hasGetDisplayMedia, ipRegex, isMobile, isRelayed, maybeRejectNoH264, maybeTurnOnly, modifyMediaCapabilities, removePeerConnection, replaceSSRCs, replaceTracksInStream, _default as rtcManagerEvents, rtcStats, setClientProvider, setCodecPreferenceSDP, setPeerConnectionsForTests, setVideoBandwidthUsingSetParameters, standardDeviation, startPerformanceMonitor, stopStreamTracks, subscribeIssues, subscribeStats, variance };
1494
+ export { type AddSpotlightRequest, type AudioEnableRequest, type AudioEnableRequestedEvent, type AudioEnabledEvent, BandwidthTester, type ChatMessage, type ClientKickedEvent, type ClientLeftEvent, type ClientMetadataPayload, type ClientMetadataReceivedEvent, type ClientRole, type ClientUnableToJoinEvent, type CloudRecordingStartedEvent, type Credentials, type CustomMediaStreamTrack, EVENTS, type GetConstraintsOptions, type GetDeviceDataResult, type GetMediaConstraintsOptions, type GetStreamOptions, type GetStreamResult, type GetUpdatedDevicesResult, type IdentifyDeviceRequest, type IssuesAndMetricsByView, type JoinRoomRequest, KNOCK_MESSAGES, KalmanFilter, type KnockAcceptedEvent, type KnockRejectedEvent, type KnockRoomRequest, type KnockerLeftEvent, type LiveTranscriptionStartedEvent, type LiveTranscriptionStoppedEvent, Logger, MAXIMUM_TURN_BANDWIDTH, MAXIMUM_TURN_BANDWIDTH_UNLIMITED, MEDIA_JITTER_BUFFER_TARGET, type NewClientEvent, NoDevicesError, P2pRtcManager, PROTOCOL_ERRORS, PROTOCOL_EVENTS, PROTOCOL_REQUESTS, PROTOCOL_RESPONSES, RELAY_MESSAGES, ReconnectManager, type RemoveSpotlightRequest, type RoleName, type RoomJoinedEvent, type RoomKnockedEvent, type RoomLockedEvent, type RoomSessionEndedEvent, type RtcClientConnectionStatusChangedPayload, RtcEventNames, type RtcEvents, type RtcLocalStreamTrackAddedPayload, type RtcLocalStreamTrackRemovedPayload, type RtcManager, type RtcManagerCreatedPayload, RtcManagerDispatcher, RtcStream, type RtcStreamAddedPayload, STREAM_TYPES, type ScreenshareStartedEvent, type ScreenshareStoppedEvent, type SendClientMetadataRequest, ServerSocket, Session, SfuV2Parser, type SignalClient, type SignalEvents, type SignalKnocker, type SignalRequests, type SocketConf, type SocketManager, type Spotlight, type SpotlightAddedEvent, type SpotlightRemovedEvent, type StatsMonitorOptions, type StatsMonitorState, TYPES, type TurnTransportProtocol, VegaConnection, VegaMediaQualityMonitor, VegaRtcManager, type VideoEnabledEvent, addAbsCaptureTimeExtMap, addExtMap, assert, buildDeviceList, calculateStd, captureAudioSsrcMetrics, captureCandidatePairInfoMetrics, captureCommonSsrcMetrics, captureSsrcInfo, captureVideoSsrcMetrics, changeMediaDirection, compareLocalDevices, createACFCalculator, createMicAnalyser, createWorker, deprioritizeH264, detectMicrophoneNotWorking, enumerate, filterMidExtension, filterMsidSemantic, fromLocation, generateByteString, getConstraints, getCurrentPeerConnections, getDeviceData, getDisplayMedia, getHandler, getIssuesAndMetrics, getMediaConstraints, getMediaSettings, getOptimalBitrate, getPeerConnectionIndex, getStats, getStream, getStream2, getUpdatedDevices, getUpdatedStats, getUserMedia, hasGetDisplayMedia, ipRegex, isMobile, isRelayed, maybeRejectNoH264, maybeTurnOnly, modifyMediaCapabilities, removePeerConnection, replaceSSRCs, replaceTracksInStream, _default as rtcManagerEvents, rtcStats, setClientProvider, setCodecPreferenceSDP, setPeerConnectionsForTests, setVideoBandwidthUsingSetParameters, standardDeviation, startPerformanceMonitor, stopStreamTracks, subscribeIssues, subscribeStats, variance };
package/dist/index.mjs CHANGED
@@ -886,13 +886,13 @@ const metrics = [
886
886
  id: "turn-usage",
887
887
  global: true,
888
888
  enabled: ({ stats }) => !!Object.values(stats.candidatePairs).length,
889
- value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.usingTurn)
889
+ value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.usingTurn),
890
890
  },
891
891
  {
892
892
  id: "turn-tls-usage",
893
893
  global: true,
894
894
  enabled: ({ stats }) => !!Object.values(stats.candidatePairs).length,
895
- value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.turnProtocol === 'tls')
895
+ value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.turnProtocol === "tls"),
896
896
  },
897
897
  {
898
898
  id: "concealment",
@@ -1400,6 +1400,10 @@ class VegaConnection extends EventEmitter {
1400
1400
  var _a;
1401
1401
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
1402
1402
  }
1403
+ isConnected() {
1404
+ var _a, _b;
1405
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN || ((_b = this.socket) === null || _b === void 0 ? void 0 : _b.readyState) === WebSocket.CONNECTING;
1406
+ }
1403
1407
  _onOpen() {
1404
1408
  logger$9.info("Connected");
1405
1409
  this.emit("open");
@@ -2521,10 +2525,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2521
2525
  if (hasPassedOnRoomSessionId &&
2522
2526
  newRoomSessionIdValue &&
2523
2527
  newRoomSessionIdValue !== oldRoomSessionIdValue) {
2524
- if (ws) {
2525
- ws.close();
2526
- return;
2527
- }
2528
+ ws === null || ws === void 0 ? void 0 : ws.close();
2528
2529
  }
2529
2530
  if (newRoomSessionIdValue)
2530
2531
  hasPassedOnRoomSessionId = true;
@@ -2556,7 +2557,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2556
2557
  else if (args[0] === "customEvent" && args[2].type === "featureFlags") {
2557
2558
  featureFlags = args;
2558
2559
  }
2559
- if (ws.readyState === WebSocket.OPEN) {
2560
+ if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.OPEN) {
2560
2561
  connectionAttempt = 0;
2561
2562
  ws.send(JSON.stringify(args));
2562
2563
  }
@@ -2570,7 +2571,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2570
2571
  else {
2571
2572
  buffer.push(args);
2572
2573
  }
2573
- if (ws.readyState === WebSocket.CLOSED && connectionShouldBeOpen) {
2574
+ if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.CLOSED && connectionShouldBeOpen) {
2574
2575
  setTimeout(() => {
2575
2576
  if (ws.readyState === WebSocket.CLOSED && connectionShouldBeOpen) {
2576
2577
  connection.connect();
@@ -2580,16 +2581,12 @@ function rtcStatsConnection(wsURL, logger = console) {
2580
2581
  },
2581
2582
  close: () => {
2582
2583
  connectionShouldBeOpen = false;
2583
- if (ws) {
2584
- ws.close();
2585
- }
2584
+ ws === null || ws === void 0 ? void 0 : ws.close();
2586
2585
  },
2587
2586
  connect: () => {
2588
2587
  connectionShouldBeOpen = true;
2589
2588
  connectionAttempt += 1;
2590
- if (ws) {
2591
- ws.close();
2592
- }
2589
+ ws === null || ws === void 0 ? void 0 : ws.close();
2593
2590
  connection.connected = true;
2594
2591
  ws = new WebSocket(wsURL + window.location.pathname, RTCSTATS_PROTOCOL_VERSION);
2595
2592
  ws.onerror = (e) => {
@@ -2641,7 +2638,6 @@ function rtcStatsConnection(wsURL, logger = console) {
2641
2638
  };
2642
2639
  },
2643
2640
  };
2644
- connection.connect();
2645
2641
  return connection;
2646
2642
  }
2647
2643
  const server = rtcStatsConnection(process.env.RTCSTATS_URL || "wss://rtcstats.srv.whereby.com");
@@ -4138,7 +4134,6 @@ class P2pRtcManager {
4138
4134
  this._videoTrackBeingMonitored = track;
4139
4135
  }
4140
4136
  _connect(clientId) {
4141
- this.rtcStatsReconnect();
4142
4137
  let session = this._getSession(clientId);
4143
4138
  let initialBandwidth = (session && session.bandwidth) || 0;
4144
4139
  if (session) {
@@ -5098,6 +5093,9 @@ class VegaRtcManager {
5098
5093
  }), this._serverSocket.on(PROTOCOL_RESPONSES.ROOM_JOINED, () => {
5099
5094
  if (this._screenVideoTrack)
5100
5095
  this._emitScreenshareStarted();
5096
+ if (this._features.sfuReconnectV2On && !this._vegaConnection.isConnected() && this._reconnect) {
5097
+ this._connect();
5098
+ }
5101
5099
  }));
5102
5100
  this._connect();
5103
5101
  }
@@ -5108,6 +5106,17 @@ class VegaRtcManager {
5108
5106
  });
5109
5107
  }
5110
5108
  _connect() {
5109
+ if (this._features.sfuReconnectV2On) {
5110
+ if (!this._serverSocket.isConnected()) {
5111
+ const reconnectThresholdInMs = this._serverSocket.getReconnectThreshold();
5112
+ if (!reconnectThresholdInMs)
5113
+ return;
5114
+ if (Date.now() > (this._serverSocket.disconnectTimestamp || 0) + reconnectThresholdInMs)
5115
+ return;
5116
+ }
5117
+ if (this._reconnectTimeOut)
5118
+ clearTimeout(this._reconnectTimeOut);
5119
+ }
5111
5120
  const host = this._features.sfuServerOverrideHost || [this._sfuServer.url];
5112
5121
  const searchParams = new URLSearchParams(Object.assign({ clientId: this._selfId, organizationId: this._room.organizationId, roomName: this._room.name, eventClaim: this._room.isClaimed ? this._eventClaim : null, lowBw: "true" }, Object.keys(this._features || {})
5113
5122
  .filter((featureKey) => this._features[featureKey] && /^sfu/.test(featureKey))
@@ -5935,7 +5944,6 @@ class VegaRtcManager {
5935
5944
  }
5936
5945
  acceptNewStream({ streamId, clientId }) {
5937
5946
  logger$1.info("acceptNewStream()", { streamId, clientId });
5938
- this.rtcStatsReconnect();
5939
5947
  const clientState = this._getOrCreateClientState(clientId);
5940
5948
  const isScreenShare = streamId !== clientId;
5941
5949
  if (isScreenShare) {
@@ -6343,6 +6351,7 @@ class RtcManagerDispatcher {
6343
6351
  else {
6344
6352
  rtcManager = new P2pRtcManager(config);
6345
6353
  }
6354
+ rtcManager.rtcStatsReconnect();
6346
6355
  rtcManager.setupSocketListeners();
6347
6356
  emitter.emit(EVENTS.RTC_MANAGER_CREATED, { rtcManager });
6348
6357
  this.currentManager = rtcManager;
@@ -6452,6 +6461,7 @@ const logger = new Logger();
6452
6461
  class ReconnectManager extends EventEmitter$1 {
6453
6462
  constructor(socket) {
6454
6463
  super();
6464
+ this.reconnectThresholdInMs = 0;
6455
6465
  this._socket = socket;
6456
6466
  this._clients = {};
6457
6467
  this._signalDisconnectTime = undefined;
@@ -6477,6 +6487,7 @@ class ReconnectManager extends EventEmitter$1 {
6477
6487
  _onRoomJoined(payload) {
6478
6488
  var _a, _b;
6479
6489
  return __awaiter(this, void 0, void 0, function* () {
6490
+ this.reconnectThresholdInMs = (payload.disconnectTimeout || 0) * 0.8;
6480
6491
  if (!((_a = payload.room) === null || _a === void 0 ? void 0 : _a.clients)) {
6481
6492
  this.emit(PROTOCOL_RESPONSES.ROOM_JOINED, payload);
6482
6493
  return;
@@ -6730,6 +6741,7 @@ class ServerSocket {
6730
6741
  }
6731
6742
  });
6732
6743
  this._socket.on("disconnect", () => {
6744
+ this.disconnectTimestamp = Date.now();
6733
6745
  if (this.noopKeepaliveInterval) {
6734
6746
  clearInterval(this.noopKeepaliveInterval);
6735
6747
  this.noopKeepaliveInterval = null;
@@ -6813,6 +6825,10 @@ class ServerSocket {
6813
6825
  var _a;
6814
6826
  return (_a = this._reconnectManager) === null || _a === void 0 ? void 0 : _a.metrics;
6815
6827
  }
6828
+ getReconnectThreshold() {
6829
+ var _a;
6830
+ return (_a = this._reconnectManager) === null || _a === void 0 ? void 0 : _a.reconnectThresholdInMs;
6831
+ }
6816
6832
  }
6817
6833
 
6818
6834
  const defaultSubdomainPattern = /^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/;
@@ -886,13 +886,13 @@ const metrics = [
886
886
  id: "turn-usage",
887
887
  global: true,
888
888
  enabled: ({ stats }) => !!Object.values(stats.candidatePairs).length,
889
- value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.usingTurn)
889
+ value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.usingTurn),
890
890
  },
891
891
  {
892
892
  id: "turn-tls-usage",
893
893
  global: true,
894
894
  enabled: ({ stats }) => !!Object.values(stats.candidatePairs).length,
895
- value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.turnProtocol === 'tls')
895
+ value: ({ stats }) => Object.values(stats.candidatePairs).some((cp) => cp.turnProtocol === "tls"),
896
896
  },
897
897
  {
898
898
  id: "concealment",
@@ -1400,6 +1400,10 @@ class VegaConnection extends EventEmitter {
1400
1400
  var _a;
1401
1401
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
1402
1402
  }
1403
+ isConnected() {
1404
+ var _a, _b;
1405
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN || ((_b = this.socket) === null || _b === void 0 ? void 0 : _b.readyState) === WebSocket.CONNECTING;
1406
+ }
1403
1407
  _onOpen() {
1404
1408
  logger$9.info("Connected");
1405
1409
  this.emit("open");
@@ -2521,10 +2525,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2521
2525
  if (hasPassedOnRoomSessionId &&
2522
2526
  newRoomSessionIdValue &&
2523
2527
  newRoomSessionIdValue !== oldRoomSessionIdValue) {
2524
- if (ws) {
2525
- ws.close();
2526
- return;
2527
- }
2528
+ ws === null || ws === void 0 ? void 0 : ws.close();
2528
2529
  }
2529
2530
  if (newRoomSessionIdValue)
2530
2531
  hasPassedOnRoomSessionId = true;
@@ -2556,7 +2557,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2556
2557
  else if (args[0] === "customEvent" && args[2].type === "featureFlags") {
2557
2558
  featureFlags = args;
2558
2559
  }
2559
- if (ws.readyState === WebSocket.OPEN) {
2560
+ if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.OPEN) {
2560
2561
  connectionAttempt = 0;
2561
2562
  ws.send(JSON.stringify(args));
2562
2563
  }
@@ -2570,7 +2571,7 @@ function rtcStatsConnection(wsURL, logger = console) {
2570
2571
  else {
2571
2572
  buffer.push(args);
2572
2573
  }
2573
- if (ws.readyState === WebSocket.CLOSED && connectionShouldBeOpen) {
2574
+ if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.CLOSED && connectionShouldBeOpen) {
2574
2575
  setTimeout(() => {
2575
2576
  if (ws.readyState === WebSocket.CLOSED && connectionShouldBeOpen) {
2576
2577
  connection.connect();
@@ -2580,16 +2581,12 @@ function rtcStatsConnection(wsURL, logger = console) {
2580
2581
  },
2581
2582
  close: () => {
2582
2583
  connectionShouldBeOpen = false;
2583
- if (ws) {
2584
- ws.close();
2585
- }
2584
+ ws === null || ws === void 0 ? void 0 : ws.close();
2586
2585
  },
2587
2586
  connect: () => {
2588
2587
  connectionShouldBeOpen = true;
2589
2588
  connectionAttempt += 1;
2590
- if (ws) {
2591
- ws.close();
2592
- }
2589
+ ws === null || ws === void 0 ? void 0 : ws.close();
2593
2590
  connection.connected = true;
2594
2591
  ws = new WebSocket(wsURL + window.location.pathname, RTCSTATS_PROTOCOL_VERSION);
2595
2592
  ws.onerror = (e) => {
@@ -2641,7 +2638,6 @@ function rtcStatsConnection(wsURL, logger = console) {
2641
2638
  };
2642
2639
  },
2643
2640
  };
2644
- connection.connect();
2645
2641
  return connection;
2646
2642
  }
2647
2643
  const server = rtcStatsConnection(process.env.RTCSTATS_URL || "wss://rtcstats.srv.whereby.com");
@@ -4138,7 +4134,6 @@ class P2pRtcManager {
4138
4134
  this._videoTrackBeingMonitored = track;
4139
4135
  }
4140
4136
  _connect(clientId) {
4141
- this.rtcStatsReconnect();
4142
4137
  let session = this._getSession(clientId);
4143
4138
  let initialBandwidth = (session && session.bandwidth) || 0;
4144
4139
  if (session) {
@@ -5098,6 +5093,9 @@ class VegaRtcManager {
5098
5093
  }), this._serverSocket.on(PROTOCOL_RESPONSES.ROOM_JOINED, () => {
5099
5094
  if (this._screenVideoTrack)
5100
5095
  this._emitScreenshareStarted();
5096
+ if (this._features.sfuReconnectV2On && !this._vegaConnection.isConnected() && this._reconnect) {
5097
+ this._connect();
5098
+ }
5101
5099
  }));
5102
5100
  this._connect();
5103
5101
  }
@@ -5108,6 +5106,17 @@ class VegaRtcManager {
5108
5106
  });
5109
5107
  }
5110
5108
  _connect() {
5109
+ if (this._features.sfuReconnectV2On) {
5110
+ if (!this._serverSocket.isConnected()) {
5111
+ const reconnectThresholdInMs = this._serverSocket.getReconnectThreshold();
5112
+ if (!reconnectThresholdInMs)
5113
+ return;
5114
+ if (Date.now() > (this._serverSocket.disconnectTimestamp || 0) + reconnectThresholdInMs)
5115
+ return;
5116
+ }
5117
+ if (this._reconnectTimeOut)
5118
+ clearTimeout(this._reconnectTimeOut);
5119
+ }
5111
5120
  const host = this._features.sfuServerOverrideHost || [this._sfuServer.url];
5112
5121
  const searchParams = new URLSearchParams(Object.assign({ clientId: this._selfId, organizationId: this._room.organizationId, roomName: this._room.name, eventClaim: this._room.isClaimed ? this._eventClaim : null, lowBw: "true" }, Object.keys(this._features || {})
5113
5122
  .filter((featureKey) => this._features[featureKey] && /^sfu/.test(featureKey))
@@ -5935,7 +5944,6 @@ class VegaRtcManager {
5935
5944
  }
5936
5945
  acceptNewStream({ streamId, clientId }) {
5937
5946
  logger$1.info("acceptNewStream()", { streamId, clientId });
5938
- this.rtcStatsReconnect();
5939
5947
  const clientState = this._getOrCreateClientState(clientId);
5940
5948
  const isScreenShare = streamId !== clientId;
5941
5949
  if (isScreenShare) {
@@ -6343,6 +6351,7 @@ class RtcManagerDispatcher {
6343
6351
  else {
6344
6352
  rtcManager = new P2pRtcManager(config);
6345
6353
  }
6354
+ rtcManager.rtcStatsReconnect();
6346
6355
  rtcManager.setupSocketListeners();
6347
6356
  emitter.emit(EVENTS.RTC_MANAGER_CREATED, { rtcManager });
6348
6357
  this.currentManager = rtcManager;
@@ -6452,6 +6461,7 @@ const logger = new Logger();
6452
6461
  class ReconnectManager extends EventEmitter$1 {
6453
6462
  constructor(socket) {
6454
6463
  super();
6464
+ this.reconnectThresholdInMs = 0;
6455
6465
  this._socket = socket;
6456
6466
  this._clients = {};
6457
6467
  this._signalDisconnectTime = undefined;
@@ -6477,6 +6487,7 @@ class ReconnectManager extends EventEmitter$1 {
6477
6487
  _onRoomJoined(payload) {
6478
6488
  var _a, _b;
6479
6489
  return __awaiter(this, void 0, void 0, function* () {
6490
+ this.reconnectThresholdInMs = (payload.disconnectTimeout || 0) * 0.8;
6480
6491
  if (!((_a = payload.room) === null || _a === void 0 ? void 0 : _a.clients)) {
6481
6492
  this.emit(PROTOCOL_RESPONSES.ROOM_JOINED, payload);
6482
6493
  return;
@@ -6730,6 +6741,7 @@ class ServerSocket {
6730
6741
  }
6731
6742
  });
6732
6743
  this._socket.on("disconnect", () => {
6744
+ this.disconnectTimestamp = Date.now();
6733
6745
  if (this.noopKeepaliveInterval) {
6734
6746
  clearInterval(this.noopKeepaliveInterval);
6735
6747
  this.noopKeepaliveInterval = null;
@@ -6813,6 +6825,10 @@ class ServerSocket {
6813
6825
  var _a;
6814
6826
  return (_a = this._reconnectManager) === null || _a === void 0 ? void 0 : _a.metrics;
6815
6827
  }
6828
+ getReconnectThreshold() {
6829
+ var _a;
6830
+ return (_a = this._reconnectManager) === null || _a === void 0 ? void 0 : _a.reconnectThresholdInMs;
6831
+ }
6816
6832
  }
6817
6833
 
6818
6834
  const defaultSubdomainPattern = /^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@whereby.com/media",
3
3
  "description": "Media library for Whereby",
4
- "version": "1.12.2",
4
+ "version": "1.14.0",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/whereby/sdk",
7
7
  "repository": {