matrix-js-sdk
Version:
Matrix Client-Server SDK for Javascript
806 lines (776 loc) • 122 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MatrixCall = exports.FALLBACK_ICE_SERVER = exports.CallType = exports.CallState = exports.CallParty = exports.CallEvent = exports.CallErrorCode = exports.CallError = exports.CallDirection = void 0;
exports.createNewMatrixCall = createNewMatrixCall;
exports.genCallID = genCallID;
exports.setTracksEnabled = setTracksEnabled;
exports.supportsMatrixCall = supportsMatrixCall;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _uuid = require("uuid");
var _sdpTransform = require("sdp-transform");
var _logger = require("../logger");
var _utils = require("../utils");
var _event = require("../@types/event");
var _randomstring = require("../randomstring");
var _callEventTypes = require("./callEventTypes");
var _callFeed = require("./callFeed");
var _typedEventEmitter = require("../models/typed-event-emitter");
var _deviceinfo = require("../crypto/deviceinfo");
var _groupCall = require("./groupCall");
var _httpApi = require("../http-api");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 New Vector Ltd
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
Copyright 2021 - 2022 Š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.
*/ /**
* This is an internal module. See {@link createNewMatrixCall} for the public API.
*/
var MediaType = /*#__PURE__*/function (MediaType) {
MediaType["AUDIO"] = "audio";
MediaType["VIDEO"] = "video";
return MediaType;
}(MediaType || {});
var CodecName = /*#__PURE__*/function (CodecName) {
CodecName["OPUS"] = "opus";
return CodecName;
}(CodecName || {}); // add more as needed
// Used internally to specify modifications to codec parameters in SDP
let CallState = /*#__PURE__*/function (CallState) {
CallState["Fledgling"] = "fledgling";
CallState["InviteSent"] = "invite_sent";
CallState["WaitLocalMedia"] = "wait_local_media";
CallState["CreateOffer"] = "create_offer";
CallState["CreateAnswer"] = "create_answer";
CallState["Connecting"] = "connecting";
CallState["Connected"] = "connected";
CallState["Ringing"] = "ringing";
CallState["Ended"] = "ended";
return CallState;
}({});
exports.CallState = CallState;
let CallType = /*#__PURE__*/function (CallType) {
CallType["Voice"] = "voice";
CallType["Video"] = "video";
return CallType;
}({});
exports.CallType = CallType;
let CallDirection = /*#__PURE__*/function (CallDirection) {
CallDirection["Inbound"] = "inbound";
CallDirection["Outbound"] = "outbound";
return CallDirection;
}({});
exports.CallDirection = CallDirection;
let CallParty = /*#__PURE__*/function (CallParty) {
CallParty["Local"] = "local";
CallParty["Remote"] = "remote";
return CallParty;
}({});
exports.CallParty = CallParty;
let CallEvent = /*#__PURE__*/function (CallEvent) {
CallEvent["Hangup"] = "hangup";
CallEvent["State"] = "state";
CallEvent["Error"] = "error";
CallEvent["Replaced"] = "replaced";
CallEvent["LocalHoldUnhold"] = "local_hold_unhold";
CallEvent["RemoteHoldUnhold"] = "remote_hold_unhold";
CallEvent["HoldUnhold"] = "hold_unhold";
CallEvent["FeedsChanged"] = "feeds_changed";
CallEvent["AssertedIdentityChanged"] = "asserted_identity_changed";
CallEvent["LengthChanged"] = "length_changed";
CallEvent["DataChannel"] = "datachannel";
CallEvent["SendVoipEvent"] = "send_voip_event";
CallEvent["PeerConnectionCreated"] = "peer_connection_created";
return CallEvent;
}({});
exports.CallEvent = CallEvent;
let CallErrorCode = /*#__PURE__*/function (CallErrorCode) {
CallErrorCode["UserHangup"] = "user_hangup";
CallErrorCode["LocalOfferFailed"] = "local_offer_failed";
CallErrorCode["NoUserMedia"] = "no_user_media";
CallErrorCode["UnknownDevices"] = "unknown_devices";
CallErrorCode["SendInvite"] = "send_invite";
CallErrorCode["CreateAnswer"] = "create_answer";
CallErrorCode["CreateOffer"] = "create_offer";
CallErrorCode["SendAnswer"] = "send_answer";
CallErrorCode["SetRemoteDescription"] = "set_remote_description";
CallErrorCode["SetLocalDescription"] = "set_local_description";
CallErrorCode["AnsweredElsewhere"] = "answered_elsewhere";
CallErrorCode["IceFailed"] = "ice_failed";
CallErrorCode["InviteTimeout"] = "invite_timeout";
CallErrorCode["Replaced"] = "replaced";
CallErrorCode["SignallingFailed"] = "signalling_timeout";
CallErrorCode["UserBusy"] = "user_busy";
CallErrorCode["Transferred"] = "transferred";
CallErrorCode["NewSession"] = "new_session";
return CallErrorCode;
}({});
/**
* The version field that we set in m.call.* events
*/
exports.CallErrorCode = CallErrorCode;
const VOIP_PROTO_VERSION = "1";
/** The fallback ICE server to use for STUN or TURN protocols. */
const FALLBACK_ICE_SERVER = "stun:turn.matrix.org";
/** The length of time a call can be ringing for. */
exports.FALLBACK_ICE_SERVER = FALLBACK_ICE_SERVER;
const CALL_TIMEOUT_MS = 60 * 1000; // ms
/** The time after which we increment callLength */
const CALL_LENGTH_INTERVAL = 1000; // ms
/** The time after which we end the call, if ICE got disconnected */
const ICE_DISCONNECTED_TIMEOUT = 30 * 1000; // ms
/** The time after which we try a ICE restart, if ICE got disconnected */
const ICE_RECONNECTING_TIMEOUT = 2 * 1000; // ms
class CallError extends Error {
constructor(code, msg, err) {
// Still don't think there's any way to have proper nested errors
super(msg + ": " + err);
(0, _defineProperty2.default)(this, "code", void 0);
this.code = code;
}
}
exports.CallError = CallError;
function genCallID() {
return Date.now().toString() + (0, _randomstring.randomString)(16);
}
function getCodecParamMods(isPtt) {
const mods = [{
mediaType: "audio",
codec: "opus",
enableDtx: true,
maxAverageBitrate: isPtt ? 12000 : undefined
}];
return mods;
}
/**
* These now all have the call object as an argument. Why? Well, to know which call a given event is
* about you have three options:
* 1. Use a closure as the callback that remembers what call it's listening to. This can be
* a pain because you need to pass the listener function again when you remove the listener,
* which might be somewhere else.
* 2. Use not-very-well-known fact that EventEmitter sets 'this' to the emitter object in the
* callback. This doesn't really play well with modern Typescript and eslint and doesn't work
* with our pattern of re-emitting events.
* 3. Pass the object in question as an argument to the callback.
*
* Now that we have group calls which have to deal with multiple call objects, this will
* become more important, and I think methods 1 and 2 are just going to cause issues.
*/
// The key of the transceiver map (purpose + media type, separated by ':')
// generates keys for the map of transceivers
// kind is unfortunately a string rather than MediaType as this is the type of
// track.kind
function getTransceiverKey(purpose, kind) {
return purpose + ":" + kind;
}
class MatrixCall extends _typedEventEmitter.TypedEventEmitter {
/**
* Construct a new Matrix Call.
* @param opts - Config options.
*/
constructor(opts) {
var _opts$forceTURN;
super();
(0, _defineProperty2.default)(this, "roomId", void 0);
(0, _defineProperty2.default)(this, "callId", void 0);
(0, _defineProperty2.default)(this, "invitee", void 0);
(0, _defineProperty2.default)(this, "hangupParty", void 0);
(0, _defineProperty2.default)(this, "hangupReason", void 0);
(0, _defineProperty2.default)(this, "direction", void 0);
(0, _defineProperty2.default)(this, "ourPartyId", void 0);
(0, _defineProperty2.default)(this, "peerConn", void 0);
(0, _defineProperty2.default)(this, "toDeviceSeq", 0);
// whether this call should have push-to-talk semantics
// This should be set by the consumer on incoming & outgoing calls.
(0, _defineProperty2.default)(this, "isPtt", false);
(0, _defineProperty2.default)(this, "_state", CallState.Fledgling);
(0, _defineProperty2.default)(this, "client", void 0);
(0, _defineProperty2.default)(this, "forceTURN", void 0);
(0, _defineProperty2.default)(this, "turnServers", void 0);
// A queue for candidates waiting to go out.
// We try to amalgamate candidates into a single candidate message where
// possible
(0, _defineProperty2.default)(this, "candidateSendQueue", []);
(0, _defineProperty2.default)(this, "candidateSendTries", 0);
(0, _defineProperty2.default)(this, "candidatesEnded", false);
(0, _defineProperty2.default)(this, "feeds", []);
// our transceivers for each purpose and type of media
(0, _defineProperty2.default)(this, "transceivers", new Map());
(0, _defineProperty2.default)(this, "inviteOrAnswerSent", false);
(0, _defineProperty2.default)(this, "waitForLocalAVStream", false);
(0, _defineProperty2.default)(this, "successor", void 0);
(0, _defineProperty2.default)(this, "opponentMember", void 0);
(0, _defineProperty2.default)(this, "opponentVersion", void 0);
// The party ID of the other side: undefined if we haven't chosen a partner
// yet, null if we have but they didn't send a party ID.
(0, _defineProperty2.default)(this, "opponentPartyId", void 0);
(0, _defineProperty2.default)(this, "opponentCaps", void 0);
(0, _defineProperty2.default)(this, "iceDisconnectedTimeout", void 0);
(0, _defineProperty2.default)(this, "iceReconnectionTimeOut", void 0);
(0, _defineProperty2.default)(this, "inviteTimeout", void 0);
(0, _defineProperty2.default)(this, "removeTrackListeners", new Map());
// The logic of when & if a call is on hold is nontrivial and explained in is*OnHold
// This flag represents whether we want the other party to be on hold
(0, _defineProperty2.default)(this, "remoteOnHold", false);
// the stats for the call at the point it ended. We can't get these after we
// tear the call down, so we just grab a snapshot before we stop the call.
// The typescript definitions have this type as 'any' :(
(0, _defineProperty2.default)(this, "callStatsAtEnd", void 0);
// Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example
(0, _defineProperty2.default)(this, "makingOffer", false);
(0, _defineProperty2.default)(this, "ignoreOffer", false);
(0, _defineProperty2.default)(this, "isSettingRemoteAnswerPending", false);
(0, _defineProperty2.default)(this, "responsePromiseChain", void 0);
// If candidates arrive before we've picked an opponent (which, in particular,
// will happen if the opponent sends candidates eagerly before the user answers
// the call) we buffer them up here so we can then add the ones from the party we pick
(0, _defineProperty2.default)(this, "remoteCandidateBuffer", new Map());
(0, _defineProperty2.default)(this, "remoteAssertedIdentity", void 0);
(0, _defineProperty2.default)(this, "remoteSDPStreamMetadata", void 0);
(0, _defineProperty2.default)(this, "callLengthInterval", void 0);
(0, _defineProperty2.default)(this, "callStartTime", void 0);
(0, _defineProperty2.default)(this, "opponentDeviceId", void 0);
(0, _defineProperty2.default)(this, "opponentDeviceInfo", void 0);
(0, _defineProperty2.default)(this, "opponentSessionId", void 0);
(0, _defineProperty2.default)(this, "groupCallId", void 0);
// Used to keep the timer for the delay before actually stopping our
// video track after muting (see setLocalVideoMuted)
(0, _defineProperty2.default)(this, "stopVideoTrackTimer", void 0);
// Used to allow connection without Video and Audio. To establish a webrtc connection without media a Data channel is
// needed At the moment this property is true if we allow MatrixClient with isVoipWithNoMediaAllowed = true
(0, _defineProperty2.default)(this, "isOnlyDataChannelAllowed", void 0);
(0, _defineProperty2.default)(this, "stats", void 0);
/**
* Internal
*/
(0, _defineProperty2.default)(this, "gotLocalIceCandidate", event => {
if (event.candidate) {
if (this.candidatesEnded) {
_logger.logger.warn(`Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended!`);
}
_logger.logger.debug(`Call ${this.callId} got local ICE ${event.candidate.sdpMid} ${event.candidate.candidate}`);
if (this.callHasEnded()) return;
// As with the offer, note we need to make a copy of this object, not
// pass the original: that broke in Chrome ~m43.
if (event.candidate.candidate === "") {
this.queueCandidate(null);
} else {
this.queueCandidate(event.candidate);
}
}
});
(0, _defineProperty2.default)(this, "onIceGatheringStateChange", event => {
var _this$peerConn;
_logger.logger.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${this.peerConn.iceGatheringState}`);
if (((_this$peerConn = this.peerConn) === null || _this$peerConn === void 0 ? void 0 : _this$peerConn.iceGatheringState) === "complete") {
this.queueCandidate(null); // We should leave it to WebRTC to announce the end
_logger.logger.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state complete, set candidates have ended`);
}
});
(0, _defineProperty2.default)(this, "getLocalOfferFailed", err => {
_logger.logger.error(`Call ${this.callId} getLocalOfferFailed() running`, err);
this.emit(CallEvent.Error, new CallError(CallErrorCode.LocalOfferFailed, "Failed to get local offer!", err), this);
this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);
});
(0, _defineProperty2.default)(this, "getUserMediaFailed", err => {
if (this.successor) {
this.successor.getUserMediaFailed(err);
return;
}
_logger.logger.warn(`Call ${this.callId} getUserMediaFailed() failed to get user media - ending call`, err);
this.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, "Couldn't start capturing media! Is your microphone set up and " + "does this app have permission?", err), this);
this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);
});
(0, _defineProperty2.default)(this, "onIceConnectionStateChanged", () => {
var _this$peerConn2, _this$peerConn3, _this$peerConn$iceCon, _this$peerConn4, _this$peerConn5, _this$peerConn8;
if (this.callHasEnded()) {
return; // because ICE can still complete as we're ending the call
}
_logger.logger.debug(`Call ${this.callId} onIceConnectionStateChanged() running (state=${(_this$peerConn2 = this.peerConn) === null || _this$peerConn2 === void 0 ? void 0 : _this$peerConn2.iceConnectionState}, conn=${(_this$peerConn3 = this.peerConn) === null || _this$peerConn3 === void 0 ? void 0 : _this$peerConn3.connectionState})`);
// ideally we'd consider the call to be connected when we get media but
// chrome doesn't implement any of the 'onstarted' events yet
if (["connected", "completed"].includes((_this$peerConn$iceCon = (_this$peerConn4 = this.peerConn) === null || _this$peerConn4 === void 0 ? void 0 : _this$peerConn4.iceConnectionState) !== null && _this$peerConn$iceCon !== void 0 ? _this$peerConn$iceCon : "")) {
clearTimeout(this.iceDisconnectedTimeout);
this.iceDisconnectedTimeout = undefined;
if (this.iceReconnectionTimeOut) {
clearTimeout(this.iceReconnectionTimeOut);
}
this.state = CallState.Connected;
if (!this.callLengthInterval && !this.callStartTime) {
this.callStartTime = Date.now();
this.callLengthInterval = setInterval(() => {
this.emit(CallEvent.LengthChanged, Math.round((Date.now() - this.callStartTime) / 1000), this);
}, CALL_LENGTH_INTERVAL);
}
} else if (((_this$peerConn5 = this.peerConn) === null || _this$peerConn5 === void 0 ? void 0 : _this$peerConn5.iceConnectionState) == "failed") {
var _this$peerConn6;
this.candidatesEnded = false;
// Firefox for Android does not yet have support for restartIce()
// (the types say it's always defined though, so we have to cast
// to prevent typescript from warning).
if ((_this$peerConn6 = this.peerConn) !== null && _this$peerConn6 !== void 0 && _this$peerConn6.restartIce) {
var _this$peerConn7;
this.candidatesEnded = false;
_logger.logger.debug(`Call ${this.callId} onIceConnectionStateChanged() ice restart (state=${(_this$peerConn7 = this.peerConn) === null || _this$peerConn7 === void 0 ? void 0 : _this$peerConn7.iceConnectionState})`);
this.peerConn.restartIce();
} else {
_logger.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`);
this.hangup(CallErrorCode.IceFailed, false);
}
} else if (((_this$peerConn8 = this.peerConn) === null || _this$peerConn8 === void 0 ? void 0 : _this$peerConn8.iceConnectionState) == "disconnected") {
this.candidatesEnded = false;
this.iceReconnectionTimeOut = setTimeout(() => {
var _this$peerConn9, _this$peerConn10, _this$peerConn11;
_logger.logger.info(`Call ${this.callId} onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=${(_this$peerConn9 = this.peerConn) === null || _this$peerConn9 === void 0 ? void 0 : _this$peerConn9.iceConnectionState}, conn=${(_this$peerConn10 = this.peerConn) === null || _this$peerConn10 === void 0 ? void 0 : _this$peerConn10.connectionState})`);
if ((_this$peerConn11 = this.peerConn) !== null && _this$peerConn11 !== void 0 && _this$peerConn11.restartIce) {
this.candidatesEnded = false;
this.peerConn.restartIce();
}
this.iceReconnectionTimeOut = undefined;
}, ICE_RECONNECTING_TIMEOUT);
this.iceDisconnectedTimeout = setTimeout(() => {
_logger.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`);
this.hangup(CallErrorCode.IceFailed, false);
}, ICE_DISCONNECTED_TIMEOUT);
this.state = CallState.Connecting;
}
// In PTT mode, override feed status to muted when we lose connection to
// the peer, since we don't want to block the line if they're not saying anything.
// Experimenting in Chrome, this happens after 5 or 6 seconds, which is probably
// fast enough.
if (this.isPtt && ["failed", "disconnected"].includes(this.peerConn.iceConnectionState)) {
for (const feed of this.getRemoteFeeds()) {
feed.setAudioVideoMuted(true, true);
}
}
});
(0, _defineProperty2.default)(this, "onSignallingStateChanged", () => {
var _this$peerConn12;
_logger.logger.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${(_this$peerConn12 = this.peerConn) === null || _this$peerConn12 === void 0 ? void 0 : _this$peerConn12.signalingState})`);
});
(0, _defineProperty2.default)(this, "onTrack", ev => {
if (ev.streams.length === 0) {
_logger.logger.warn(`Call ${this.callId} onTrack() called with streamless track streamless (kind=${ev.track.kind})`);
return;
}
const stream = ev.streams[0];
this.pushRemoteFeed(stream);
if (!this.removeTrackListeners.has(stream)) {
const onRemoveTrack = () => {
if (stream.getTracks().length === 0) {
_logger.logger.info(`Call ${this.callId} onTrack() removing track (streamId=${stream.id})`);
this.deleteFeedByStream(stream);
stream.removeEventListener("removetrack", onRemoveTrack);
this.removeTrackListeners.delete(stream);
}
};
stream.addEventListener("removetrack", onRemoveTrack);
this.removeTrackListeners.set(stream, onRemoveTrack);
}
});
(0, _defineProperty2.default)(this, "onDataChannel", ev => {
this.emit(CallEvent.DataChannel, ev.channel, this);
});
(0, _defineProperty2.default)(this, "onNegotiationNeeded", async () => {
_logger.logger.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`);
if (this.state !== CallState.CreateOffer && this.opponentVersion === 0) {
_logger.logger.info(`Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`);
return;
}
this.queueGotLocalOffer();
});
(0, _defineProperty2.default)(this, "onHangupReceived", msg => {
_logger.logger.debug(`Call ${this.callId} onHangupReceived() running`);
// party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen
// a partner yet but we're treating the hangup as a reject as per VoIP v0)
if (this.partyIdMatches(msg) || this.state === CallState.Ringing) {
// default reason is user_hangup
this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);
} else {
_logger.logger.info(`Call ${this.callId} onHangupReceived() ignoring message from party ID ${msg.party_id}: our partner is ${this.opponentPartyId}`);
}
});
(0, _defineProperty2.default)(this, "onRejectReceived", msg => {
_logger.logger.debug(`Call ${this.callId} onRejectReceived() running`);
// No need to check party_id for reject because if we'd received either
// an answer or reject, we wouldn't be in state InviteSent
const shouldTerminate =
// reject events also end the call if it's ringing: it's another of
// our devices rejecting the call.
[CallState.InviteSent, CallState.Ringing].includes(this.state) ||
// also if we're in the init state and it's an inbound call, since
// this means we just haven't entered the ringing state yet
this.state === CallState.Fledgling && this.direction === CallDirection.Inbound;
if (shouldTerminate) {
this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);
} else {
_logger.logger.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`);
}
});
(0, _defineProperty2.default)(this, "onAnsweredElsewhere", msg => {
_logger.logger.debug(`Call ${this.callId} onAnsweredElsewhere() running`);
this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);
});
this.roomId = opts.roomId;
this.invitee = opts.invitee;
this.client = opts.client;
if (!this.client.deviceId) throw new Error("Client must have a device ID to start calls");
this.forceTURN = (_opts$forceTURN = opts.forceTURN) !== null && _opts$forceTURN !== void 0 ? _opts$forceTURN : false;
this.ourPartyId = this.client.deviceId;
this.opponentDeviceId = opts.opponentDeviceId;
this.opponentSessionId = opts.opponentSessionId;
this.groupCallId = opts.groupCallId;
// Array of Objects with urls, username, credential keys
this.turnServers = opts.turnServers || [];
if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {
this.turnServers.push({
urls: [FALLBACK_ICE_SERVER]
});
}
for (const server of this.turnServers) {
(0, _utils.checkObjectHasKeys)(server, ["urls"]);
}
this.callId = genCallID();
// If the Client provides calls without audio and video we need a datachannel for a webrtc connection
this.isOnlyDataChannelAllowed = this.client.isVoipWithNoMediaAllowed;
}
/**
* Place a voice call to this room.
* @throws If you have not specified a listener for 'error' events.
*/
async placeVoiceCall() {
await this.placeCall(true, false);
}
/**
* Place a video call to this room.
* @throws If you have not specified a listener for 'error' events.
*/
async placeVideoCall() {
await this.placeCall(true, true);
}
/**
* Create a datachannel using this call's peer connection.
* @param label - A human readable label for this datachannel
* @param options - An object providing configuration options for the data channel.
*/
createDataChannel(label, options) {
const dataChannel = this.peerConn.createDataChannel(label, options);
this.emit(CallEvent.DataChannel, dataChannel, this);
return dataChannel;
}
getOpponentMember() {
return this.opponentMember;
}
getOpponentDeviceId() {
return this.opponentDeviceId;
}
getOpponentSessionId() {
return this.opponentSessionId;
}
opponentCanBeTransferred() {
return Boolean(this.opponentCaps && this.opponentCaps["m.call.transferee"]);
}
opponentSupportsDTMF() {
return Boolean(this.opponentCaps && this.opponentCaps["m.call.dtmf"]);
}
getRemoteAssertedIdentity() {
return this.remoteAssertedIdentity;
}
get state() {
return this._state;
}
set state(state) {
const oldState = this._state;
this._state = state;
this.emit(CallEvent.State, state, oldState, this);
}
get type() {
// we may want to look for a video receiver here rather than a track to match the
// sender behaviour, although in practice they should be the same thing
return this.hasUserMediaVideoSender || this.hasRemoteUserMediaVideoTrack ? CallType.Video : CallType.Voice;
}
get hasLocalUserMediaVideoTrack() {
var _this$localUsermediaS;
return !!((_this$localUsermediaS = this.localUsermediaStream) !== null && _this$localUsermediaS !== void 0 && _this$localUsermediaS.getVideoTracks().length);
}
get hasRemoteUserMediaVideoTrack() {
return this.getRemoteFeeds().some(feed => {
var _feed$stream;
return feed.purpose === _callEventTypes.SDPStreamMetadataPurpose.Usermedia && ((_feed$stream = feed.stream) === null || _feed$stream === void 0 ? void 0 : _feed$stream.getVideoTracks().length);
});
}
get hasLocalUserMediaAudioTrack() {
var _this$localUsermediaS2;
return !!((_this$localUsermediaS2 = this.localUsermediaStream) !== null && _this$localUsermediaS2 !== void 0 && _this$localUsermediaS2.getAudioTracks().length);
}
get hasRemoteUserMediaAudioTrack() {
return this.getRemoteFeeds().some(feed => {
var _feed$stream2;
return feed.purpose === _callEventTypes.SDPStreamMetadataPurpose.Usermedia && !!((_feed$stream2 = feed.stream) !== null && _feed$stream2 !== void 0 && _feed$stream2.getAudioTracks().length);
});
}
get hasUserMediaAudioSender() {
var _this$transceivers$ge;
return Boolean((_this$transceivers$ge = this.transceivers.get(getTransceiverKey(_callEventTypes.SDPStreamMetadataPurpose.Usermedia, "audio"))) === null || _this$transceivers$ge === void 0 ? void 0 : _this$transceivers$ge.sender);
}
get hasUserMediaVideoSender() {
var _this$transceivers$ge2;
return Boolean((_this$transceivers$ge2 = this.transceivers.get(getTransceiverKey(_callEventTypes.SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _this$transceivers$ge2 === void 0 ? void 0 : _this$transceivers$ge2.sender);
}
get localUsermediaFeed() {
return this.getLocalFeeds().find(feed => feed.purpose === _callEventTypes.SDPStreamMetadataPurpose.Usermedia);
}
get localScreensharingFeed() {
return this.getLocalFeeds().find(feed => feed.purpose === _callEventTypes.SDPStreamMetadataPurpose.Screenshare);
}
get localUsermediaStream() {
var _this$localUsermediaF;
return (_this$localUsermediaF = this.localUsermediaFeed) === null || _this$localUsermediaF === void 0 ? void 0 : _this$localUsermediaF.stream;
}
get localScreensharingStream() {
var _this$localScreenshar;
return (_this$localScreenshar = this.localScreensharingFeed) === null || _this$localScreenshar === void 0 ? void 0 : _this$localScreenshar.stream;
}
get remoteUsermediaFeed() {
return this.getRemoteFeeds().find(feed => feed.purpose === _callEventTypes.SDPStreamMetadataPurpose.Usermedia);
}
get remoteScreensharingFeed() {
return this.getRemoteFeeds().find(feed => feed.purpose === _callEventTypes.SDPStreamMetadataPurpose.Screenshare);
}
get remoteUsermediaStream() {
var _this$remoteUsermedia;
return (_this$remoteUsermedia = this.remoteUsermediaFeed) === null || _this$remoteUsermedia === void 0 ? void 0 : _this$remoteUsermedia.stream;
}
get remoteScreensharingStream() {
var _this$remoteScreensha;
return (_this$remoteScreensha = this.remoteScreensharingFeed) === null || _this$remoteScreensha === void 0 ? void 0 : _this$remoteScreensha.stream;
}
getFeedByStreamId(streamId) {
return this.getFeeds().find(feed => feed.stream.id === streamId);
}
/**
* Returns an array of all CallFeeds
* @returns CallFeeds
*/
getFeeds() {
return this.feeds;
}
/**
* Returns an array of all local CallFeeds
* @returns local CallFeeds
*/
getLocalFeeds() {
return this.feeds.filter(feed => feed.isLocal());
}
/**
* Returns an array of all remote CallFeeds
* @returns remote CallFeeds
*/
getRemoteFeeds() {
return this.feeds.filter(feed => !feed.isLocal());
}
async initOpponentCrypto() {
var _this$getOpponentMemb, _deviceInfoMap$get;
if (!this.opponentDeviceId) return;
if (!this.client.getUseE2eForGroupCall()) return;
// It's possible to want E2EE and yet not have the means to manage E2EE
// ourselves (for example if the client is a RoomWidgetClient)
if (!this.client.isCryptoEnabled()) {
// All we know is the device ID
this.opponentDeviceInfo = new _deviceinfo.DeviceInfo(this.opponentDeviceId);
return;
}
// if we've got to this point, we do want to init crypto, so throw if we can't
if (!this.client.crypto) throw new Error("Crypto is not initialised.");
const userId = this.invitee || ((_this$getOpponentMemb = this.getOpponentMember()) === null || _this$getOpponentMemb === void 0 ? void 0 : _this$getOpponentMemb.userId);
if (!userId) throw new Error("Couldn't find opponent user ID to init crypto");
const deviceInfoMap = await this.client.crypto.deviceList.downloadKeys([userId], false);
this.opponentDeviceInfo = (_deviceInfoMap$get = deviceInfoMap.get(userId)) === null || _deviceInfoMap$get === void 0 ? void 0 : _deviceInfoMap$get.get(this.opponentDeviceId);
if (this.opponentDeviceInfo === undefined) {
throw new _groupCall.GroupCallUnknownDeviceError(userId);
}
}
/**
* Generates and returns localSDPStreamMetadata
* @returns localSDPStreamMetadata
*/
getLocalSDPStreamMetadata(updateStreamIds = false) {
const metadata = {};
for (const localFeed of this.getLocalFeeds()) {
if (updateStreamIds) {
localFeed.sdpMetadataStreamId = localFeed.stream.id;
}
metadata[localFeed.sdpMetadataStreamId] = {
purpose: localFeed.purpose,
audio_muted: localFeed.isAudioMuted(),
video_muted: localFeed.isVideoMuted()
};
}
return metadata;
}
/**
* Returns true if there are no incoming feeds,
* otherwise returns false
* @returns no incoming feeds
*/
noIncomingFeeds() {
return !this.feeds.some(feed => !feed.isLocal());
}
pushRemoteFeed(stream) {
// Fallback to old behavior if the other side doesn't support SDPStreamMetadata
if (!this.opponentSupportsSDPStreamMetadata()) {
this.pushRemoteFeedWithoutMetadata(stream);
return;
}
const userId = this.getOpponentMember().userId;
const purpose = this.remoteSDPStreamMetadata[stream.id].purpose;
const audioMuted = this.remoteSDPStreamMetadata[stream.id].audio_muted;
const videoMuted = this.remoteSDPStreamMetadata[stream.id].video_muted;
if (!purpose) {
_logger.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${stream.id})`);
return;
}
if (this.getFeedByStreamId(stream.id)) {
_logger.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${stream.id})`);
return;
}
this.feeds.push(new _callFeed.CallFeed({
client: this.client,
call: this,
roomId: this.roomId,
userId,
deviceId: this.getOpponentDeviceId(),
stream,
purpose,
audioMuted,
videoMuted
}));
this.emit(CallEvent.FeedsChanged, this.feeds, this);
_logger.logger.info(`Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${stream.id}, active=${stream.active}, purpose=${purpose})`);
}
/**
* This method is used ONLY if the other client doesn't support sending SDPStreamMetadata
*/
pushRemoteFeedWithoutMetadata(stream) {
var _this$feeds$find;
const userId = this.getOpponentMember().userId;
// We can guess the purpose here since the other client can only send one stream
const purpose = _callEventTypes.SDPStreamMetadataPurpose.Usermedia;
const oldRemoteStream = (_this$feeds$find = this.feeds.find(feed => !feed.isLocal())) === null || _this$feeds$find === void 0 ? void 0 : _this$feeds$find.stream;
// Note that we check by ID and always set the remote stream: Chrome appears
// to make new stream objects when transceiver directionality is changed and the 'active'
// status of streams change - Dave
// If we already have a stream, check this stream has the same id
if (oldRemoteStream && stream.id !== oldRemoteStream.id) {
_logger.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${stream.id})`);
return;
}
if (this.getFeedByStreamId(stream.id)) {
_logger.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${stream.id})`);
return;
}
this.feeds.push(new _callFeed.CallFeed({
client: this.client,
call: this,
roomId: this.roomId,
audioMuted: false,
videoMuted: false,
userId,
deviceId: this.getOpponentDeviceId(),
stream,
purpose
}));
this.emit(CallEvent.FeedsChanged, this.feeds, this);
_logger.logger.info(`Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${stream.id}, active=${stream.active})`);
}
pushNewLocalFeed(stream, purpose, addToPeerConnection = true) {
const userId = this.client.getUserId();
// Tracks don't always start off enabled, eg. chrome will give a disabled
// audio track if you ask for user media audio and already had one that
// you'd set to disabled (presumably because it clones them internally).
setTracksEnabled(stream.getAudioTracks(), true);
setTracksEnabled(stream.getVideoTracks(), true);
if (this.getFeedByStreamId(stream.id)) {
_logger.logger.warn(`Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${stream.id})`);
return;
}
this.pushLocalFeed(new _callFeed.CallFeed({
client: this.client,
roomId: this.roomId,
audioMuted: false,
videoMuted: false,
userId,
deviceId: this.getOpponentDeviceId(),
stream,
purpose
}), addToPeerConnection);
}
/**
* Pushes supplied feed to the call
* @param callFeed - to push
* @param addToPeerConnection - whether to add the tracks to the peer connection
*/
pushLocalFeed(callFeed, addToPeerConnection = true) {
if (this.feeds.some(feed => callFeed.stream.id === feed.stream.id)) {
_logger.logger.info(`Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${callFeed.stream.id})`);
return;
}
this.feeds.push(callFeed);
if (addToPeerConnection) {
for (const track of callFeed.stream.getTracks()) {
_logger.logger.info(`Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${track.id}, kind=${track.kind}, streamId=${callFeed.stream.id}, streamPurpose=${callFeed.purpose}, enabled=${track.enabled})`);
const tKey = getTransceiverKey(callFeed.purpose, track.kind);
if (this.transceivers.has(tKey)) {
// we already have a sender, so we re-use it. We try to re-use transceivers as much
// as possible because they can't be removed once added, so otherwise they just
// accumulate which makes the SDP very large very quickly: in fact it only takes
// about 6 video tracks to exceed the maximum size of an Olm-encrypted
// Matrix event.
const transceiver = this.transceivers.get(tKey);
transceiver.sender.replaceTrack(track);
// set the direction to indicate we're going to start sending again
// (this will trigger the re-negotiation)
transceiver.direction = transceiver.direction === "inactive" ? "sendonly" : "sendrecv";
} else {
// create a new one. We need to use addTrack rather addTransceiver for this because firefox
// doesn't yet implement RTCRTPSender.setStreams()
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1510802) so we'd have no way to group the
// two tracks together into a stream.
const newSender = this.peerConn.addTrack(track, callFeed.stream);
// now go & fish for the new transceiver
const newTransceiver = this.peerConn.getTransceivers().find(t => t.sender === newSender);
if (newTransceiver) {
this.transceivers.set(tKey, newTransceiver);
} else {
_logger.logger.warn(`Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`);
}
}
}
}
_logger.logger.info(`Call ${this.callId} pushLocalFeed() pushed stream (id=${callFeed.stream.id}, active=${callFeed.stream.active}, purpose=${callFeed.purpose})`);
this.emit(CallEvent.FeedsChanged, this.feeds, this);
}
/**
* Removes local call feed from the call and its tracks from the peer
* connection
* @param callFeed - to remove
*/
removeLocalFeed(callFeed) {
const audioTransceiverKey = getTransceiverKey(callFeed.purpose, "audio");
const videoTransceiverKey = getTransceiverKey(callFeed.purpose, "video");
for (const transceiverKey of [audioTransceiverKey, videoTransceiverKey]) {
// this is slightly mixing the track and transceiver API but is basically just shorthand.
// There is no way to actually