element-call/src/room/usePTT.ts

280 lines
7.3 KiB
TypeScript
Raw Normal View History

2022-05-04 16:09:48 +00:00
/*
Copyright 2022 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.
*/
2022-04-29 00:44:50 +00:00
import { useCallback, useEffect, useState } from "react";
2022-05-06 10:32:09 +00:00
import { MatrixClient } from "matrix-js-sdk/src/client";
import { GroupCall } from "matrix-js-sdk/src/webrtc/groupCall";
import { CallFeed, CallFeedEvent } from "matrix-js-sdk/src/webrtc/callFeed";
import { logger } from "matrix-js-sdk/src/logger";
import { PlayClipFunction, PTTClipID } from "../sound/usePttSounds";
2022-05-06 10:32:09 +00:00
// Works out who the active speaker should be given what feeds are active and
// the power level of each user.
function getActiveSpeakerFeed(
feeds: CallFeed[],
groupCall: GroupCall
): CallFeed {
const activeSpeakerFeeds = feeds.filter((f) => !f.isAudioMuted());
let activeSpeakerFeed;
let highestPowerLevel;
for (const feed of activeSpeakerFeeds) {
const member = groupCall.room.getMember(feed.userId);
if (
highestPowerLevel === undefined ||
member.powerLevel > highestPowerLevel
) {
highestPowerLevel = member.powerLevel;
activeSpeakerFeed = feed;
}
}
return activeSpeakerFeed;
}
2022-05-06 10:32:09 +00:00
export interface PTTState {
pttButtonHeld: boolean;
isAdmin: boolean;
talkOverEnabled: boolean;
setTalkOverEnabled: (boolean) => void;
activeSpeakerUserId: string;
startTalking: () => void;
stopTalking: () => void;
transmitBlocked: boolean;
2022-05-06 10:32:09 +00:00
}
2022-04-29 00:44:50 +00:00
2022-05-06 10:32:09 +00:00
export const usePTT = (
client: MatrixClient,
groupCall: GroupCall,
userMediaFeeds: CallFeed[],
playClip: PlayClipFunction
2022-05-06 10:32:09 +00:00
): PTTState => {
// Used to serialise all the mute calls so they don't race. It has
// its own state as its always set separately from anything else.
2022-05-13 19:39:21 +00:00
const [mutePromise, setMutePromise] = useState(
Promise.resolve<boolean | void>(false)
);
// Wrapper to serialise all the mute operations on the promise
const setMicMuteWrapper = useCallback(
2022-05-13 19:39:21 +00:00
(muted: boolean) => {
setMutePromise(
mutePromise.then(() => {
2022-05-13 19:39:21 +00:00
return groupCall.setMicrophoneMuted(muted).catch((e) => {
logger.error("Failed to unmute microphone", e);
});
})
);
},
[groupCall, mutePromise]
);
2022-04-29 00:44:50 +00:00
const [
2022-05-06 20:27:07 +00:00
{
pttButtonHeld,
isAdmin,
talkOverEnabled,
activeSpeakerUserId,
transmitBlocked,
2022-05-06 20:27:07 +00:00
},
2022-04-29 00:44:50 +00:00
setState,
] = useState(() => {
const roomMember = groupCall.room.getMember(client.getUserId());
const activeSpeakerFeed = getActiveSpeakerFeed(userMediaFeeds, groupCall);
2022-04-29 00:44:50 +00:00
return {
isAdmin: roomMember.powerLevel >= 100,
talkOverEnabled: false,
pttButtonHeld: false,
activeSpeakerUserId: activeSpeakerFeed ? activeSpeakerFeed.userId : null,
transmitBlocked: false,
2022-04-29 00:44:50 +00:00
};
});
const onMuteStateChanged = useCallback(() => {
const activeSpeakerFeed = getActiveSpeakerFeed(userMediaFeeds, groupCall);
let blocked = false;
if (activeSpeakerUserId === null && activeSpeakerFeed.userId !== null) {
if (activeSpeakerFeed.userId === client.getUserId()) {
playClip(PTTClipID.START_TALKING_LOCAL);
} else {
playClip(PTTClipID.START_TALKING_REMOTE);
}
} else if (
pttButtonHeld &&
activeSpeakerUserId === client.getUserId() &&
activeSpeakerFeed?.userId !== client.getUserId()
) {
2022-05-13 17:09:45 +00:00
// We were talking but we've been cut off: mute our own mic
// (this is the easier way of cutting other speakers off if an
// admin barges in: we could also mute the non-admin speaker
// on all receivers, but we'd have to make sure we unmuted them
// correctly.)
setMicMuteWrapper(true);
blocked = true;
playClip(PTTClipID.BLOCKED);
}
setState((prevState) => {
return {
2022-04-29 00:44:50 +00:00
...prevState,
activeSpeakerUserId: activeSpeakerFeed
? activeSpeakerFeed.userId
: null,
transmitBlocked: blocked,
};
});
}, [
playClip,
groupCall,
pttButtonHeld,
activeSpeakerUserId,
client,
userMediaFeeds,
setMicMuteWrapper,
]);
2022-04-29 00:44:50 +00:00
useEffect(() => {
2022-04-29 00:44:50 +00:00
for (const callFeed of userMediaFeeds) {
callFeed.addListener(CallFeedEvent.MuteStateChanged, onMuteStateChanged);
2022-04-29 00:44:50 +00:00
}
const activeSpeakerFeed = getActiveSpeakerFeed(userMediaFeeds, groupCall);
2022-04-29 00:44:50 +00:00
setState((prevState) => ({
...prevState,
activeSpeakerUserId: activeSpeakerFeed ? activeSpeakerFeed.userId : null,
}));
return () => {
for (const callFeed of userMediaFeeds) {
callFeed.removeListener(
CallFeedEvent.MuteStateChanged,
onMuteStateChanged
);
2022-04-29 00:44:50 +00:00
}
};
}, [userMediaFeeds, onMuteStateChanged, groupCall]);
2022-04-29 00:44:50 +00:00
const startTalking = useCallback(async () => {
if (pttButtonHeld) return;
let blocked = false;
if (activeSpeakerUserId && !(isAdmin && talkOverEnabled)) {
playClip(PTTClipID.BLOCKED);
blocked = true;
}
// setstate before doing the async call to mute / unmute the mic
setState((prevState) => ({
...prevState,
pttButtonHeld: true,
transmitBlocked: blocked,
}));
if (!blocked && groupCall.isMicrophoneMuted()) {
setMicMuteWrapper(false);
}
}, [
pttButtonHeld,
groupCall,
activeSpeakerUserId,
isAdmin,
talkOverEnabled,
setState,
playClip,
setMicMuteWrapper,
]);
const stopTalking = useCallback(async () => {
setState((prevState) => ({
...prevState,
pttButtonHeld: false,
transmitBlocked: false,
}));
setMicMuteWrapper(true);
}, [setMicMuteWrapper]);
2022-04-29 00:44:50 +00:00
useEffect(() => {
2022-05-06 10:32:09 +00:00
function onKeyDown(event: KeyboardEvent): void {
2022-04-29 00:44:50 +00:00
if (event.code === "Space") {
event.preventDefault();
if (pttButtonHeld) return;
startTalking();
2022-04-29 00:44:50 +00:00
}
}
2022-05-06 10:32:09 +00:00
function onKeyUp(event: KeyboardEvent): void {
2022-04-29 00:44:50 +00:00
if (event.code === "Space") {
event.preventDefault();
stopTalking();
2022-04-29 00:44:50 +00:00
}
}
2022-05-06 10:32:09 +00:00
function onBlur(): void {
2022-04-29 00:44:50 +00:00
// TODO: We will need to disable this for a global PTT hotkey to work
if (!groupCall.isMicrophoneMuted()) {
setMicMuteWrapper(true);
2022-04-29 00:44:50 +00:00
}
setState((prevState) => ({ ...prevState, pttButtonHeld: false }));
}
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
window.addEventListener("blur", onBlur);
2022-04-29 00:44:50 +00:00
return () => {
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener("keyup", onKeyUp);
window.removeEventListener("blur", onBlur);
};
2022-05-06 20:34:58 +00:00
}, [
groupCall,
startTalking,
stopTalking,
activeSpeakerUserId,
isAdmin,
talkOverEnabled,
pttButtonHeld,
setMicMuteWrapper,
2022-05-06 20:34:58 +00:00
]);
2022-04-29 00:44:50 +00:00
const setTalkOverEnabled = useCallback((talkOverEnabled) => {
setState((prevState) => ({
...prevState,
talkOverEnabled,
}));
}, []);
return {
pttButtonHeld,
isAdmin,
talkOverEnabled,
setTalkOverEnabled,
activeSpeakerUserId,
startTalking,
stopTalking,
transmitBlocked,
2022-04-29 00:44:50 +00:00
};
2022-05-06 10:32:09 +00:00
};