Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix some MatrixCall leaks and use a shared AudioContext #2484

Merged
merged 3 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ module.exports = {
// We're okay with assertion errors when we ask for them
"@typescript-eslint/no-non-null-assertion": "off",

// The base rule produces false positives
"func-call-spacing": "off",
"@typescript-eslint/func-call-spacing": ["error"],

"quotes": "off",
// We use a `logger` intermediary module
"no-console": "error",
Expand Down
44 changes: 44 additions & 0 deletions src/webrtc/audioContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.

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.
*/

let audioContext: AudioContext | null = null;
let refCount = 0;

/**
* Acquires a reference to the shared AudioContext.
* It's highly recommended to reuse this AudioContext rather than creating your
* own, because multiple AudioContexts can be problematic in some browsers.
* Make sure to call releaseContext when you're done using it.
* @returns {AudioContext} The shared AudioContext
*/
export const acquireContext = (): AudioContext => {
if (audioContext === null) audioContext = new AudioContext();
refCount++;
return audioContext;
};

/**
* Signals that one of the references to the shared AudioContext has been
* released, allowing the context and associated hardware resources to be
* cleaned up if nothing else is using it.
*/
export const releaseContext = () => {
refCount--;
if (refCount === 0) {
audioContext.close();
audioContext = null;
}
};
52 changes: 36 additions & 16 deletions src/webrtc/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap
private opponentCaps: CallCapabilities;
private iceDisconnectedTimeout: ReturnType<typeof setTimeout>;
private inviteTimeout: ReturnType<typeof setTimeout>;
private readonly removeTrackListeners = new Map<MediaStream, () => void>();

// 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
Expand Down Expand Up @@ -841,18 +842,25 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap
this.setState(CallState.Ringing);

if (event.getLocalAge()) {
setTimeout(() => {
if (this.state == CallState.Ringing) {
logger.debug(`Call ${this.callId} invite has expired. Hanging up.`);
this.hangupParty = CallParty.Remote; // effectively
this.setState(CallState.Ended);
this.stopAllMedia();
if (this.peerConn.signalingState != 'closed') {
this.peerConn.close();
}
this.emit(CallEvent.Hangup, this);
// Time out the call if it's ringing for too long
const ringingTimer = setTimeout(() => {
logger.debug(`Call ${this.callId} invite has expired. Hanging up.`);
this.hangupParty = CallParty.Remote; // effectively
this.setState(CallState.Ended);
this.stopAllMedia();
if (this.peerConn.signalingState != 'closed') {
this.peerConn.close();
}
this.emit(CallEvent.Hangup, this);
}, invite.lifetime - event.getLocalAge());

const onState = (state: CallState) => {
if (state !== CallState.Ringing) {
clearTimeout(ringingTimer);
this.off(CallEvent.State, onState);
}
};
this.on(CallEvent.State, onState);
}
}

Expand Down Expand Up @@ -1986,12 +1994,19 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap

const stream = ev.streams[0];
this.pushRemoteFeed(stream);
stream.addEventListener("removetrack", () => {
if (stream.getTracks().length === 0) {
logger.info(`Call ${this.callId} removing track streamId: ${stream.id}`);
this.deleteFeedByStream(stream);
}
});

if (!this.removeTrackListeners.has(stream)) {
const onRemoveTrack = () => {
if (stream.getTracks().length === 0) {
logger.info(`Call ${this.callId} 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);
}
};

private onDataChannel = (ev: RTCDataChannelEvent): void => {
Expand Down Expand Up @@ -2290,6 +2305,11 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap
this.callLengthInterval = null;
}

for (const [stream, listener] of this.removeTrackListeners) {
stream.removeEventListener("removetrack", listener);
}
this.removeTrackListeners.clear();

this.callStatsAtEnd = await this.collectCallStats();

// Order is important here: first we stopAllMedia() and only then we can deleteAllFeeds()
Expand Down
15 changes: 10 additions & 5 deletions src/webrtc/callFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ limitations under the License.
*/

import { SDPStreamMetadataPurpose } from "./callEventTypes";
import { acquireContext, releaseContext } from "./audioContext";
import { MatrixClient } from "../client";
import { RoomMember } from "../models/room-member";
import { logger } from "../logger";
Expand Down Expand Up @@ -118,10 +119,8 @@ export class CallFeed extends TypedEventEmitter<CallFeedEvent, EventHandlerMap>
}

private initVolumeMeasuring(): void {
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (!this.hasAudioTrack || !AudioContext) return;

this.audioContext = new AudioContext();
if (!this.hasAudioTrack) return;
if (!this.audioContext) this.audioContext = acquireContext();

this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 512;
Expand Down Expand Up @@ -211,7 +210,7 @@ export class CallFeed extends TypedEventEmitter<CallFeedEvent, EventHandlerMap>
*/
public measureVolumeActivity(enabled: boolean): void {
if (enabled) {
if (!this.audioContext || !this.analyser || !this.frequencyBinCount || !this.hasAudioTrack) return;
if (!this.analyser || !this.frequencyBinCount || !this.hasAudioTrack) return;

this.measuringVolumeActivity = true;
this.volumeLooper();
Expand Down Expand Up @@ -288,5 +287,11 @@ export class CallFeed extends TypedEventEmitter<CallFeedEvent, EventHandlerMap>

public dispose(): void {
clearTimeout(this.volumeLooperTimeout);
this.stream?.removeEventListener("addtrack", this.onAddTrack);
if (this.audioContext) {
this.audioContext = null;
this.analyser = null;
releaseContext();
}
}
}