summaryrefslogtreecommitdiffstats
path: root/comm/chat/protocols/matrix/lib/matrix-sdk/webrtc/callFeed.js
blob: 25af7aa5e8bdb82d7d14817cc662b14897f65395 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SPEAKING_THRESHOLD = exports.CallFeedEvent = exports.CallFeed = void 0;
var _callEventTypes = require("./callEventTypes");
var _audioContext = require("./audioContext");
var _logger = require("../logger");
var _typedEventEmitter = require("../models/typed-event-emitter");
var _call = require("./call");
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
                                                                                                                                                                                                                                                                                                                                                                                          Copyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>
                                                                                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                                                          Licensed under the Apache License, Version 2.0 (the "License");
                                                                                                                                                                                                                                                                                                                                                                                          you may not use this file except in compliance with the License.
                                                                                                                                                                                                                                                                                                                                                                                          You may obtain a copy of the License at
                                                                                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                                                              http://www.apache.org/licenses/LICENSE-2.0
                                                                                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                                                          Unless required by applicable law or agreed to in writing, software
                                                                                                                                                                                                                                                                                                                                                                                          distributed under the License is distributed on an "AS IS" BASIS,
                                                                                                                                                                                                                                                                                                                                                                                          WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                                                                                                                                                                                                                                                                                                                                                                          See the License for the specific language governing permissions and
                                                                                                                                                                                                                                                                                                                                                                                          limitations under the License.
                                                                                                                                                                                                                                                                                                                                                                                          */
const POLLING_INTERVAL = 200; // ms
const SPEAKING_THRESHOLD = -60; // dB
exports.SPEAKING_THRESHOLD = SPEAKING_THRESHOLD;
const SPEAKING_SAMPLE_COUNT = 8; // samples
let CallFeedEvent = /*#__PURE__*/function (CallFeedEvent) {
  CallFeedEvent["NewStream"] = "new_stream";
  CallFeedEvent["MuteStateChanged"] = "mute_state_changed";
  CallFeedEvent["LocalVolumeChanged"] = "local_volume_changed";
  CallFeedEvent["VolumeChanged"] = "volume_changed";
  CallFeedEvent["ConnectedChanged"] = "connected_changed";
  CallFeedEvent["Speaking"] = "speaking";
  CallFeedEvent["Disposed"] = "disposed";
  return CallFeedEvent;
}({});
exports.CallFeedEvent = CallFeedEvent;
class CallFeed extends _typedEventEmitter.TypedEventEmitter {
  constructor(opts) {
    super();
    _defineProperty(this, "stream", void 0);
    _defineProperty(this, "sdpMetadataStreamId", void 0);
    _defineProperty(this, "userId", void 0);
    _defineProperty(this, "deviceId", void 0);
    _defineProperty(this, "purpose", void 0);
    _defineProperty(this, "speakingVolumeSamples", void 0);
    _defineProperty(this, "client", void 0);
    _defineProperty(this, "call", void 0);
    _defineProperty(this, "roomId", void 0);
    _defineProperty(this, "audioMuted", void 0);
    _defineProperty(this, "videoMuted", void 0);
    _defineProperty(this, "localVolume", 1);
    _defineProperty(this, "measuringVolumeActivity", false);
    _defineProperty(this, "audioContext", void 0);
    _defineProperty(this, "analyser", void 0);
    _defineProperty(this, "frequencyBinCount", void 0);
    _defineProperty(this, "speakingThreshold", SPEAKING_THRESHOLD);
    _defineProperty(this, "speaking", false);
    _defineProperty(this, "volumeLooperTimeout", void 0);
    _defineProperty(this, "_disposed", false);
    _defineProperty(this, "_connected", false);
    _defineProperty(this, "onAddTrack", () => {
      this.emit(CallFeedEvent.NewStream, this.stream);
    });
    _defineProperty(this, "onCallState", state => {
      if (state === _call.CallState.Connected) {
        this.connected = true;
      } else if (state === _call.CallState.Connecting) {
        this.connected = false;
      }
    });
    _defineProperty(this, "volumeLooper", () => {
      if (!this.analyser) return;
      if (!this.measuringVolumeActivity) return;
      this.analyser.getFloatFrequencyData(this.frequencyBinCount);
      let maxVolume = -Infinity;
      for (const volume of this.frequencyBinCount) {
        if (volume > maxVolume) {
          maxVolume = volume;
        }
      }
      this.speakingVolumeSamples.shift();
      this.speakingVolumeSamples.push(maxVolume);
      this.emit(CallFeedEvent.VolumeChanged, maxVolume);
      let newSpeaking = false;
      for (const volume of this.speakingVolumeSamples) {
        if (volume > this.speakingThreshold) {
          newSpeaking = true;
          break;
        }
      }
      if (this.speaking !== newSpeaking) {
        this.speaking = newSpeaking;
        this.emit(CallFeedEvent.Speaking, this.speaking);
      }
      this.volumeLooperTimeout = setTimeout(this.volumeLooper, POLLING_INTERVAL);
    });
    this.client = opts.client;
    this.call = opts.call;
    this.roomId = opts.roomId;
    this.userId = opts.userId;
    this.deviceId = opts.deviceId;
    this.purpose = opts.purpose;
    this.audioMuted = opts.audioMuted;
    this.videoMuted = opts.videoMuted;
    this.speakingVolumeSamples = new Array(SPEAKING_SAMPLE_COUNT).fill(-Infinity);
    this.sdpMetadataStreamId = opts.stream.id;
    this.updateStream(null, opts.stream);
    this.stream = opts.stream; // updateStream does this, but this makes TS happier

    if (this.hasAudioTrack) {
      this.initVolumeMeasuring();
    }
    if (opts.call) {
      opts.call.addListener(_call.CallEvent.State, this.onCallState);
      this.onCallState(opts.call.state);
    }
  }
  get connected() {
    // Local feeds are always considered connected
    return this.isLocal() || this._connected;
  }
  set connected(connected) {
    this._connected = connected;
    this.emit(CallFeedEvent.ConnectedChanged, this.connected);
  }
  get hasAudioTrack() {
    return this.stream.getAudioTracks().length > 0;
  }
  updateStream(oldStream, newStream) {
    if (newStream === oldStream) return;
    const wasMeasuringVolumeActivity = this.measuringVolumeActivity;
    if (oldStream) {
      oldStream.removeEventListener("addtrack", this.onAddTrack);
      this.measureVolumeActivity(false);
    }
    this.stream = newStream;
    newStream.addEventListener("addtrack", this.onAddTrack);
    if (this.hasAudioTrack) {
      this.initVolumeMeasuring();
      if (wasMeasuringVolumeActivity) this.measureVolumeActivity(true);
    } else {
      this.measureVolumeActivity(false);
    }
    this.emit(CallFeedEvent.NewStream, this.stream);
  }
  initVolumeMeasuring() {
    if (!this.hasAudioTrack) return;
    if (!this.audioContext) this.audioContext = (0, _audioContext.acquireContext)();
    this.analyser = this.audioContext.createAnalyser();
    this.analyser.fftSize = 512;
    this.analyser.smoothingTimeConstant = 0.1;
    const mediaStreamAudioSourceNode = this.audioContext.createMediaStreamSource(this.stream);
    mediaStreamAudioSourceNode.connect(this.analyser);
    this.frequencyBinCount = new Float32Array(this.analyser.frequencyBinCount);
  }
  /**
   * Returns callRoom member
   * @returns member of the callRoom
   */
  getMember() {
    const callRoom = this.client.getRoom(this.roomId);
    return callRoom?.getMember(this.userId) ?? null;
  }

  /**
   * Returns true if CallFeed is local, otherwise returns false
   * @returns is local?
   */
  isLocal() {
    return this.userId === this.client.getUserId() && (this.deviceId === undefined || this.deviceId === this.client.getDeviceId());
  }

  /**
   * Returns true if audio is muted or if there are no audio
   * tracks, otherwise returns false
   * @returns is audio muted?
   */
  isAudioMuted() {
    return this.stream.getAudioTracks().length === 0 || this.audioMuted;
  }

  /**
   * Returns true video is muted or if there are no video
   * tracks, otherwise returns false
   * @returns is video muted?
   */
  isVideoMuted() {
    // We assume only one video track
    return this.stream.getVideoTracks().length === 0 || this.videoMuted;
  }
  isSpeaking() {
    return this.speaking;
  }

  /**
   * Replaces the current MediaStream with a new one.
   * The stream will be different and new stream as remote parties are
   * concerned, but this can be used for convenience locally to set up
   * volume listeners automatically on the new stream etc.
   * @param newStream - new stream with which to replace the current one
   */
  setNewStream(newStream) {
    this.updateStream(this.stream, newStream);
  }

  /**
   * Set one or both of feed's internal audio and video video mute state
   * Either value may be null to leave it as-is
   * @param audioMuted - is the feed's audio muted?
   * @param videoMuted - is the feed's video muted?
   */
  setAudioVideoMuted(audioMuted, videoMuted) {
    if (audioMuted !== null) {
      if (this.audioMuted !== audioMuted) {
        this.speakingVolumeSamples.fill(-Infinity);
      }
      this.audioMuted = audioMuted;
    }
    if (videoMuted !== null) this.videoMuted = videoMuted;
    this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);
  }

  /**
   * Starts emitting volume_changed events where the emitter value is in decibels
   * @param enabled - emit volume changes
   */
  measureVolumeActivity(enabled) {
    if (enabled) {
      if (!this.analyser || !this.frequencyBinCount || !this.hasAudioTrack) return;
      this.measuringVolumeActivity = true;
      this.volumeLooper();
    } else {
      this.measuringVolumeActivity = false;
      this.speakingVolumeSamples.fill(-Infinity);
      this.emit(CallFeedEvent.VolumeChanged, -Infinity);
    }
  }
  setSpeakingThreshold(threshold) {
    this.speakingThreshold = threshold;
  }
  clone() {
    const mediaHandler = this.client.getMediaHandler();
    const stream = this.stream.clone();
    _logger.logger.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${stream.id})`);
    if (this.purpose === _callEventTypes.SDPStreamMetadataPurpose.Usermedia) {
      mediaHandler.userMediaStreams.push(stream);
    } else {
      mediaHandler.screensharingStreams.push(stream);
    }
    return new CallFeed({
      client: this.client,
      roomId: this.roomId,
      userId: this.userId,
      deviceId: this.deviceId,
      stream,
      purpose: this.purpose,
      audioMuted: this.audioMuted,
      videoMuted: this.videoMuted
    });
  }
  dispose() {
    clearTimeout(this.volumeLooperTimeout);
    this.stream?.removeEventListener("addtrack", this.onAddTrack);
    this.call?.removeListener(_call.CallEvent.State, this.onCallState);
    if (this.audioContext) {
      this.audioContext = undefined;
      this.analyser = undefined;
      (0, _audioContext.releaseContext)();
    }
    this._disposed = true;
    this.emit(CallFeedEvent.Disposed);
  }
  get disposed() {
    return this._disposed;
  }
  set disposed(value) {
    this._disposed = value;
  }
  getLocalVolume() {
    return this.localVolume;
  }
  setLocalVolume(localVolume) {
    this.localVolume = localVolume;
    this.emit(CallFeedEvent.LocalVolumeChanged, localVolume);
  }
}
exports.CallFeed = CallFeed;