UNPKG

matrix-js-sdk

Version:
1,065 lines (1,027 loc) 120 kB
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /* 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. */ import { v4 as uuidv4 } from "uuid"; import { parse as parseSdp, write as writeSdp } from "sdp-transform"; import { logger } from "../logger.js"; import { checkObjectHasKeys, isNullOrUndefined, recursivelyAssign } from "../utils.js"; import { EventType, ToDeviceMessageId } from "../@types/event.js"; import { secureRandomString } from "../randomstring.js"; import { SDPStreamMetadataPurpose, SDPStreamMetadataKey } from "./callEventTypes.js"; import { CallFeed } from "./callFeed.js"; import { EventEmitterEvents, TypedEventEmitter } from "../models/typed-event-emitter.js"; import { GroupCallUnknownDeviceError } from "./groupCall.js"; import { MatrixError } from "../http-api/index.js"; var MediaType = /*#__PURE__*/function (MediaType) { MediaType["AUDIO"] = "audio"; MediaType["VIDEO"] = "video"; return MediaType; }(MediaType || {}); var CodecName = /*#__PURE__*/function (CodecName) { CodecName["OPUS"] = "opus"; // add more as needed return CodecName; }(CodecName || {}); // Used internally to specify modifications to codec parameters in SDP export var 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; }({}); export var CallType = /*#__PURE__*/function (CallType) { CallType["Voice"] = "voice"; CallType["Video"] = "video"; return CallType; }({}); export var CallDirection = /*#__PURE__*/function (CallDirection) { CallDirection["Inbound"] = "inbound"; CallDirection["Outbound"] = "outbound"; return CallDirection; }({}); export var CallParty = /*#__PURE__*/function (CallParty) { CallParty["Local"] = "local"; CallParty["Remote"] = "remote"; return CallParty; }({}); export var CallEvent = /*#__PURE__*/function (CallEvent) { CallEvent["Hangup"] = "hangup"; CallEvent["State"] = "state"; CallEvent["Error"] = "error"; CallEvent["Replaced"] = "replaced"; // The value of isLocalOnHold() has changed CallEvent["LocalHoldUnhold"] = "local_hold_unhold"; // The value of isRemoteOnHold() has changed CallEvent["RemoteHoldUnhold"] = "remote_hold_unhold"; // backwards compat alias for LocalHoldUnhold: remove in a major version bump CallEvent["HoldUnhold"] = "hold_unhold"; // Feeds have changed CallEvent["FeedsChanged"] = "feeds_changed"; CallEvent["AssertedIdentityChanged"] = "asserted_identity_changed"; CallEvent["LengthChanged"] = "length_changed"; CallEvent["DataChannel"] = "datachannel"; CallEvent["SendVoipEvent"] = "send_voip_event"; // When the call instantiates its peer connection // For apps that want to access the underlying peer connection, eg for debugging CallEvent["PeerConnectionCreated"] = "peer_connection_created"; return CallEvent; }({}); export var CallErrorCode = /*#__PURE__*/function (CallErrorCode) { /** The user chose to end the call */ CallErrorCode["UserHangup"] = "user_hangup"; /** An error code when the local client failed to create an offer. */ CallErrorCode["LocalOfferFailed"] = "local_offer_failed"; /** * An error code when there is no local mic/camera to use. This may be because * the hardware isn't plugged in, or the user has explicitly denied access. */ CallErrorCode["NoUserMedia"] = "no_user_media"; /** * Error code used when a call event failed to send * because unknown devices were present in the room */ CallErrorCode["UnknownDevices"] = "unknown_devices"; /** * Error code used when we fail to send the invite * for some reason other than there being unknown devices */ CallErrorCode["SendInvite"] = "send_invite"; /** * An answer could not be created */ CallErrorCode["CreateAnswer"] = "create_answer"; /** * An offer could not be created */ CallErrorCode["CreateOffer"] = "create_offer"; /** * Error code used when we fail to send the answer * for some reason other than there being unknown devices */ CallErrorCode["SendAnswer"] = "send_answer"; /** * The session description from the other side could not be set */ CallErrorCode["SetRemoteDescription"] = "set_remote_description"; /** * The session description from this side could not be set */ CallErrorCode["SetLocalDescription"] = "set_local_description"; /** * A different device answered the call */ CallErrorCode["AnsweredElsewhere"] = "answered_elsewhere"; /** * No media connection could be established to the other party */ CallErrorCode["IceFailed"] = "ice_failed"; /** * The invite timed out whilst waiting for an answer */ CallErrorCode["InviteTimeout"] = "invite_timeout"; /** * The call was replaced by another call */ CallErrorCode["Replaced"] = "replaced"; /** * Signalling for the call could not be sent (other than the initial invite) */ CallErrorCode["SignallingFailed"] = "signalling_timeout"; /** * The remote party is busy */ CallErrorCode["UserBusy"] = "user_busy"; /** * We transferred the call off to somewhere else */ CallErrorCode["Transferred"] = "transferred"; /** * A call from the same user was found with a new session id */ CallErrorCode["NewSession"] = "new_session"; return CallErrorCode; }({}); /** * The version field that we set in m.call.* events */ var VOIP_PROTO_VERSION = "1"; /** The fallback ICE server to use for STUN or TURN protocols. */ export var FALLBACK_ICE_SERVER = "stun:turn.matrix.org"; /** The length of time a call can be ringing for. */ var CALL_TIMEOUT_MS = 60 * 1000; // ms /** The time after which we increment callLength */ var CALL_LENGTH_INTERVAL = 1000; // ms /** The time after which we end the call, if ICE got disconnected */ var ICE_DISCONNECTED_TIMEOUT = 30 * 1000; // ms /** The time after which we try a ICE restart, if ICE got disconnected */ var ICE_RECONNECTING_TIMEOUT = 2 * 1000; // ms export class CallError extends Error { constructor(code, msg, err) { // Still don't think there's any way to have proper nested errors super(msg + ": " + err); _defineProperty(this, "code", void 0); this.code = code; } } export function genCallID() { return Date.now().toString() + secureRandomString(16); } function getCodecParamMods(isPtt) { var 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; } export class MatrixCall extends TypedEventEmitter { /** * Construct a new Matrix Call. * @param opts - Config options. */ constructor(opts) { var _this, _opts$forceTURN; super(); _this = this; _defineProperty(this, "roomId", void 0); _defineProperty(this, "callId", void 0); _defineProperty(this, "invitee", void 0); _defineProperty(this, "hangupParty", void 0); _defineProperty(this, "hangupReason", void 0); _defineProperty(this, "direction", void 0); _defineProperty(this, "ourPartyId", void 0); _defineProperty(this, "peerConn", void 0); _defineProperty(this, "toDeviceSeq", 0); // whether this call should have push-to-talk semantics // This should be set by the consumer on incoming & outgoing calls. _defineProperty(this, "isPtt", false); _defineProperty(this, "_state", CallState.Fledgling); _defineProperty(this, "client", void 0); _defineProperty(this, "forceTURN", void 0); _defineProperty(this, "turnServers", void 0); // A queue for candidates waiting to go out. // We try to amalgamate candidates into a single candidate message where // possible _defineProperty(this, "candidateSendQueue", []); _defineProperty(this, "candidateSendTries", 0); _defineProperty(this, "candidatesEnded", false); _defineProperty(this, "feeds", []); // our transceivers for each purpose and type of media _defineProperty(this, "transceivers", new Map()); _defineProperty(this, "inviteOrAnswerSent", false); _defineProperty(this, "waitForLocalAVStream", false); _defineProperty(this, "successor", void 0); _defineProperty(this, "opponentMember", void 0); _defineProperty(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. _defineProperty(this, "opponentPartyId", void 0); _defineProperty(this, "opponentCaps", void 0); _defineProperty(this, "iceDisconnectedTimeout", void 0); _defineProperty(this, "iceReconnectionTimeOut", void 0); _defineProperty(this, "inviteTimeout", void 0); _defineProperty(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 _defineProperty(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' :( _defineProperty(this, "callStatsAtEnd", void 0); // Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example _defineProperty(this, "makingOffer", false); _defineProperty(this, "ignoreOffer", false); _defineProperty(this, "isSettingRemoteAnswerPending", false); _defineProperty(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 _defineProperty(this, "remoteCandidateBuffer", new Map()); _defineProperty(this, "remoteAssertedIdentity", void 0); _defineProperty(this, "remoteSDPStreamMetadata", void 0); _defineProperty(this, "callLengthInterval", void 0); _defineProperty(this, "callStartTime", void 0); _defineProperty(this, "opponentDeviceId", void 0); _defineProperty(this, "hasOpponentDeviceInfo", void 0); _defineProperty(this, "opponentSessionId", void 0); _defineProperty(this, "groupCallId", void 0); // Used to keep the timer for the delay before actually stopping our // video track after muting (see setLocalVideoMuted) _defineProperty(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 _defineProperty(this, "isOnlyDataChannelAllowed", void 0); _defineProperty(this, "stats", void 0); /** * Internal */ _defineProperty(this, "gotLocalIceCandidate", event => { if (event.candidate) { if (this.candidatesEnded) { logger.warn("Call ".concat(this.callId, " gotLocalIceCandidate() got candidate after candidates have ended!")); } logger.debug("Call ".concat(this.callId, " got local ICE ").concat(event.candidate.sdpMid, " ").concat(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); } } }); _defineProperty(this, "onIceGatheringStateChange", event => { var _this$peerConn; logger.debug("Call ".concat(this.callId, " onIceGatheringStateChange() ice gathering state changed to ").concat(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.debug("Call ".concat(this.callId, " onIceGatheringStateChange() ice gathering state complete, set candidates have ended")); } }); _defineProperty(this, "getLocalOfferFailed", err => { logger.error("Call ".concat(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); }); _defineProperty(this, "getUserMediaFailed", err => { if (this.successor) { this.successor.getUserMediaFailed(err); return; } logger.warn("Call ".concat(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); }); _defineProperty(this, "placeCallFailed", err => { if (this.successor) { this.successor.placeCallFailed(err); return; } logger.warn("Call ".concat(this.callId, " placeCallWithCallFeeds() failed - ending call"), err); this.emit(CallEvent.Error, new CallError(CallErrorCode.IceFailed, "Couldn't start call! Invalid ICE server configuration.", err), this); this.terminate(CallParty.Local, CallErrorCode.IceFailed, false); }); _defineProperty(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.debug("Call ".concat(this.callId, " onIceConnectionStateChanged() running (state=").concat((_this$peerConn2 = this.peerConn) === null || _this$peerConn2 === void 0 ? void 0 : _this$peerConn2.iceConnectionState, ", conn=").concat((_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.debug("Call ".concat(this.callId, " onIceConnectionStateChanged() ice restart (state=").concat((_this$peerConn7 = this.peerConn) === null || _this$peerConn7 === void 0 ? void 0 : _this$peerConn7.iceConnectionState, ")")); this.peerConn.restartIce(); } else { logger.info("Call ".concat(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$peerConn0, _this$peerConn1; logger.info("Call ".concat(this.callId, " onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=").concat((_this$peerConn9 = this.peerConn) === null || _this$peerConn9 === void 0 ? void 0 : _this$peerConn9.iceConnectionState, ", conn=").concat((_this$peerConn0 = this.peerConn) === null || _this$peerConn0 === void 0 ? void 0 : _this$peerConn0.connectionState, ")")); if ((_this$peerConn1 = this.peerConn) !== null && _this$peerConn1 !== void 0 && _this$peerConn1.restartIce) { this.candidatesEnded = false; this.peerConn.restartIce(); } this.iceReconnectionTimeOut = undefined; }, ICE_RECONNECTING_TIMEOUT); this.iceDisconnectedTimeout = setTimeout(() => { logger.info("Call ".concat(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 (var feed of this.getRemoteFeeds()) { feed.setAudioVideoMuted(true, true); } } }); _defineProperty(this, "onSignallingStateChanged", () => { var _this$peerConn10; logger.debug("Call ".concat(this.callId, " onSignallingStateChanged() running (state=").concat((_this$peerConn10 = this.peerConn) === null || _this$peerConn10 === void 0 ? void 0 : _this$peerConn10.signalingState, ")")); }); _defineProperty(this, "onTrack", ev => { if (ev.streams.length === 0) { logger.warn("Call ".concat(this.callId, " onTrack() called with streamless track streamless (kind=").concat(ev.track.kind, ")")); return; } var stream = ev.streams[0]; this.pushRemoteFeed(stream); if (!this.removeTrackListeners.has(stream)) { var onRemoveTrack = () => { if (stream.getTracks().length === 0) { logger.info("Call ".concat(this.callId, " onTrack() removing track (streamId=").concat(stream.id, ")")); this.deleteFeedByStream(stream); stream.removeEventListener("removetrack", onRemoveTrack); this.removeTrackListeners.delete(stream); } }; stream.addEventListener("removetrack", onRemoveTrack); this.removeTrackListeners.set(stream, onRemoveTrack); } }); _defineProperty(this, "onDataChannel", ev => { this.emit(CallEvent.DataChannel, ev.channel, this); }); _defineProperty(this, "onNegotiationNeeded", /*#__PURE__*/_asyncToGenerator(function* () { logger.info("Call ".concat(_this.callId, " onNegotiationNeeded() negotiation is needed!")); if (_this.state !== CallState.CreateOffer && _this.opponentVersion === 0) { logger.info("Call ".concat(_this.callId, " onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event")); return; } _this.queueGotLocalOffer(); })); _defineProperty(this, "onHangupReceived", msg => { logger.debug("Call ".concat(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.info("Call ".concat(this.callId, " onHangupReceived() ignoring message from party ID ").concat(msg.party_id, ": our partner is ").concat(this.opponentPartyId)); } }); _defineProperty(this, "onRejectReceived", msg => { logger.debug("Call ".concat(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 var 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.debug("Call ".concat(this.callId, " onRejectReceived() called in wrong state (state=").concat(this.state, ")")); } }); _defineProperty(this, "onAnsweredElsewhere", msg => { logger.debug("Call ".concat(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 (var server of this.turnServers) { 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. */ placeVoiceCall() { var _this2 = this; return _asyncToGenerator(function* () { yield _this2.placeCall(true, false); })(); } /** * Place a video call to this room. * @throws If you have not specified a listener for 'error' events. */ placeVideoCall() { var _this3 = this; return _asyncToGenerator(function* () { yield _this3.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) { var 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) { var 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 === 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 === 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(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(SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _this$transceivers$ge2 === void 0 ? void 0 : _this$transceivers$ge2.sender); } get localUsermediaFeed() { return this.getLocalFeeds().find(feed => feed.purpose === SDPStreamMetadataPurpose.Usermedia); } get localScreensharingFeed() { return this.getLocalFeeds().find(feed => feed.purpose === 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 === SDPStreamMetadataPurpose.Usermedia); } get remoteScreensharingFeed() { return this.getRemoteFeeds().find(feed => feed.purpose === 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()); } initOpponentCrypto() { var _this4 = this; return _asyncToGenerator(function* () { var _this4$getOpponentMem; if (!_this4.opponentDeviceId) return; if (!_this4.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 (!_this4.client.getCrypto()) { // All we know is the device ID _this4.hasOpponentDeviceInfo = true; return; } var userId = _this4.invitee || ((_this4$getOpponentMem = _this4.getOpponentMember()) === null || _this4$getOpponentMem === void 0 ? void 0 : _this4$getOpponentMem.userId); if (!userId) throw new Error("Couldn't find opponent user ID to init crypto"); // Here we were calling `MatrixClient.crypto.deviceList.downloadKeys` which is not supported by the rust cryptography. _this4.hasOpponentDeviceInfo = false; throw new GroupCallUnknownDeviceError(userId); })(); } /** * Generates and returns localSDPStreamMetadata * @returns localSDPStreamMetadata */ getLocalSDPStreamMetadata() { var updateStreamIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var metadata = {}; for (var 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; } var userId = this.getOpponentMember().userId; var purpose = this.remoteSDPStreamMetadata[stream.id].purpose; var audioMuted = this.remoteSDPStreamMetadata[stream.id].audio_muted; var videoMuted = this.remoteSDPStreamMetadata[stream.id].video_muted; if (!purpose) { logger.warn("Call ".concat(this.callId, " pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=").concat(stream.id, ")")); return; } if (this.getFeedByStreamId(stream.id)) { logger.warn("Call ".concat(this.callId, " pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=").concat(stream.id, ")")); return; } this.feeds.push(new 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.info("Call ".concat(this.callId, " pushRemoteFeed() pushed stream (streamId=").concat(stream.id, ", active=").concat(stream.active, ", purpose=").concat(purpose, ")")); } /** * This method is used ONLY if the other client doesn't support sending SDPStreamMetadata */ pushRemoteFeedWithoutMetadata(stream) { var _this$feeds$find; var userId = this.getOpponentMember().userId; // We can guess the purpose here since the other client can only send one stream var purpose = SDPStreamMetadataPurpose.Usermedia; var 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.warn("Call ".concat(this.callId, " pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=").concat(stream.id, ")")); return; } if (this.getFeedByStreamId(stream.id)) { logger.warn("Call ".concat(this.callId, " pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=").concat(stream.id, ")")); return; } this.feeds.push(new 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.info("Call ".concat(this.callId, " pushRemoteFeedWithoutMetadata() pushed stream (streamId=").concat(stream.id, ", active=").concat(stream.active, ")")); } pushNewLocalFeed(stream, purpose) { var addToPeerConnection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var 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.warn("Call ".concat(this.callId, " pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=").concat(stream.id, ")")); return; } this.pushLocalFeed(new 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) { var _this5 = this; var addToPeerConnection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (this.feeds.some(feed => callFeed.stream.id === feed.stream.id)) { logger.info("Call ".concat(this.callId, " pushLocalFeed() ignoring duplicate local stream (streamId=").concat(callFeed.stream.id, ")")); return; } this.feeds.push(callFeed); if (addToPeerConnection) { var _loop = function _loop() { logger.info("Call ".concat(_this5.callId, " pushLocalFeed() adding track to peer connection (id=").concat(track.id, ", kind=").concat(track.kind, ", streamId=").concat(callFeed.stream.id, ", streamPurpose=").concat(callFeed.purpose, ", enabled=").concat(track.enabled, ")")); var tKey = getTransceiverKey(callFeed.purpose, track.kind); if (_this5.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. var transceiver = _this5.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. var newSender = _this5.peerConn.addTrack(track, callFeed.stream); // now go & fish for the new transceiver var newTransceiver = _this5.peerConn.getTransceivers().find(t => t.sender === newSender); if (newTransceiver) { _this5.transceivers.set(tKey, newTransceiver); } else { logger.warn("Call ".concat(_this5.callId, " pushLocalFeed() didn't find a matching transceiver after adding track!")); } } }; for (var track of callFeed.stream.getTracks()) { _loop(); } } logger.info("Call ".concat(this.callId, " pushLocalFeed() pushed stream (id=").concat(callFeed.stream.id, ", active=").concat(callFeed.stream.active, ", purpose=").concat(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) { var audioTransceiverKey = getTransceiverKey(callFeed.purpose, "audio"); var videoTransceiverKey = getTransceiverKey(callFeed.purpose, "video"); for (var transceiverKey of [audioTransceiverKey, videoTransceiverKey]) { // this is slightly mixing the track and transceiver API but is basically just shorthand. // There is no way to actually remove a transceiver, so this just sets it to inactive // (or recvonly) and replaces the source with nothing. if (this.transceivers.has(transceiverKey)) { var transceiver = this.transceivers.get(transceiverKey); if (transceiver.sender) this.peerConn.removeTrack(transceiver.sender); } } if (callFeed.purpose === SDPStreamMetadataPurpose.Screenshare) { this.client.getMediaHandler().stopScreensharingStream(callFeed.stream); } this.deleteFeed(callFeed); } deleteAllFeeds() { for (var feed of this.feeds) { if (!feed.isLocal() || !this.groupCallId) { feed.dispose(); } } this.feeds = []; this.emit(CallEvent.FeedsChanged, this.feeds, this); } deleteFeedByStream(stream) { var feed = this.getFeedByStreamId(stream.id); if (!feed) { logger.warn("Call ".concat(this.callId, " deleteFeedByStream() didn't find the feed to delete (streamId=").concat(stream.id, ")")); return; } this.deleteFeed(feed); } deleteFeed(feed) { feed.dispose(); this.feeds.splice(this.feeds.indexOf(feed), 1); this.emit(CallEvent.FeedsChanged, this.feeds, this); } // The typescript definitions have this type as 'any' :( getCurrentCallStats() { var _this6 = this; return _asyncToGenerator(function* () { if (_this6.callHasEnded()) { return _this6.callStatsAtEnd; } return _this6.collectCallStats(); })(); } collectCallStats() { var _this7 = this; return _asyncToGenerator(function* () { // This happens when the call fails before it starts. // For example when we fail to get capture sources if (!_this7.peerConn) return; var statsReport = yield _this7.peerConn.getStats(); var stats = []; statsReport.forEach(item => { stats.push(item); }); return stats; })(); } /** * Configure this call from an invite event. Used by MatrixClient. * @param event - The m.call.invite event */ initWithInvite(event) { var _this8 = this; return _asyncToGenerator(function* () { var _this8$feeds$find; var invite = event.getContent(); _this8.direction = CallDirection.Inbound; // make sure we have valid turn creds. Unless something's gone wrong, it should // poll and keep the credentials valid so this should be instant. var haveTurnCreds = yield _this8.client.checkTurnServers(); if (!haveTurnCreds) { logger.warn("Call ".concat(_this8.callId, " initWithInvite() failed to get TURN credentials! Proceeding with call anyway...")); } var sdpStreamMetadata = SDPStreamMetadataKey.findIn(invite); if (sdpStreamMetadata) { _this8.updateRemoteSDPStreamMetadata(sdpStreamMetadata); } else { logger.debug("Call ".concat(_this8.callId, " initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams")); } _this8.peerConn = _this8.createPeerConnection(); _this8.emit(CallEvent.PeerConnectionCreated, _this8.peerConn, _this8); // we must set the party ID before await-ing on anything: the call event // handler will start giving us more call events (eg. candidates) so if // we haven't set the party ID, we'll ignore them. _this8.chooseOpponent(event); yield _this8.initOpponentCrypto(); try { yield _this8.peerConn.setRemoteDescription(invite.offer); logger.debug("Call ".concat(_this8.callId, " initWithInvite() set remote description: ").concat(invite.offer.type)); yield _this8.addBufferedIceCandidates(); } catch (e) { logger.debug("Call ".concat(_this8.callId, " initWithInvite() failed to set remote description"), e); _this8.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false); return; } var remoteStream = (_this8$feeds$find = _this8.feeds.find(feed => !feed.isLocal())) === null || _this8$feeds$find === void 0 ? void 0 : _this8$feeds$find.stream; // According to previous comments in this file, firefox at some point did not // add streams until media started arriving on them. Testing latest firefox // (81 at time of writing), this is no longer a problem, so let's do it the correct way. // // For example in case of no media webrtc connections like screen share only call we have to allow webrtc // connections without remote media. In this case we always use a data channel. At the moment we allow as well // only data channel as media in the WebRTC connection with this setup here. if (!_this8.isOnlyDataChannelAllowed && (!remoteStream || remoteStream.getTracks().length === 0)) { logger.error("Call ".concat(_this8.callId, " initWithInvite() no remote stream or no tracks after setting remote description!")); _this8.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false); return; } _this8.state = CallState.Ringing; if (event.getLocalAge()) { // Time out the call if it's ringing for too long var ringingTimer = setTimeout(() => { if (_this8.state == CallState.Ringing) { var _this8$stats; logger.debug("Call ".concat(_this8.callId, " initWithInvite() invite has expired. Hanging up.")); _this8.hangupParty = CallParty.Remote; // effectively _this8.state = CallState.Ended; _this8.stopAllMedia(); if (_this8.peerConn.signalingState != "closed") { _this8.peerConn.close(); } (_this8$stats = _this8.stats) === null || _this8$stats === void 0 || _this8$stats.removeStatsReportGatherer(_this8.callId); _this8.emit(CallEvent.Hangup, _this8); } }, invite.lifetime - event.getLocalAge()); var onState = state => { if (state !== CallState.Ringing) { clearTimeout(ringingTimer); _this8.off(CallEvent.State, onState); } }; _this8.on(CallEvent.State, onState); } })(); } /** * Configure this call from a hangup or reject event. Used by MatrixClient. * @param event - The m.call.hangup event */ initWithHangup(event) { // perverse as it may seem, sometimes we want to instantiate a call with a // hangup message (because when getting the state of the room on load, events // come in reverse order and we want to remember that a call has been hung up) this.state = CallState.Ended; } shouldAnswerWithMediaType(wantedValue, valueOfTheOtherSide, type) { if (wantedValue && !valueOfTheOtherSide) { // TODO: Figure out how to do this logger.warn("Call ".concat(this.callId, " shouldAnswerWithMediaType() unable to answer with ").concat(type, " because the other side isn't sending it either.")); return false; } else if (!isNullOrUndefined(wantedValue) && wantedValue !== valueOfTheOtherSide && !this.opponentSupportsSDPStreamMetadata()) { logger.warn("Call ".concat(this.callId, " shouldAnswerWithMediaType() unable to answer with ").concat(type, "=").concat(wantedValue, " because the other side doesn't support it. Answering with ").concat(type, "=").concat(valueOfTheOtherSide, ".")); return valueOfTheOtherSide; } return wantedValue !== null && wantedValue !== void 0 ? wantedValue : valueOfTheOtherSide; } /** * Answer a call. */ answer(audio, video) { var _this9 = this; return _asyncToGenerator(function* () { if (_this9.inviteOrAnswerSent) return; // TODO: Figure out how to do this if (audio === false && video === false) throw new Error("You CANNOT answer a call without media"); if (!_this9.localUsermediaStream && !_this9.waitForLocalAVStream) { var prevState = _this9.state; var answerWithAudio = _this9.shouldAnswerWithMediaType(audio, _this9.hasRemoteUserMediaAudioTrack, "audio"); var answerWithVideo = _this9.shouldAnswerWithMediaType(video, _this9.hasRemoteUserMediaVideoTrack, "video"); _this9.state = CallState.WaitLocalMedia; _this9.waitForLocalAVStream = true; try { var _this9$client$getDevi; var stream = yield _this9.client.getMediaHandler().getUserMediaStream(answerWithAudio, answerWithVideo); _this9.waitForLocalAVStream = false; var usermediaFeed = new CallFeed({ client: _this9.client, roomId: _this9.roomId, userId: _this9.client.getUserId(), deviceId: (_this9$client$getDevi = _this9.client.getDeviceId()) !== null && _this9$client$getDevi !== void 0 ? _this9$client$getDevi : undefined, stream, purpose: SDPStreamMetadataPurpose.Usermedia, audioMuted: false, videoMuted: false }); var feeds =