Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(audio-translation): per-participant translation indicators (#17619)
Jaya Allamsetty00b5cbab3870
diff --git a/config.js b/config.jsindex 64c1dcb81a..d67721bb2f 100644--- a/config.js+++ b/config.js@@ -240,6 +240,11 @@ var config = {// // Defaults to 0.15. Ignored on iOS, where the original is muted instead because the// // element volume cannot be lowered there.// duckedVolume: 0.15,+ //+ // // Whether to process the bridge's translated-source sending notifications, which drive the+ // // per-participant "receiving translated audio" indicator. Off by default until the bridge+ // // emits stop notifications as well as start ones.+ // enableSendingChangeEvents: false,// },// Noise suppression configuration. By default rnnoise is used. Optionally Krispdiff --git a/lang/main.json b/lang/main.jsonindex ca4a7420ed..810121fb99 100644--- a/lang/main.json+++ b/lang/main.json@@ -48,7 +48,8 @@"errorGeneric": "Couldn't enable audio translation. Please try again.","errorLimitReached": "Couldn't translate everyone at once. Turn on translation for individual participants instead.","errorRoomDisabled": "Audio translation is turned off for this meeting. Enable it in Moderator settings.",- "errorSpeakerUnavailable": "Can't translate this participant — they're no longer in the meeting."+ "errorSpeakerUnavailable": "Can't translate this participant — they're no longer in the meeting.",+ "labelTooltip": "Translation in progress"},"bandwidthSettings": {"assumedBandwidthBps": "e.g. 10000000 for 10 Mbps",@@ -1652,10 +1653,13 @@"mute": "Participant is muted","muted": "Muted","pinToStage": "Pin to stage",+ "receivingTranslatedAudio": "You're receiving translated audio","remoteControl": "Start / Stop remote control","screenSharing": "Participant is sharing their screen","show": "Show on stage","showSelfView": "Show self view",+ "translationEnabledForYou": "Translation enabled for you",+ "translationOnAndReceiving": "Translation on · receiving","unpinFromStage": "Unpin","verify": "Verify participant","videoMuted": "Camera disabled",diff --git a/react/features/audio-translation/actionTypes.ts b/react/features/audio-translation/actionTypes.tsindex 94b64a1975..3e235be86b 100644--- a/react/features/audio-translation/actionTypes.ts+++ b/react/features/audio-translation/actionTypes.ts@@ -4,6 +4,12 @@*/export const CLEAR_AUDIO_TRANSLATION = 'CLEAR_AUDIO_TRANSLATION';+/**+ * The type of (redux) action which clears the set of translated sources the bridge is currently+ * forwarding to us, e.g. when the conference is left.+ */+export const CLEAR_RECEIVING_TRANSLATED_SOURCES = 'CLEAR_RECEIVING_TRANSLATED_SOURCES';+/*** The type of (redux) action which sets the default AI audio translation target* language for every speaker, or null when translation is turned off.@@ -16,3 +22,15 @@ export const SET_AUDIO_TRANSLATION_LANGUAGE = 'SET_AUDIO_TRANSLATION_LANGUAGE';* that participant.*/export const SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE = 'SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE';++/**+ * The type of (redux) action which sets the list of remote participants currently translating the local+ * participant's audio (i.e. who to show the "translation enabled" badge on).+ */+export const SET_TRANSLATION_LISTENERS = 'SET_TRANSLATION_LISTENERS';++/**+ * The type of (redux) action which records that the bridge started or stopped forwarding a translated+ * source to the local endpoint (i.e. whether we are hearing that source translated).+ */+export const UPDATE_TRANSLATED_SOURCE_SENDING = 'UPDATE_TRANSLATED_SOURCE_SENDING';diff --git a/react/features/audio-translation/actions.ts b/react/features/audio-translation/actions.tsindex e0dd9ac7af..e30fcff9bb 100644--- a/react/features/audio-translation/actions.ts+++ b/react/features/audio-translation/actions.ts@@ -1,7 +1,10 @@import {CLEAR_AUDIO_TRANSLATION,+ CLEAR_RECEIVING_TRANSLATED_SOURCES,SET_AUDIO_TRANSLATION_LANGUAGE,- SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE+ SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE,+ SET_TRANSLATION_LISTENERS,+ UPDATE_TRANSLATED_SOURCE_SENDING} from './actionTypes';/**@@ -18,6 +21,20 @@ export function clearAudioTranslation() {};}+/**+ * Clears the set of translated sources the bridge is currently forwarding to us. Used when the+ * conference is left so stale received-translation state does not leak into the next conference.+ *+ * @returns {{+ * type: string+ * }}+ */+export function clearReceivingTranslatedSources() {+ return {+ type: CLEAR_RECEIVING_TRANSLATED_SOURCES+ };+}+/*** Sets the default target language for AI audio translation. The bridge is asked* to translate every remote speaker into this language and the local endpoint@@ -58,3 +75,44 @@ export function setParticipantAudioTranslationLanguage(participantId: string, lalanguage};}++/**+ * Sets the endpoint ids of the remote participants currently translating the local participant's audio,+ * as pushed by the audio-translation component. Drives the per-participant "translation enabled" badge.+ *+ * @param {Array<string>} ids - The endpoint ids translating the local participant.+ * @returns {{+ * ids: Array<string>,+ * type: string+ * }}+ */+export function setTranslationListeners(ids: string[]) {+ return {+ type: SET_TRANSLATION_LISTENERS,+ ids+ };+}++/**+ * Records whether the bridge is currently forwarding a translated source to the local endpoint. A translated+ * source follows the {@code <endpointId>-a<idx>.<lang>} convention. The timestamp is the RTP timestamp from the+ * event (48 kHz, wraps) and is kept for completeness only — the boolean state is last-write-wins.+ *+ * @param {string} sourceName - The translated source name.+ * @param {boolean} sending - Whether the bridge started (true) or stopped (false) forwarding the source.+ * @param {number} timestamp - The RTP timestamp carried by the event.+ * @returns {{+ * sending: boolean,+ * sourceName: string,+ * timestamp: number,+ * type: string+ * }}+ */+export function updateTranslatedSourceSending(sourceName: string, sending: boolean, timestamp: number) {+ return {+ type: UPDATE_TRANSLATED_SOURCE_SENDING,+ sending,+ sourceName,+ timestamp+ };+}diff --git a/react/features/audio-translation/components/web/TranslationLabel.tsx b/react/features/audio-translation/components/web/TranslationLabel.tsxnew file mode 100644index 0000000000..9acb47d310--- /dev/null+++ b/react/features/audio-translation/components/web/TranslationLabel.tsx@@ -0,0 +1,47 @@+import React from 'react';+import { useTranslation } from 'react-i18next';+import { useSelector } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IconTranslate } from '../../../base/icons/svg';+import Label from '../../../base/label/components/web/Label';+import Tooltip from '../../../base/tooltip/components/Tooltip';+import { isAudioTranslationActiveInMeeting } from '../../functions';++const useStyles = makeStyles()(theme => {+ return {+ translation: {+ background: theme.palette.action01+ }+ };+});++/**+ * Conference-header label shown while audio translation is active in the meeting.+ *+ * @returns {ReactElement|null}+ */+const TranslationLabel = () => {+ const { classes: styles } = useStyles();+ const { t } = useTranslation();+ const active = useSelector(isAudioTranslationActiveInMeeting);++ if (!active) {+ return null;+ }++ const content = t('audioTranslation.labelTooltip');++ return (+ <Tooltip+ content = { content }+ position = { 'bottom' }>+ <Label+ accessibilityText = { content }+ className = { styles.translation }+ icon = { IconTranslate } />+ </Tooltip>+ );+};++export default TranslationLabel;diff --git a/react/features/audio-translation/constants.ts b/react/features/audio-translation/constants.tsindex 2c0e50c4f9..3cc1aa3b46 100644--- a/react/features/audio-translation/constants.ts+++ b/react/features/audio-translation/constants.ts@@ -26,3 +26,30 @@ export const DEFAULT_ORIGINAL_VOLUME = 1;* Volume (0..1) a speaker's original audio is ducked to while its translation plays.*/export const DUCKED_ORIGINAL_VOLUME = 0.15;++/**+ * The per-participant audio-translation status the thumbnail indicator renders, combining whether translation+ * is enabled for the local user and whether translated audio is actually being received.+ */+export enum TranslationTreatment {++ /**+ * Translation is enabled for the local user AND translated audio is being received.+ */+ BOTH = 'both',++ /**+ * Translation is enabled for the local user but no translated audio is being received yet.+ */+ ENABLED = 'enabled',++ /**+ * Neither enabled nor receiving — the indicator renders nothing.+ */+ NONE = 'none',++ /**+ * Translated audio is being received without translation having been explicitly enabled.+ */+ RECEIVING = 'receiving'+}diff --git a/react/features/audio-translation/functions.ts b/react/features/audio-translation/functions.tsindex 426434826e..52e215e94a 100644--- a/react/features/audio-translation/functions.ts+++ b/react/features/audio-translation/functions.ts@@ -4,6 +4,8 @@ import { isJwtFeatureEnabled } from '../base/jwt/functions';import { isLocalParticipantModerator } from '../base/participants/functions';import { ITrack } from '../base/tracks/types';+import { TranslationTreatment } from './constants';+/*** Whether audio translation is enabled for the room. Driven by the {@code audioTranslation} RoomMetadata flag,* which a moderator can toggle; absent or any value other than an explicit {@code false} means enabled.@@ -15,6 +17,88 @@ export function isAudioTranslationRoomEnabled(state: IReduxState): boolean {return state['features/base/conference'].metadata?.audioTranslation?.enabled !== false;}+/**+ * Whether the given participant is currently translating the local participant's audio, per the directed+ * {@code translationListeners} list pushed by the audio-translation component.+ *+ * @param {IReduxState} state - The redux state.+ * @param {string} participantId - The participant (endpoint) id to check.+ * @returns {boolean}+ */+export function isParticipantAudioTranslationActive(state: IReduxState, participantId: string): boolean {+ return state['features/audio-translation'].translationListeners.includes(participantId);+}++/**+ * The owner endpoint id encoded in a translated source name — the substring before the first {@code -}.+ * Translated sources follow the {@code <endpointId>-a<idx>.<lang>} convention (endpoint ids are dash/dot-free).+ * Returns an empty string for a source without a dash.+ *+ * @param {string} sourceName - The translated source name.+ * @returns {string}+ */+export function getSourceOwnerEndpointId(sourceName: string): string {+ const dashIndex = sourceName.indexOf('-');++ return dashIndex === -1 ? '' : sourceName.substring(0, dashIndex);+}++/**+ * Whether the bridge is currently forwarding any translated audio owned by the given participant to us (i.e. we+ * are hearing that participant translated), per the {@code receivingSources} set.+ *+ * @param {IReduxState} state - The redux state.+ * @param {string} participantId - The participant (endpoint) id to check.+ * @returns {boolean}+ */+export function isReceivingTranslationFrom(state: IReduxState, participantId: string): boolean {+ return state['features/audio-translation'].receivingSources+ .some(sourceName => getSourceOwnerEndpointId(sourceName) === participantId);+}++/**+ * The audio-translation status treatment for a participant, combining whether translation is enabled for the+ * local user ({@link isParticipantAudioTranslationActive}) and whether translated audio is being received+ * ({@link isReceivingTranslationFrom}).+ *+ * @param {IReduxState} state - The redux state.+ * @param {string} participantId - The participant (endpoint) id to check.+ * @returns {TranslationTreatment}+ */+export function getTranslationTreatment(state: IReduxState, participantId: string): TranslationTreatment {+ const enabled = isParticipantAudioTranslationActive(state, participantId);+ const receiving = isReceivingTranslationFrom(state, participantId);++ if (enabled && receiving) {+ return TranslationTreatment.BOTH;+ }+ if (enabled) {+ return TranslationTreatment.ENABLED;+ }+ if (receiving) {+ return TranslationTreatment.RECEIVING;+ }++ return TranslationTreatment.NONE;+}++/**+ * Whether audio translation is currently active anywhere in the meeting: a remote participant is translating+ * the local user, translated audio is being received, or the local user has translation on.+ *+ * @param {IReduxState} state - The redux state.+ * @returns {boolean}+ */+export function isAudioTranslationActiveInMeeting(state: IReduxState): boolean {+ const { language, participantLanguages, receivingSources, translationListeners }+ = state['features/audio-translation'];++ return translationListeners.length > 0+ || receivingSources.length > 0+ || Boolean(language)+ || Object.values(participantLanguages).some(lang => lang !== null);+}+/*** Whether the local user may manage audio translation for the room (i.e. toggle the room-wide flag). Mirrors the* prosody {@code live-translation} permission: the token's explicit value wins, otherwise moderators have it.diff --git a/react/features/audio-translation/middleware.ts b/react/features/audio-translation/middleware.tsindex 7acc37a493..f8aabfffd3 100644--- a/react/features/audio-translation/middleware.ts+++ b/react/features/audio-translation/middleware.ts@@ -1,4 +1,5 @@import { JitsiAudioTranslationErrors, JitsiConferenceEvents } from '../base/lib-jitsi-meet';+import { getLocalParticipant } from '../base/participants/functions';import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';import StateListenerRegistry from '../base/redux/StateListenerRegistry';import { showErrorNotification, showNotification } from '../notifications/actions';@@ -9,8 +10,14 @@ import {SET_AUDIO_TRANSLATION_LANGUAGE,SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE} from './actionTypes';-import { clearAudioTranslation, setParticipantAudioTranslationLanguage } from './actions';-import { isAudioTranslationRoomEnabled } from './functions';+import {+ clearAudioTranslation,+ clearReceivingTranslatedSources,+ setParticipantAudioTranslationLanguage,+ setTranslationListeners,+ updateTranslatedSourceSending+} from './actions';+import { getSourceOwnerEndpointId, isAudioTranslationRoomEnabled } from './functions';import logger from './logger';/**@@ -111,6 +118,45 @@ StateListenerRegistry.register(});});+/**+ * Ingests the two per-participant translation signals from the conference: which translated sources the bridge+ * is forwarding to us (receiving), and which remote participants are translating us (enabled). Both are cleared+ * when the conference goes away.+ */+StateListenerRegistry.register(+ state => state['features/base/conference'].conference,+ (conference, { dispatch, getState }, previousConference) => {+ if (previousConference) {+ dispatch(clearReceivingTranslatedSources());+ dispatch(setTranslationListeners([]));+ }++ if (!conference) {+ return;+ }++ conference.on(JitsiConferenceEvents.TRANSLATED_SOURCE_SENDING_CHANGED,+ ({ sending, sourceName, timestamp }: { sending: boolean; sourceName: string; timestamp: number; }) => {+ // The bridge currently emits only sending=true, which would leave the receiving state+ // stuck on; ignore the events unless explicitly enabled.+ if (!getState()['features/base/config'].audioTranslation?.enableSendingChangeEvents) {+ return;+ }++ // The bridge broadcasts sending changes to every endpoint, including the translated+ // participant itself; our own translated source is not audio we receive.+ if (getSourceOwnerEndpointId(sourceName) === getLocalParticipant(getState())?.id) {+ return;+ }+ dispatch(updateTranslatedSourceSending(sourceName, sending, timestamp));+ });++ conference.on(JitsiConferenceEvents.AUDIO_TRANSLATION_LISTENERS_CHANGED,+ (ids: string[]) => {+ dispatch(setTranslationListeners(ids));+ });+ });+/*** When a moderator disables audio translation for the room, clear the local user's active translation and notify* them. The room flag only blocks new requests on the bridge; it does not tear down active subscriptions. Clearingdiff --git a/react/features/audio-translation/reducer.ts b/react/features/audio-translation/reducer.tsindex 380920dabb..f2c2c164a3 100644--- a/react/features/audio-translation/reducer.ts+++ b/react/features/audio-translation/reducer.ts@@ -2,8 +2,11 @@ import ReducerRegistry from '../base/redux/ReducerRegistry';import {CLEAR_AUDIO_TRANSLATION,+ CLEAR_RECEIVING_TRANSLATED_SOURCES,SET_AUDIO_TRANSLATION_LANGUAGE,- SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE+ SET_PARTICIPANT_AUDIO_TRANSLATION_LANGUAGE,+ SET_TRANSLATION_LISTENERS,+ UPDATE_TRANSLATED_SOURCE_SENDING} from './actionTypes';/**@@ -21,11 +24,25 @@ export interface IAudioTranslationState {* participant). An entry present here takes precedence over {@link language}; an absent entry inherits it.*/participantLanguages: { [participantId: string]: string | null; };++ /**+ * Translated source names the bridge is currently forwarding to us (i.e. we are hearing them translated).+ * A source follows the {@code <endpointId>-a<idx>.<lang>} convention; membership is last-write-wins.+ */+ receivingSources: string[];++ /**+ * Endpoint ids of the remote participants currently translating the local participant's audio, pushed by+ * the audio-translation component. Drives the per-participant "translation enabled" badge.+ */+ translationListeners: string[];}const DEFAULT_STATE: IAudioTranslationState = {language: null,- participantLanguages: {}+ participantLanguages: {},+ receivingSources: [],+ translationListeners: []};ReducerRegistry.register<IAudioTranslationState>(@@ -34,6 +51,11 @@ ReducerRegistry.register<IAudioTranslationState>(switch (action.type) {case CLEAR_AUDIO_TRANSLATION:return DEFAULT_STATE;+ case CLEAR_RECEIVING_TRANSLATED_SOURCES:+ return {+ ...state,+ receivingSources: []+ };case SET_AUDIO_TRANSLATION_LANGUAGE:return {...state,@@ -47,6 +69,25 @@ ReducerRegistry.register<IAudioTranslationState>([action.participantId]: action.language}};+ case SET_TRANSLATION_LISTENERS:+ return {+ ...state,+ translationListeners: action.ids+ };+ case UPDATE_TRANSLATED_SOURCE_SENDING: {+ const has = state.receivingSources.includes(action.sourceName);++ if (action.sending === has) {+ return state;+ }++ return {+ ...state,+ receivingSources: action.sending+ ? [ ...state.receivingSources, action.sourceName ]+ : state.receivingSources.filter((source: string) => source !== action.sourceName)+ };+ }default:return state;}diff --git a/react/features/base/config/configType.ts b/react/features/base/config/configType.tsindex c6fd288774..f554631c80 100644--- a/react/features/base/config/configType.ts+++ b/react/features/base/config/configType.ts@@ -224,6 +224,7 @@ export interface IConfig {*/audioTranslation?: {duckedVolume?: number;+ enableSendingChangeEvents?: boolean;enabled?: boolean;};/**diff --git a/react/features/conference/components/web/ConferenceInfo.tsx b/react/features/conference/components/web/ConferenceInfo.tsxindex cd89587171..d8339ce2fe 100644--- a/react/features/conference/components/web/ConferenceInfo.tsx+++ b/react/features/conference/components/web/ConferenceInfo.tsx@@ -3,6 +3,7 @@ import React, { Component } from 'react';import { connect } from 'react-redux';import { IReduxState, IStore } from '../../../app/types';+import TranslationLabel from '../../../audio-translation/components/web/TranslationLabel';import { JitsiRecordingConstants } from '../../../base/lib-jitsi-meet';import E2EELabel from '../../../e2ee/components/E2EELabel';import HighlightButton from '../../../recording/components/Recording/web/HighlightButton';@@ -105,6 +106,7 @@ const COMPONENTS: Array<{<RecordingLabel mode = { JitsiRecordingConstants.mode.FILE } /><RecordingLabel mode = { JitsiRecordingConstants.mode.STREAM } /><TranscribingLabel />+ <TranslationLabel /></>),id: 'recording'diff --git a/react/features/filmstrip/components/web/StatusIndicators.tsx b/react/features/filmstrip/components/web/StatusIndicators.tsxindex 23196c7c38..d534499e07 100644--- a/react/features/filmstrip/components/web/StatusIndicators.tsx+++ b/react/features/filmstrip/components/web/StatusIndicators.tsx@@ -15,6 +15,7 @@ import { getIndicatorsTooltipPosition } from '../../functions.web';import AudioMutedIndicator from './AudioMutedIndicator';import ModeratorIndicator from './ModeratorIndicator';import ScreenShareIndicator from './ScreenShareIndicator';+import TranslationIndicator from './TranslationIndicator';/*** The type of the React {@code Component} props of {@link StatusIndicators}.@@ -36,10 +37,15 @@ interface IProps {*/_showScreenShareIndicator: Boolean;+ /**+ * Indicates if the translation indicator should be visible or not.+ */+ _showTranslationIndicator: Boolean;+/*** The ID of the participant for which the status bar is rendered.*/- participantID: String;+ participantID: string;/*** The type of thumbnail.@@ -64,6 +70,8 @@ class StatusIndicators extends Component<IProps> {_showAudioMutedIndicator,_showModeratorIndicator,_showScreenShareIndicator,+ _showTranslationIndicator,+ participantID,thumbnailType} = this.props;const tooltipPosition = getIndicatorsTooltipPosition(thumbnailType);@@ -72,6 +80,9 @@ class StatusIndicators extends Component<IProps> {<>{ _showAudioMutedIndicator && <AudioMutedIndicator tooltipPosition = { tooltipPosition } /> }{ _showModeratorIndicator && <ModeratorIndicator tooltipPosition = { tooltipPosition } />}+ { _showTranslationIndicator && <TranslationIndicator+ participantId = { participantID }+ tooltipPosition = { tooltipPosition } /> }{ _showScreenShareIndicator && <ScreenShareIndicator tooltipPosition = { tooltipPosition } /> }</>);@@ -87,11 +98,12 @@ class StatusIndicators extends Component<IProps> {* @returns {{* _showAudioMutedIndicator: boolean,* _showModeratorIndicator: boolean,- * _showScreenShareIndicator: boolean+ * _showScreenShareIndicator: boolean,+ * _showTranslationIndicator: boolean* }}*/function _mapStateToProps(state: IReduxState, ownProps: any) {- const { participantID, audio, moderator, screenshare } = ownProps;+ const { participantID, audio, moderator, screenshare, translation } = ownProps;// Only the local participant won't have id for the time when the conference is not yet joined.const participant = getParticipantByIdOrUndefined(state, participantID);@@ -116,7 +128,8 @@ function _mapStateToProps(state: IReduxState, ownProps: any) {_showAudioMutedIndicator: isAudioMuted && audio,_showModeratorIndicator:!disableModeratorIndicator && participant && participant.role === PARTICIPANT_ROLE.MODERATOR && moderator,- _showScreenShareIndicator: isScreenSharing && screenshare+ _showScreenShareIndicator: isScreenSharing && screenshare,+ _showTranslationIndicator: Boolean(translation)};}diff --git a/react/features/filmstrip/components/web/ThumbnailBottomIndicators.tsx b/react/features/filmstrip/components/web/ThumbnailBottomIndicators.tsxindex 48c1e26a15..7992f75f9a 100644--- a/react/features/filmstrip/components/web/ThumbnailBottomIndicators.tsx+++ b/react/features/filmstrip/components/web/ThumbnailBottomIndicators.tsx@@ -76,7 +76,8 @@ const ThumbnailBottomIndicators = ({moderator = { true }participantID = { participantId }screenshare = { isVirtualScreenshareParticipant }- thumbnailType = { thumbnailType } />+ thumbnailType = { thumbnailType }+ translation = { !local && !isVirtualScreenshareParticipant } />}{_showDisplayName && (diff --git a/react/features/filmstrip/components/web/TranslationIndicator.tsx b/react/features/filmstrip/components/web/TranslationIndicator.tsxnew file mode 100644index 0000000000..31227c5611--- /dev/null+++ b/react/features/filmstrip/components/web/TranslationIndicator.tsx@@ -0,0 +1,118 @@+import React from 'react';+import { connect } from 'react-redux';+import { makeStyles } from 'tss-react/mui';++import { IReduxState } from '../../../app/types';+import { TranslationTreatment } from '../../../audio-translation/constants';+import { getTranslationTreatment } from '../../../audio-translation/functions';+import { IconTranslate } from '../../../base/icons/svg';+import BaseIndicator from '../../../base/react/components/web/BaseIndicator';+import { TOOLTIP_POSITION } from '../../../base/ui/constants.any';++/**+ * The type of the React {@code Component} props of {@link TranslationIndicator}.+ */+interface IProps {++ /**+ * Which of the three treatments to render, or NONE to render nothing.+ */+ _treatment: TranslationTreatment;++ /**+ * The id of the participant this indicator is rendered for.+ */+ participantId: string;++ /**+ * From which side of the indicator the tooltip should appear from.+ */+ tooltipPosition: TOOLTIP_POSITION;+}++/**+ * Tooltip i18n key per rendered treatment.+ */+const TOOLTIP_KEYS: Record<TranslationTreatment, string> = {+ [TranslationTreatment.BOTH]: 'videothumbnail.translationOnAndReceiving',+ [TranslationTreatment.ENABLED]: 'videothumbnail.translationEnabledForYou',+ [TranslationTreatment.NONE]: '',+ [TranslationTreatment.RECEIVING]: 'videothumbnail.receivingTranslatedAudio'+};++const useStyles = makeStyles()(theme => {+ return {+ dot: {+ backgroundColor: theme.palette.icon01,+ border: `1px solid ${theme.palette.uiBackground}`,+ borderRadius: '50%',+ height: '5px',+ position: 'absolute',+ right: '-1px',+ top: '-1px',+ width: '5px'+ },+ filled: {+ backgroundColor: theme.palette.action01,+ borderRadius: '4px',+ boxSizing: 'border-box',+ display: 'inline-block',+ padding: '4px',+ position: 'relative'+ },+ outlined: {+ border: `1px solid ${theme.palette.action01}`,+ borderRadius: '4px',+ boxSizing: 'border-box',+ display: 'inline-block',+ padding: '3px'+ }+ };+});++/**+ * React {@code Component} showing a participant's audio-translation status as one of three treatments: outlined+ * (translation enabled for the local user), filled (receiving translated audio) or filled with a dot (both).+ * Renders nothing when neither applies.+ *+ * @param {IProps} props - The component's props.+ * @returns {ReactElement|null}+ */+const TranslationIndicator = ({ _treatment, tooltipPosition }: IProps) => {+ const { classes: styles, theme } = useStyles();++ if (_treatment === TranslationTreatment.NONE) {+ return null;+ }++ const outlined = _treatment === TranslationTreatment.ENABLED;++ return (+ <div className = { outlined ? styles.outlined : styles.filled }>+ <BaseIndicator+ icon = { IconTranslate }+ iconColor = { outlined ? theme.palette.action01 : theme.palette.icon01 }+ iconId = 'translation-active'+ iconSize = { 16 }+ id = 'translationActive'+ tooltipKey = { TOOLTIP_KEYS[_treatment] }+ tooltipPosition = { tooltipPosition } />+ { _treatment === TranslationTreatment.BOTH && <span className = { styles.dot } /> }+ </div>+ );+};++/**+ * Maps (parts of) the redux state to the component's props.+ *+ * @param {IReduxState} state - The redux state.+ * @param {Object} ownProps - The component's own props.+ * @returns {Object}+ */+function _mapStateToProps(state: IReduxState, ownProps: any) {+ return {+ _treatment: getTranslationTreatment(state, ownProps.participantId)+ };+}++export default connect(_mapStateToProps)(TranslationIndicator);diff --git a/resources/prosody-plugins/mod_audio_translation_component.lua b/resources/prosody-plugins/mod_audio_translation_component.luaindex 33aecc8a50..fd0ec65e71 100644--- a/resources/prosody-plugins/mod_audio_translation_component.lua+++ b/resources/prosody-plugins/mod_audio_translation_component.lua@@ -40,6 +40,17 @@-- module injects audioTranslationRequests into the metadata only for admin-- (jicofo) occupants, so regular clients never see it.--+-- ── Directed listeners push (component → each sender) ─────────────────────────────+-- Alongside the jicofo aggregate, each sender is told which receivers currently translate it.+-- An inverted map { [senderId] = set<receiverId> } is maintained in lockstep with the forward+-- subscription map (updated incrementally on every delta and on occupant-leave), and a directed+-- <translation-listeners xmlns='http://jitsi.org/jitmeet'> message (sorted JSON array) is sent to+-- each sender whose listener set changed, so a client badges the receivers translating the local+-- user. Only senders flagged dirty since the last publish are reconsidered, so the cost is+-- proportional to what changed rather than to room size. Gated exactly like the aggregate; an empty+-- array clears a sender whose last listener left. Handled in publish_listeners(), kept separate so+-- the jicofo-facing publish() is unchanged.+---- ── Enable-flag write gating ─────────────────────────────────────────────────-- The audioTranslation metadata key (which carries the room-level enable flag)-- is written through mod_room_metadata_component. This module hooks@@ -99,15 +110,68 @@ module:log('info', 'Starting audio_translation for %s (max_subscriptions=%s, deblocal main_muc_module;-- Returns (creating if needed) the per-room translation state:--- { receivers = { [receiverId] = { [senderId] = lang } }, last_published = <json|nil> }+-- { receivers = { [receiverId] = { [senderId] = lang } }, -- forward map (source of truth)+-- last_published = <json|nil>, -- jicofo aggregate dedup+-- listeners_by_sender = { [senderId] = { [receiverId] = true } }, -- inverted map, kept in lockstep+-- dirty_senders = { [senderId] = true }, -- senders changed since last publish+-- last_sent_listeners = { [senderId] = <json> } } -- directed-push dedup+-- receivers drives per-receiver atomic updates and the jicofo aggregate; listeners_by_sender is+-- maintained alongside it so the directed per-sender push costs work proportional to what changed.local function get_state(room)if not room._audio_translation then- room._audio_translation = { receivers = {} };+ room._audio_translation = {+ receivers = {};+ listeners_by_sender = {};+ dirty_senders = {};+ last_sent_listeners = {};+ };endreturn room._audio_translation;end+-- Flags a sender for reconsideration on the next listeners publish.+local function mark_sender_dirty(state, sender_id)+ state.dirty_senders[sender_id] = true;+end++-- Records that receiver_id now translates sender_id in the inverted map, flagging the sender dirty.+local function add_listener(state, sender_id, receiver_id)+ local set = state.listeners_by_sender[sender_id];++ if not set then+ set = {};+ state.listeners_by_sender[sender_id] = set;+ end+ set[receiver_id] = true;+ mark_sender_dirty(state, sender_id);+end++-- Records that receiver_id no longer translates sender_id, dropping the set once it empties and+-- flagging the sender dirty so the change is pushed (an empty set clears the sender).+local function remove_listener(state, sender_id, receiver_id)+ local set = state.listeners_by_sender[sender_id];++ if set then+ set[receiver_id] = nil;+ if next(set) == nil then+ state.listeners_by_sender[sender_id] = nil;+ end+ end+ mark_sender_dirty(state, sender_id);+end++-- Flags every currently-tracked sender dirty. Used when room-wide gating (the enable flag) flips,+-- which changes every sender's pushed list at once with no per-sender delta to key off.+local function mark_all_senders_dirty(state)+ for sender_id in pairs(state.listeners_by_sender) do+ state.dirty_senders[sender_id] = true;+ end+ for sender_id in pairs(state.last_sent_listeners) do+ state.dirty_senders[sender_id] = true;+ end+end+-- The endpoint id of an occupant is the resource part of its in-room nick.local function endpoint_id(occupant)return jid_resource(occupant.nick);@@ -199,6 +263,20 @@ local function apply_delta(room, receiver_id, delta)state.receivers[receiver_id] = next_map;+ -- Update the inverted map in lockstep, now that the delta has fully validated (so a rejected+ -- delta never mutates it). Only membership changes move listeners; a language-only change+ -- (sender present before and after) is not a listener change and leaves the sender untouched.+ for sender_id in pairs(current) do+ if not next_map[sender_id] then+ remove_listener(state, sender_id, receiver_id);+ end+ end+ for sender_id in pairs(next_map) do+ if not current[sender_id] then+ add_listener(state, sender_id, receiver_id);+ end+ end+return true;end@@ -283,6 +361,64 @@ local function publish(room)main_muc_module:fire_event('room-metadata-changed', { room = room; });end+-- Pushes each dirty sender the sorted receiver ids currently translating it, as a directed+-- <translation-listeners> message, then clears the dirty set. Reads the incrementally-maintained+-- inverted map (listeners_by_sender), so the cost is proportional to what changed, not room size.+-- Kept separate from publish() so the jicofo-facing aggregate path stays untouched. Gated like the+-- aggregate: while disabled/vetoed every dirty sender resolves to an empty list. Change-detected per+-- sender against last_sent_listeners; an empty array is sent (then the tracker entry dropped) to+-- clear a sender whose last listener left.+local function publish_listeners(room)+ if not room._audio_translation or not main_muc_module then+ return;+ end++ local state = room._audio_translation;+ local dirty = state.dirty_senders;++ if not dirty or next(dirty) == nil then+ return;+ end+ state.dirty_senders = {};++ local allow_publish = main_muc_module:fire_event('jitsi-audio-translation-allow-publish', { room = room; }) ~= false;+ local enabled = allow_publish and is_enabled(room);++ for sender_id in pairs(dirty) do+ local list = {};+ local set = enabled and state.listeners_by_sender[sender_id];++ if set then+ for receiver_id in pairs(set) do+ list[#list + 1] = receiver_id;+ end+ -- Sorted so set-iteration order never produces a spurious change.+ table.sort(list);+ end++ -- util.json encodes an empty table as "{}"; force "[]" so clients always parse an array.+ local encoded_listeners = (#list > 0) and json.encode(list) or '[]';++ if encoded_listeners ~= state.last_sent_listeners[sender_id] then+ local occupant = room:get_occupant_by_nick(room.jid..'/'..sender_id);++ if occupant then+ module:send(st.message({ from = module.host; to = occupant.jid; })+ :tag('translation-listeners', { xmlns = AUDIO_TRANSLATION_NS; })+ :text(encoded_listeners):up());+ end++ -- Only a delivered push is recorded; for a missing occupant the entry is dropped so a+ -- rejoin with the same endpoint id gets a fresh push instead of being change-suppressed.+ if occupant and #list > 0 then+ state.last_sent_listeners[sender_id] = encoded_listeners;+ else+ state.last_sent_listeners[sender_id] = nil;+ end+ end+ end+end+-- Schedules a debounced publish so a burst of updates produces a single metadata-- broadcast.local function schedule_publish(room)@@ -298,6 +434,7 @@ local function schedule_publish(room)room._audio_translation.publish_scheduled = nil;endpublish(room);+ publish_listeners(room);end);end@@ -398,20 +535,37 @@ function process_main_muc_loaded(main_muc, host_module)return;end+ local state = room._audio_translation;local id = endpoint_id(occupant);local changed = false;- if room._audio_translation.receivers[id] then- room._audio_translation.receivers[id] = nil;+ -- As a receiver: drop its own subscriptions, removing it as a listener from each sender it+ -- was translating (which flags those senders dirty so their pushed lists shrink).+ local own = state.receivers[id];++ if own then+ state.receivers[id] = nil;+ for sender_id in pairs(own) do+ remove_listener(state, sender_id, id);+ endchanged = true;end- for _, subs in pairs(room._audio_translation.receivers) do+ -- As a sender: remove it from every receiver's map, then forget its listener set entirely.+ -- It has left, so there is no one to notify — dropping the tracking prevents a leak and a+ -- stale re-push, and needs no dirty flag.+ for _, subs in pairs(state.receivers) doif subs[id] thensubs[id] = nil;changed = true;endend+ if state.listeners_by_sender[id] or state.last_sent_listeners[id] then+ state.listeners_by_sender[id] = nil;+ state.last_sent_listeners[id] = nil;+ state.dirty_senders[id] = nil;+ changed = true;+ endif changed thenschedule_publish(room);@@ -425,6 +579,9 @@ function process_main_muc_loaded(main_muc, host_module)if event.key == ENABLED_METADATA_KEY and room._audio_translationand not is_healthcheck_room(room.jid) then+ -- Room-wide gating changes every sender's pushed list at once, with no per-sender delta,+ -- so flag them all for the listeners pass (publish() recomputes the aggregate itself).+ mark_all_senders_dirty(room._audio_translation);schedule_publish(room);endend);diff --git a/tests/prosody/mod_audio_translation_component_spec.js b/tests/prosody/mod_audio_translation_component_spec.jsindex 1b2ae38950..4230671002 100644--- a/tests/prosody/mod_audio_translation_component_spec.js+++ b/tests/prosody/mod_audio_translation_component_spec.js@@ -163,6 +163,55 @@ async function waitForRequests(focus, predicate) {throw new Error('audioTranslationRequests did not reach the expected state');}+const LISTENERS_ELEMENT = 'translation-listeners';++/** True if the stanza is a directed <translation-listeners> push. */+function isListeners(msg) {+ return msg.name === 'message'+ && msg.getChild(LISTENERS_ELEMENT, JITMEET_NS) !== undefined;+}++/** Parses a <translation-listeners> push into its JSON array (or null). */+function parseListeners(msg) {+ const text = msg.getChild(LISTENERS_ELEMENT, JITMEET_NS)?.getText();++ return text ? JSON.parse(text) : null;+}++/** Waits for the next directed <translation-listeners> push and returns its parsed array. */+async function waitForListeners(client, timeout = 3000) {+ return parseListeners(await client.waitForMessage(isListeners, timeout));+}++/**+ * Waits for a <translation-listeners> push whose parsed array satisfies `predicate`,+ * returning that array. Skips earlier pushes (e.g. an intermediate single-listener+ * list emitted before a second receiver has subscribed).+ */+async function waitForListenersMatching(client, predicate) {+ for (let i = 0; i < 5; i++) {+ const list = await waitForListeners(client); // eslint-disable-line no-await-in-loop++ if (predicate(list)) {+ return list;+ }+ }+ throw new Error('translation-listeners did not reach the expected state');+}++/** Asserts that no <translation-listeners> push arrives within the timeout. */+async function assertNoListeners(client, timeout = 350) {+ try {+ await client.waitForMessage(isListeners, timeout);+ throw new Error('received unexpected translation-listeners push');+ } catch (err) {+ if (err.message.includes('Timeout')) {+ return;+ }+ throw err;+ }+}+// ─── Tests ────────────────────────────────────────────────────────────────────describe('mod_audio_translation_component', () => {@@ -985,4 +1034,145 @@ describe('mod_audio_translation_component', () => {await assertNoMetadata(foc);});});++ // ── Directed listeners push (translation-listeners) ────────────────────────+ describe('directed listeners push (translation-listeners)', () => {++ it('tells a sender which receiver is translating it', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx = await joinOccupant(r);+ const sender = await joinOccupant(r);++ clients.push(foc, rx, sender);++ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });++ assert.deepEqual(await waitForListeners(sender), [ rx.nick ]);+ });++ it('directs the push only to the translated sender', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx = await joinOccupant(r);+ const s1 = await joinOccupant(r);+ const s2 = await joinOccupant(r);++ clients.push(foc, rx, s1, s2);++ rx.sendAudioTranslation(AT_COMPONENT, { [s1.nick]: 'en' });++ // The translated sender learns about rx ...+ assert.deepEqual(await waitForListeners(s1), [ rx.nick ]);++ // ... while an untranslated sender and the receiver itself get nothing.+ await assertNoListeners(s2);+ await assertNoListeners(rx);+ });++ it('lists every receiver translating a sender, sorted', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx1 = await joinOccupant(r);+ const rx2 = await joinOccupant(r);+ const sender = await joinOccupant(r);++ clients.push(foc, rx1, rx2, sender);++ rx1.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ rx2.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'fr' });++ const list = await waitForListenersMatching(sender, l => l.length === 2);++ assert.deepEqual(list, [ rx1.nick, rx2.nick ].sort());+ });++ it('sends an empty JSON array when the last listener unsubscribes', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx = await joinOccupant(r);+ const sender = await joinOccupant(r);++ clients.push(foc, rx, sender);++ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ assert.deepEqual(await waitForListeners(sender), [ rx.nick ]);++ // Removal clears the sender — the payload must be an empty ARRAY ("[]"), not "{}".+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: '' });++ const cleared = await waitForListeners(sender);++ assert.ok(Array.isArray(cleared), 'cleared payload must parse as a JSON array');+ assert.equal(cleared.length, 0);+ });++ it('clears a sender when its listener leaves the room', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx = await joinOccupant(r);+ const sender = await joinOccupant(r);++ clients.push(foc, sender);++ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ assert.deepEqual(await waitForListeners(sender), [ rx.nick ]);++ await rx.disconnect();++ assert.deepEqual(await waitForListeners(sender), []);+ });++ it('does not resend when the listener set is unchanged', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx = await joinOccupant(r);+ const sender = await joinOccupant(r);++ clients.push(foc, rx, sender);++ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ assert.deepEqual(await waitForListeners(sender), [ rx.nick ]);++ // Identical subscription → listener set unchanged → no new push.+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ await assertNoListeners(sender);+ });++ it('does not resend for a language switch that leaves the listener set unchanged', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const rx = await joinOccupant(r);+ const sender = await joinOccupant(r);++ clients.push(foc, rx, sender);++ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ assert.deepEqual(await waitForListeners(sender), [ rx.nick ]);++ // The badge tracks who translates, not the language — a switch is not a listener change.+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'es' });+ await assertNoListeners(sender);+ });++ it('clears listeners when disabled and restores them when re-enabled', async () => {+ const r = nextRoom();+ const foc = await startRoom(r);+ const mod = await joinOccupant(r, { user: { moderator: true } });+ const sender = await joinOccupant(r);++ clients.push(foc, mod, sender);++ mod.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });+ assert.deepEqual(await waitForListeners(sender), [ mod.nick ]);++ // Disable → the sender's listeners are cleared.+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: false });+ assert.deepEqual(await waitForListenersMatching(sender, l => l.length === 0), []);++ // Re-enable → the retained subscription is re-pushed.+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: true });+ assert.deepEqual(await waitForListenersMatching(sender, l => l.length === 1), [ mod.nick ]);+ });+ });});