Merge branch 'main' of github.com:daily-demos/examples into fitness-demo

This commit is contained in:
harshithpabbati 2022-01-19 12:30:39 +05:30
commit 7b5235e452
4 changed files with 64 additions and 71 deletions

View File

@ -1,5 +1,7 @@
# Active Speaker
![Active Speaker](./image.png)
### Live example
**[See it in action here ➡️](https://custom-active-speaker.vercel.app)**

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

After

Width:  |  Height:  |  Size: 584 KiB

View File

@ -12,7 +12,6 @@ import { useParticipants } from '@custom/shared/contexts/ParticipantsProvider';
import { useTracks } from '@custom/shared/contexts/TracksProvider';
import { useUIState } from '@custom/shared/contexts/UIStateProvider';
import { isLocalId } from '@custom/shared/contexts/participantsState';
import { useActiveSpeaker } from '@custom/shared/hooks/useActiveSpeaker';
import { useCamSubscriptions } from '@custom/shared/hooks/useCamSubscriptions';
import { useResize } from '@custom/shared/hooks/useResize';
import { useScrollbarWidth } from '@custom/shared/hooks/useScrollbarWidth';
@ -40,18 +39,21 @@ export const ParticipantBar = ({
width,
}) => {
const { networkState } = useCallState();
const { currentSpeaker, screens, swapParticipantPosition } =
useParticipants();
const {
currentSpeaker,
screens,
swapParticipantPosition,
} = useParticipants();
const { maxCamSubscriptions } = useTracks();
const { pinnedId, showParticipantsBar } = useUIState();
const itemHeight = useMemo(
() => width / aspectRatio + GAP,
[aspectRatio, width]
);
const paddingTop = useMemo(
() => itemHeight * fixed.length,
[fixed, itemHeight]
);
const itemHeight = useMemo(() => width / aspectRatio + GAP, [
aspectRatio,
width,
]);
const paddingTop = useMemo(() => itemHeight * fixed.length, [
fixed,
itemHeight,
]);
const scrollTop = useRef(0);
const spaceBefore = useRef(null);
const spaceAfter = useRef(null);
@ -61,14 +63,13 @@ export const ParticipantBar = ({
const [isSidebarScrollable, setIsSidebarScrollable] = useState(false);
const blockScrolling = useBlockScrolling(scrollRef);
const scrollbarWidth = useScrollbarWidth();
const activeSpeakerId = useActiveSpeaker();
const hasScreenshares = useMemo(() => screens.length > 0, [screens]);
const othersCount = useMemo(() => others.length, [others]);
const visibleOthers = useMemo(
() => others.slice(range[0], range[1]),
[others, range]
);
const visibleOthers = useMemo(() => others.slice(range[0], range[1]), [
others,
range,
]);
const currentSpeakerId = useMemo(() => currentSpeaker?.id, [currentSpeaker]);
/**
* Store other ids as string to reduce amount of running useEffects below.
@ -96,7 +97,7 @@ export const ParticipantBar = ({
if (!showParticipantsBar) {
setCamSubscriptions({
subscribedIds: [
currentSpeaker?.id,
currentSpeakerId,
pinnedId,
...fixedRemote.map((p) => p.id),
],
@ -117,8 +118,8 @@ export const ParticipantBar = ({
const min = Math.max(0, r[0] - buffer);
const max = Math.min(otherIds.length, r[1] + buffer);
const ids = otherIds.slice(min, max);
if (!ids.includes(currentSpeaker?.id) && !isLocalId(currentSpeaker?.id)) {
ids.push(currentSpeaker?.id);
if (!ids.includes(currentSpeakerId) && !isLocalId(currentSpeakerId)) {
ids.push(currentSpeakerId);
}
// Calculate paused participant ids by determining their tile position
const subscribedIds = [...fixedRemote.map((p) => p.id), ...ids];
@ -126,7 +127,7 @@ export const ParticipantBar = ({
// ignore unrendered ids, they'll be unsubscribed instead
if (!ids.includes(id)) return false;
// ignore current speaker, it should never be paused
if (id === currentSpeaker?.id) return false;
if (id === currentSpeakerId) return false;
const top = i * itemHeight;
const fixedHeight = fixed.length * itemHeight;
const visibleScrollHeight = scrollEl.clientHeight - fixedHeight;
@ -143,7 +144,7 @@ export const ParticipantBar = ({
});
},
[
currentSpeaker?.id,
currentSpeakerId,
fixed,
itemHeight,
maxCamSubscriptions,
@ -239,26 +240,27 @@ export const ParticipantBar = ({
const maybePromoteActiveSpeaker = () => {
const fixedOther = fixed.find((f) => !f.isLocal);
// Ignore when speaker is already at first position or component unmounted
if (!fixedOther || fixedOther?.id === activeSpeakerId || !scrollEl)
if (!fixedOther || fixedOther?.id === activeSpeakerId || !scrollEl) {
return false;
}
// Active speaker not rendered at all, promote immediately
if (
visibleOthers.every((p) => p.id !== activeSpeakerId) &&
!isLocalId(activeSpeakerId)
visibleOthers.every((p) => p.id !== currentSpeakerId) &&
!isLocalId(currentSpeakerId)
) {
swapParticipantPosition(fixedOther.id, activeSpeakerId);
swapParticipantPosition(fixedOther.id, currentSpeakerId);
return false;
}
const activeTile = othersRef.current?.querySelector(
`[id="${activeSpeakerId}"]`
`[id="${currentSpeakerId}"]`
);
// Ignore when active speaker is not within "others"
if (!activeTile) return false;
// Ignore when active speaker is already pinned
if (activeSpeakerId === pinnedId) return false;
if (currentSpeakerId === pinnedId) return false;
const { height: tileHeight } = activeTile.getBoundingClientRect();
const othersVisibleHeight =
@ -270,10 +272,11 @@ export const ParticipantBar = ({
if (
scrolledOffsetTop + tileHeight / 2 < othersVisibleHeight &&
scrolledOffsetTop > -tileHeight / 2
)
) {
return false;
}
return swapParticipantPosition(fixedOther.id, activeSpeakerId);
return swapParticipantPosition(fixedOther.id, currentSpeakerId);
};
maybePromoteActiveSpeaker();
const throttledHandler = debounce(maybePromoteActiveSpeaker, 100);
@ -283,7 +286,7 @@ export const ParticipantBar = ({
scrollEl?.removeEventListener('scroll', throttledHandler);
};
}, [
activeSpeakerId,
currentSpeakerId,
fixed,
hasScreenshares,
pinnedId,

View File

@ -9,16 +9,8 @@ import React, {
} from 'react';
import {
useUIState,
VIEW_MODE_SPEAKER,
} from '@custom/shared/contexts/UIStateProvider';
import PropTypes from 'prop-types';
import {
VIDEO_QUALITY_AUTO,
VIDEO_QUALITY_BANDWIDTH_SAVER,
VIDEO_QUALITY_LOW,
VIDEO_QUALITY_VERY_LOW,
} from '../constants';
import { sortByKey } from '../lib/sortByKey';
import { useCallState } from './CallProvider';
@ -37,14 +29,16 @@ import {
export const ParticipantsContext = createContext();
export const ParticipantsProvider = ({ children }) => {
const { callObject, videoQuality, networkState, broadcast, broadcastRole, } = useCallState();
const { callObject, videoQuality, networkState, broadcast } = useCallState();
const [state, dispatch] = useReducer(
participantsReducer,
initialParticipantsState
);
const { isMobile, viewMode, pinnedId } = useUIState();
const [participantMarkedForRemoval, setParticipantMarkedForRemoval] =
useState(null);
const { viewMode } = useUIState();
const [
participantMarkedForRemoval,
setParticipantMarkedForRemoval,
] = useState(null);
/**
* ALL participants (incl. shared screens) in a convenient array
@ -100,31 +94,37 @@ export const ParticipantsProvider = ({ children }) => {
[allParticipants]
);
const isOwner = useMemo(() => !!localParticipant?.isOwner, [
localParticipant,
]);
/**
* The participant who should be rendered prominently right now
*/
const currentSpeaker = useMemo(() => {
/**
* Ensure activeParticipant is still present in the call.
* If the activeParticipant is still in the call, return the activeParticipant.
* The activeParticipant only updates to a new active participant so
* if everyone else is muted when AP leaves, the value will be stale.
*/
const isPresent = participants.some((p) => p?.id === activeParticipant?.id);
const pinned = participants.find((p) => p?.id === pinnedId);
if (isPresent) {
return activeParticipant;
}
if (pinned) return pinned;
const displayableParticipants = participants.filter((p) =>
isMobile ? !p?.isLocal && !p?.isScreenshare : !p?.isLocal
);
/**
* If the activeParticipant has left, calculate the remaining displayable participants
*/
const displayableParticipants = participants.filter((p) => !p?.isLocal);
/**
* If nobody ever unmuted, return the first participant with a camera on
* Or, if all cams are off, return the first remote participant
*/
if (
!isPresent &&
displayableParticipants.length > 0 &&
displayableParticipants.every((p) => p.isMicMuted && !p.lastActiveDate)
) {
// Return first cam on participant in case everybody is muted and nobody ever talked
// or first remote participant, in case everybody's cam is muted, too.
return (
displayableParticipants.find((p) => !p.isCamMuted) ??
displayableParticipants?.[0]
@ -135,17 +135,10 @@ export const ParticipantsProvider = ({ children }) => {
.sort((a, b) => sortByKey(a, b, 'lastActiveDate'))
.reverse();
const fallback = broadcastRole === 'attendee' ? null : localParticipant;
const lastActiveSpeaker = sorted?.[0];
return isPresent ? activeParticipant : sorted?.[0] ?? fallback;
}, [
activeParticipant,
broadcastRole,
isMobile,
localParticipant,
participants,
pinnedId,
]);
return lastActiveSpeaker || localParticipant;
}, [activeParticipant, localParticipant, participants]);
/**
* Screen shares
@ -165,12 +158,6 @@ export const ParticipantsProvider = ({ children }) => {
callObject.setUserName(name);
};
const isOwner = useMemo(
() => !!localParticipant?.isOwner,
[localParticipant]
);
const [muteNewParticipants, setMuteNewParticipants] = useState(false);
const muteAll = useCallback(
@ -312,11 +299,12 @@ export const ParticipantsProvider = ({ children }) => {
* Our UX doesn't ever highlight the local user as the active speaker.
*/
const localId = callObject.participants().local.session_id;
if (localId === activeSpeaker?.peerId) return;
const activeSpeakerId = activeSpeaker?.peerId;
if (localId === activeSpeakerId) return;
dispatch({
type: ACTIVE_SPEAKER,
id: activeSpeaker?.peerId,
id: activeSpeakerId,
});
};
callObject.on('active-speaker-change', handleActiveSpeakerChange);