Compare commits

...
11 Commits
Author SHA1 Message Date
Marcel Hibbe 2c0b6cbf92 feat(call): order the participant bar by the most recent speakers
A participant that starts speaking swapped places with the previously
promoted one, so the bar did not show who spoke last. The promoted
participant is now moved to the front instead, and the previously
promoted one becomes the first participant in the bar.

As the bar keeps the position of its first visible tile when tiles are
inserted before it, it is scrolled back to the start when the promoted
participant changes, so the most recent speakers are visible.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:40 +01:00
Marcel Hibbe ac9323bf4f feat(call): add speaker view
A menu in the call header switches between the grid, a speaker view
that shows the promoted participant fullscreen, and a speaker view with
a scrollable bar of the other participants below. The selected view
mode is remembered across calls.

A participant that starts speaking is promoted and swaps places with
the previously promoted one, so the other participants keep their
position in the bar. When the promoted participant stops speaking, the
promotion is handed over to a participant still speaking, and when it
leaves, to the current speaker, the most recent speaker or the first
participant in the bar.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:35 +01:00
Marcel Hibbe 0e30000e68 refactor(call): determine started speakers in the CallViewModel
Which participants started speaking was determined inside the
participant grid, so speech was missed while the grid was not shown,
for example during a screen share, and compared against an outdated
state when the grid was shown again.

The CallViewModel now determines it whenever the participants change,
and the grid only reports which participants are visible. Participants
are removed from the signaling thread, so the participant state is now
updated on the main thread when a participant is removed.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:30 +01:00
Marcel Hibbe 131dc20896 fix(call): only clear stream state when the current stream is removed
A renegotiation can add the new stream before the old one is removed,
so removing the old stream cleared the new one and the participant was
shown without audio, video and speaking indicator. The same applied to
the screen stream.

Removing the current screen stream now also ends the screen share, so
the screen share view is closed even without an unshareScreen message.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:25 +01:00
Marcel Hibbe 1eb7b4de7c fix(call): clear screen share state when the screen stream is removed
As for the camera stream, the removed screen stream is passed to the
observer and still lists its tracks, so the participant kept the
removed stream and stayed marked as sharing the screen.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:20 +01:00
Marcel Hibbe 23d57811f3 refactor(call): derive the speaking indicator from audio and connection state
The speaking state now only follows the speaking messages of the
participant, and the indicator and the speaker order use it only while
the participant has audio and is connected. This replaces resetting the
speaking state whenever audio or the connection changed.

During a temporary disconnection the indicator is now hidden instead of
being shown together with the connecting spinner, and it is shown again
once reconnected. A speaking message received while muted no longer
shows the indicator.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:15 +01:00
Marcel Hibbe 73341ffb3b fix(call): clear participant stream state when the stream is removed
The removed stream is passed to the observer and still lists its tracks,
so the participant kept the removed stream and stayed marked as having
audio and speaking.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:09 +01:00
Marcel Hibbe 14a207942a fix(call): keep speaking state on temporary disconnections
Data channel messages survive temporary ICE disconnections and the
speaking state is only sent again when it changes, so it is now reset
only when the connection failed or was closed.

The speaking state is also reset when the participant has no audio
tracks anymore.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:55:04 +01:00
Marcel Hibbe d7b021ff64 fix(call): keep speaker order when the participant grid is recreated
The speaker order lived in the grid's composition, so it was lost while
a screen share was shown or the activity was recreated. It is now kept
in CallViewModel.

Speakers are only promoted once the grid has been laid out, so that
participants already speaking when the grid appears are not all treated
as not visible.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:54:58 +01:00
Marcel Hibbe fb8f82551f fix(call): reset speaking state when the connection is lost or replaced
A "stoppedSpeaking" message can not arrive once the peer connection is
disconnected or replaced, so the speaking indicator could stay on.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:54:52 +01:00
Marcel Hibbe 10fca1d688 feat(call): show speaking indicator and sort speakers in call
Handle incoming "speaking" and "stoppedSpeaking" data channel messages
and show a border around the tile of participants who are speaking.
The speaking state is reset when the participant mutes.

Participants who start speaking while their tile is not visible are
promoted to the top of the grid, after screen sharers. Promoted speakers
keep their order, most recent first.

Closes #5591

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marcel Hibbe <[email protected]>
2026-11-04 14:54:46 +01:00
23 changed files with 1367 additions and 35 deletions

No files matched your search

@@ -53,12 +53,14 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.core.app.NotificationManagerCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.net.toUri
@@ -90,7 +92,11 @@ import com.nextcloud.talk.call.e2ee.FrameKeyRing
import com.nextcloud.talk.call.MutableLocalCallParticipantModel
import com.nextcloud.talk.call.ReactionAnimator
import com.nextcloud.talk.call.ScreenCapture
import com.nextcloud.talk.call.components.CALL_VIEW_MODE_BUTTON_SIZE
import com.nextcloud.talk.call.components.CallViewMode
import com.nextcloud.talk.call.components.CallViewModeButton
import com.nextcloud.talk.call.components.ParticipantGrid
import com.nextcloud.talk.call.components.ParticipantSpeakerView
import com.nextcloud.talk.call.components.SelfVideoView
import com.nextcloud.talk.call.components.screenshare.ScreenShareComponent
import com.nextcloud.talk.camera.BackgroundBlurFrameProcessor
@@ -190,6 +196,7 @@ import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Cache
import org.apache.commons.lang3.StringEscapeUtils
import org.greenrobot.eventbus.Subscribe
@@ -507,6 +514,29 @@ class CallActivity : CallBaseActivity() {
private var isFrontCamera by mutableStateOf(true)
private var isSelfVideoEnabled by mutableStateOf(false)
private fun setUpCallViewModeButton() {
val colorScheme = viewThemeUtils.getColorScheme(this)
binding!!.callViewModeButton.setContent {
MaterialTheme(colorScheme = colorScheme) {
val participantUiStates by callViewModel.participants.collectAsState()
val viewMode by callViewModel.viewMode.collectAsState()
// A single participant is shown fullscreen in all view modes
if (participantUiStates.size > 1) {
CallViewModeButton(viewMode = viewMode) { selectedViewMode ->
callViewModel.setViewMode(selectedViewMode)
lifecycleScope.launch(Dispatchers.IO) {
appPreferences.callViewMode = selectedViewMode.preferenceValue
}
}
} else {
// Keeps the height of the header, so the participants do not move when the button is shown
Spacer(modifier = Modifier.height(CALL_VIEW_MODE_BUTTON_SIZE))
}
}
}
}
@SuppressLint("ClickableViewAccessibility", "Detekt.LongMethod")
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate")
@@ -515,6 +545,14 @@ class CallActivity : CallBaseActivity() {
conversationUser = setUpBoundUserOrFinish() ?: return
callViewModel = ViewModelProvider(this, viewModelFactory)[CallViewModel::class.java]
if (!callViewModel.hasViewMode) {
lifecycleScope.launch {
val viewMode = withContext(Dispatchers.IO) {
CallViewMode.fromPreferenceValue(appPreferences.callViewMode)
}
callViewModel.restoreViewMode(viewMode)
}
}
rootEglBase = EglBase.create()
binding = CallActivityBinding.inflate(layoutInflater)
@@ -559,27 +597,42 @@ class CallActivity : CallBaseActivity() {
MaterialTheme {
val screenShareParticipantUiState by callViewModel.activeScreenShareSession.collectAsState()
val participantUiStates by callViewModel.participants.collectAsState(initial = emptyList())
LaunchedEffect(participantUiStates) {
participantUiStates.forEach {
Log.d(TAG, "Participant: ${it.nick} (${it.sessionKey})")
}
}
val speakers by callViewModel.speakers.collectAsState()
val viewMode by callViewModel.viewMode.collectAsState()
val speakerViewOrder by callViewModel.speakerViewOrder.collectAsState()
if (screenShareParticipantUiState == null) {
ParticipantGrid(
participantUiStates = participantUiStates,
eglBase = rootEglBase!!,
isVoiceOnlyCall = isVoiceOnlyCall,
onClick = {},
onScreenShareIconClick = {
callViewModel.setActiveScreenShareSession(it)
}
)
if (viewMode.isSpeakerView) {
ParticipantSpeakerView(
eglBase = rootEglBase!!,
participantUiStates = participantUiStates,
speakerViewOrder = speakerViewOrder,
isParticipantBarVisible = viewMode == CallViewMode.SPEAKER_WITH_PARTICIPANT_BAR,
isVoiceOnlyCall = isVoiceOnlyCall,
onVisibleSessionKeysChanged = callViewModel::setVisibleSessionKeys,
onScreenShareIconClick = {
callViewModel.setActiveScreenShareSession(it)
}
)
} else {
ParticipantGrid(
participantUiStates = participantUiStates,
eglBase = rootEglBase!!,
isVoiceOnlyCall = isVoiceOnlyCall,
speakers = speakers,
onVisibleSessionKeysChanged = callViewModel::setVisibleSessionKeys,
onClick = {},
onScreenShareIconClick = {
callViewModel.setActiveScreenShareSession(it)
}
)
}
}
}
}
setUpCallViewModeButton()
hideNavigationIfNoPipAvailable()
val extras = intent.extras
if (extras != null) {
@@ -9,6 +9,11 @@ package com.nextcloud.talk.activities
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nextcloud.talk.call.components.CallViewMode
import com.nextcloud.talk.call.components.initialSpeakerViewOrder
import com.nextcloud.talk.call.components.promoteSpeakers
import com.nextcloud.talk.call.components.sortParticipants
import com.nextcloud.talk.call.components.updateSpeakerViewOrder
import com.nextcloud.talk.signaling.SignalingMessageReceiver
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -33,6 +38,30 @@ class CallViewModel @Inject constructor() : ViewModel() {
private val _isScreenSharingAllowed = MutableStateFlow(false)
val isScreenSharingAllowed: StateFlow<Boolean> = _isScreenSharingAllowed.asStateFlow()
private val _speakers = MutableStateFlow<List<String>>(emptyList())
/** Session keys of participants promoted for having spoken while not visible, most recent first. */
val speakers: StateFlow<List<String>> = _speakers.asStateFlow()
private val _viewMode = MutableStateFlow(CallViewMode.GRID)
val viewMode: StateFlow<CallViewMode> = _viewMode.asStateFlow()
/** Whether a view mode was set, so the preferred one does not need to be restored again. */
var hasViewMode = false
private set
private val _speakerViewOrder = MutableStateFlow<List<String>>(emptyList())
/**
* Session keys of the participants in the speaker view: the promoted participant first, followed by the
* participants in the participant bar. Only updated while the speaker view is shown.
*/
val speakerViewOrder: StateFlow<List<String>> = _speakerViewOrder.asStateFlow()
private var participantSessionKeys = emptyList<String>()
private var activeSpeakerSessionKeys = emptySet<String>()
private var visibleSessionKeys = emptySet<String>()
fun getParticipant(sessionId: String?): ParticipantHandler? {
if (sessionId == null) {
Log.w(TAG, "Attempted to get participant with null sessionId.")
@@ -67,7 +96,7 @@ class CallViewModel @Inject constructor() : ViewModel() {
viewModelScope.launch {
participantHandler.uiState.collect {
_participants.value = participantHandlers.values.map { it.uiState.value }
updateParticipants()
}
}
}
@@ -85,7 +114,66 @@ class CallViewModel @Inject constructor() : ViewModel() {
fun removeParticipant(sessionId: String) {
participantHandlers[sessionId]?.destroy()
participantHandlers.remove(sessionId)
_participants.value = participantHandlers.values.map { it.uiState.value }
// Participants are removed from the signaling thread, the participant state is only updated on the main thread
viewModelScope.launch {
updateParticipants()
}
}
private fun updateParticipants() {
val participants = participantHandlers.values.map { it.uiState.value }
_participants.value = participants
val sessionKeys = participants.mapNotNull { it.sessionKey }
val activeSpeakers = participants.filter { it.isActiveSpeaker }.mapNotNull { it.sessionKey }.toSet()
if (sessionKeys == participantSessionKeys && activeSpeakers == activeSpeakerSessionKeys) return
val startedSpeaking = activeSpeakers - activeSpeakerSessionKeys
val previousActiveSpeakers = activeSpeakerSessionKeys
participantSessionKeys = sessionKeys
activeSpeakerSessionKeys = activeSpeakers
_speakers.value = promoteSpeakers(
speakers = _speakers.value,
startedSpeaking = startedSpeaking,
visibleSessionKeys = visibleSessionKeys,
participantSessionKeys = sessionKeys.toSet()
)
if (_viewMode.value.isSpeakerView) {
_speakerViewOrder.value = updateSpeakerViewOrder(
order = _speakerViewOrder.value,
participantSessionKeys = sessionKeys,
activeSpeakerSessionKeys = activeSpeakers,
previousActiveSpeakerSessionKeys = previousActiveSpeakers,
speakers = _speakers.value
)
}
}
/** Sets the participants currently shown, so participants that start speaking while not shown are promoted. */
fun setVisibleSessionKeys(sessionKeys: Set<String>) {
visibleSessionKeys = sessionKeys
}
/** Sets the view mode the user prefers, unless a view mode was already set for this call. */
fun restoreViewMode(viewMode: CallViewMode) {
if (!hasViewMode) setViewMode(viewMode)
}
fun setViewMode(viewMode: CallViewMode) {
hasViewMode = true
val wasSpeakerView = _viewMode.value.isSpeakerView
_viewMode.value = viewMode
if (!viewMode.isSpeakerView || wasSpeakerView) return
val sortedSessionKeys = sortParticipants(_participants.value, _speakers.value).mapNotNull { it.sessionKey }
_speakerViewOrder.value = initialSpeakerViewOrder(
participantSessionKeys = sortedSessionKeys,
activeSpeakerSessionKeys = activeSpeakerSessionKeys,
previouslyPromotedSessionKey = _speakerViewOrder.value.firstOrNull(),
speakers = _speakers.value
)
}
fun setActiveScreenShareSession(session: String?) {
@@ -53,7 +53,11 @@ class ParticipantHandler(
}
override fun onStreamRemoved(mediaStream: MediaStream?) {
handleStreamChange(mediaStream)
// A renegotiation can add the new stream before the old one is removed, so only the current stream
// clears the state
if (mediaStream === _uiState.value.mediaStream) {
handleStreamChange(null)
}
}
override fun onIceConnectionStateChanged(iceConnectionState: IceConnectionState?) {
@@ -69,7 +73,10 @@ class ParticipantHandler(
}
override fun onStreamRemoved(mediaStream: MediaStream?) {
handleScreenStreamChange(mediaStream)
if (mediaStream === _uiState.value.screenMediaStream) {
handleScreenStreamChange(null)
onParticipantUnshareScreen.invoke(_uiState.value.sessionKey)
}
}
override fun onIceConnectionStateChanged(iceConnectionState: IceConnectionState?) {
@@ -158,6 +165,14 @@ class ParticipantHandler(
_uiState.update { it.copy(isStreamEnabled = false) }
}
override fun onSpeaking() {
_uiState.update { it.copy(isSpeaking = true) }
}
override fun onStoppedSpeaking() {
_uiState.update { it.copy(isSpeaking = false) }
}
override fun onNickChanged(nick: String?) {
_uiState.update { it.copy(nick = nick) }
}
@@ -190,6 +205,9 @@ class ParticipantHandler(
this.peerConnection = peerConnection
// "stoppedSpeaking" can no longer be received from the previous peer connection.
_uiState.update { it.copy(isSpeaking = false) }
if (this.peerConnection == null) {
// special case when participant has no permission. -> no streams are transmitted but he must be shown as
// connected
@@ -17,6 +17,8 @@ data class ParticipantUiState(
val nick: String?,
val isConnected: Boolean,
val isAudioEnabled: Boolean,
/** Speaking state as last reported by the participant. */
val isSpeaking: Boolean = false,
val isStreamEnabled: Boolean,
val mediaStream: MediaStream? = null,
val isScreenStreamEnabled: Boolean,
@@ -25,4 +27,8 @@ data class ParticipantUiState(
val actorType: ParticipantDto.ActorType? = null,
val actorId: String? = null,
val isInternal: Boolean
)
) {
/** Whether the participant is speaking and can be heard, so the speaking indicator is shown. */
val isActiveSpeaker: Boolean
get() = isSpeaking && isAudioEnabled && isConnected
}
@@ -0,0 +1,28 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
/** How the participants of a call are shown. */
enum class CallViewMode(val preferenceValue: String) {
/** All participants in a grid. */
GRID("grid"),
/** The promoted participant fullscreen. */
SPEAKER("speaker"),
/** The promoted participant above a bar with the other participants. */
SPEAKER_WITH_PARTICIPANT_BAR("speaker_with_participant_bar");
val isSpeakerView: Boolean
get() = this != GRID
companion object {
fun fromPreferenceValue(value: String?): CallViewMode =
entries.firstOrNull { it.preferenceValue == value } ?: GRID
}
}
@@ -0,0 +1,95 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.CallToAction
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.nextcloud.talk.R
/** Size of the view mode button, so the call header keeps its height while the button is hidden. */
val CALL_VIEW_MODE_BUTTON_SIZE = 40.dp
/** Button in the call header that opens a menu to switch between the grid and the speaker view. */
@Composable
fun CallViewModeButton(viewMode: CallViewMode, onViewModeSelected: (CallViewMode) -> Unit) {
var isMenuExpanded by remember { mutableStateOf(false) }
Box {
IconButton(
onClick = { isMenuExpanded = true },
modifier = Modifier.size(CALL_VIEW_MODE_BUTTON_SIZE)
) {
Icon(
imageVector = viewMode.icon,
contentDescription = stringResource(R.string.nc_call_view_mode),
tint = Color.White
)
}
DropdownMenu(expanded = isMenuExpanded, onDismissRequest = { isMenuExpanded = false }) {
CallViewMode.entries.forEach { mode ->
DropdownMenuItem(
text = { Text(stringResource(mode.titleRes)) },
leadingIcon = { Icon(imageVector = mode.icon, contentDescription = null) },
trailingIcon = if (mode == viewMode) {
{ Icon(imageVector = Icons.Filled.Check, contentDescription = null) }
} else {
null
},
onClick = {
isMenuExpanded = false
onViewModeSelected(mode)
}
)
}
}
}
}
private val CallViewMode.icon: ImageVector
get() = when (this) {
CallViewMode.GRID -> Icons.Filled.GridView
CallViewMode.SPEAKER -> Icons.Filled.AccountBox
CallViewMode.SPEAKER_WITH_PARTICIPANT_BAR -> Icons.Filled.CallToAction
}
@get:StringRes
private val CallViewMode.titleRes: Int
get() = when (this) {
CallViewMode.GRID -> R.string.nc_call_view_mode_grid
CallViewMode.SPEAKER -> R.string.nc_call_view_mode_speaker
CallViewMode.SPEAKER_WITH_PARTICIPANT_BAR -> R.string.nc_call_view_mode_speaker_with_participant_bar
}
@Preview
@Composable
fun CallViewModeButtonPreview() {
CallViewModeButton(viewMode = CallViewMode.SPEAKER_WITH_PARTICIPANT_BAR, onViewModeSelected = {})
}
@@ -21,17 +21,27 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.isFinite
import org.webrtc.EglBase
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlin.math.ceil
import android.util.Log
import com.nextcloud.talk.activities.ParticipantUiState
/** Minimum height of a participant tile, also used for the tiles in the participant bar of the speaker view. */
val PARTICIPANT_TILE_MIN_HEIGHT = 100.dp
@SuppressLint("UnusedBoxWithConstraintsScope")
@Suppress("LongParameterList", "LongMethod")
@Composable
@@ -40,6 +50,8 @@ fun ParticipantGrid(
eglBase: EglBase?,
participantUiStates: List<ParticipantUiState>,
isVoiceOnlyCall: Boolean,
speakers: List<String> = emptyList(),
onVisibleSessionKeysChanged: (Set<String>) -> Unit = {},
onClick: () -> Unit,
onScreenShareIconClick: ((String?) -> Unit?)?
) {
@@ -48,7 +60,26 @@ fun ParticipantGrid(
val configuration = LocalConfiguration.current
val isPortrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val minItemHeight = 100.dp
val gridState = rememberLazyGridState()
LaunchedEffect(gridState) {
snapshotFlow { gridState.layoutInfo.visibleItemsInfo.mapNotNull { it.key as? String }.toSet() }
.distinctUntilChanged()
.collect { onVisibleSessionKeysChanged(it) }
}
// A lazy grid keeps its first visible item in place when items move in front of it, so the grid has to be
// scrolled explicitly to keep showing the top, where promoted speakers are placed. Whether the grid was at the
// top is read in the composition with the new speaker order, before the grid is laid out with it.
val isScrolledToTop by remember {
derivedStateOf { gridState.firstVisibleItemIndex == 0 && gridState.firstVisibleItemScrollOffset == 0 }
}
val wasScrolledToTop = isScrolledToTop
LaunchedEffect(speakers) {
if (wasScrolledToTop) {
gridState.requestScrollToItem(0)
}
}
if (participantUiStates.isEmpty()) return
@@ -82,9 +113,9 @@ fun ParticipantGrid(
val itemHeight = if (hasBoundedHeight) {
val gridAvailableHeight = maxHeight - totalVerticalSpacing - totalVerticalPadding
val rawItemHeight = gridAvailableHeight / rows
maxOf(rawItemHeight, minItemHeight)
maxOf(rawItemHeight, PARTICIPANT_TILE_MIN_HEIGHT)
} else {
minItemHeight
PARTICIPANT_TILE_MIN_HEIGHT
}
val gridHeight = if (hasBoundedHeight) {
@@ -95,6 +126,7 @@ fun ParticipantGrid(
LazyVerticalGrid(
columns = GridCells.Fixed(columns),
state = gridState,
modifier = Modifier
.fillMaxWidth()
.height(gridHeight),
@@ -103,15 +135,7 @@ fun ParticipantGrid(
contentPadding = PaddingValues(vertical = edgePadding, horizontal = edgePadding)
) {
items(
items = participantUiStates.sortedWith(
compareBy(
{ !it.isScreenStreamEnabled },
{ !it.isStreamEnabled },
{ !it.isAudioEnabled },
{ !it.raisedHand },
{ !it.isConnected }
)
),
items = sortParticipants(participantUiStates, speakers),
key = { it.sessionKey!! }
) { participant ->
ParticipantTile(
@@ -0,0 +1,42 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
import com.nextcloud.talk.activities.ParticipantUiState
/**
* Returns the speaker list with the participants that started speaking moved to its front, most recent first.
*
* Participants that are currently visible are not promoted, so that speakers already on screen do not jump around.
* Session keys of participants that are no longer in the call are dropped.
*/
fun promoteSpeakers(
speakers: List<String>,
startedSpeaking: Set<String>,
visibleSessionKeys: Set<String>,
participantSessionKeys: Set<String>
): List<String> {
val promoted = startedSpeaking.filter { it !in visibleSessionKeys }
return (promoted + speakers.filter { it !in promoted }).filter { it in participantSessionKeys }
}
/**
* Sorts participants by screen sharing, then by their position in [speakers], then by their media and call state.
* The sort is stable, so participants with equal priority keep their order.
*/
fun sortParticipants(participants: List<ParticipantUiState>, speakers: List<String>): List<ParticipantUiState> =
participants.sortedWith(
compareBy(
{ !it.isScreenStreamEnabled },
{ speakers.indexOf(it.sessionKey).takeIf { index -> index >= 0 } ?: Int.MAX_VALUE },
{ !it.isStreamEnabled },
{ !it.isAudioEnabled },
{ !it.raisedHand },
{ !it.isConnected }
)
)
@@ -0,0 +1,172 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.key
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.nextcloud.talk.activities.ParticipantUiState
import kotlinx.coroutines.flow.distinctUntilChanged
import org.webrtc.EglBase
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.max
private val speakerViewSpacing = 8.dp
private const val PARTICIPANT_BAR_TILE_ASPECT_RATIO = 1.5f
private val participantBarTilePeekWidth = 16.dp
/**
* Shows the promoted participant fullscreen, optionally above a horizontally scrollable bar with the other
* participants.
*
* @param speakerViewOrder session keys of the promoted participant followed by the participants in the bar
*/
@Suppress("LongParameterList")
@Composable
fun ParticipantSpeakerView(
modifier: Modifier = Modifier,
eglBase: EglBase?,
participantUiStates: List<ParticipantUiState>,
speakerViewOrder: List<String>,
isParticipantBarVisible: Boolean,
isVoiceOnlyCall: Boolean,
onVisibleSessionKeysChanged: (Set<String>) -> Unit = {},
onScreenShareIconClick: ((String?) -> Unit?)?
) {
val participantsBySessionKey = participantUiStates.associateBy { it.sessionKey }
// Participants that joined since the order was last updated are added to the end of the bar
val orderedParticipants = speakerViewOrder.mapNotNull { participantsBySessionKey[it] } +
participantUiStates.filter { it.sessionKey !in speakerViewOrder }
val promotedParticipant = orderedParticipants.firstOrNull() ?: return
val barParticipants = orderedParticipants.drop(1)
val isBarShown = isParticipantBarVisible && barParticipants.isNotEmpty()
val barState = rememberLazyListState()
// The previously promoted participant is inserted at the start of the bar. As the bar keeps the position of its
// first visible tile, scroll back so the most recent speakers are shown
LaunchedEffect(barState, promotedParticipant.sessionKey) {
barState.scrollToItem(0)
}
LaunchedEffect(barState, promotedParticipant.sessionKey, isBarShown) {
snapshotFlow {
val barSessionKeys = if (isBarShown) {
barState.layoutInfo.visibleItemsInfo.mapNotNull { it.key as? String }
} else {
emptyList()
}
setOfNotNull(promotedParticipant.sessionKey) + barSessionKeys
}
.distinctUntilChanged()
.collect { onVisibleSessionKeysChanged(it) }
}
Column(
modifier = modifier
.fillMaxSize()
.padding(speakerViewSpacing),
verticalArrangement = Arrangement.spacedBy(speakerViewSpacing)
) {
key(promotedParticipant.sessionKey) {
ParticipantTile(
participantUiState = promotedParticipant,
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
eglBase = eglBase,
isVoiceOnlyCall = isVoiceOnlyCall,
onScreenShareIconClick = onScreenShareIconClick
)
}
// When the bar is hidden its participants are not composed, so their videos are not rendered
if (isBarShown) {
BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
val tileWidth = participantBarTileWidth(availableWidth = maxWidth, tileCount = barParticipants.size)
LazyRow(state = barState, horizontalArrangement = Arrangement.spacedBy(speakerViewSpacing)) {
items(items = barParticipants, key = { it.sessionKey!! }) { participant ->
ParticipantTile(
participantUiState = participant,
modifier = Modifier.size(width = tileWidth, height = PARTICIPANT_TILE_MIN_HEIGHT),
eglBase = eglBase,
isVoiceOnlyCall = isVoiceOnlyCall,
onScreenShareIconClick = onScreenShareIconClick
)
}
}
}
}
}
}
/**
* Returns the width of the tiles in the participant bar.
*
* When not all tiles fit and the tile at the edge is cut in a clearly visible way, the user can already see that the
* bar is scrollable and the tiles keep their preferred width. Otherwise the tiles are made a bit narrower, so a few
* pixels of the next tile are visible, or all tiles fit when only a few pixels were missing.
*/
fun participantBarTileWidth(
availableWidth: Dp,
tileCount: Int,
preferredWidth: Dp = PARTICIPANT_TILE_MIN_HEIGHT * PARTICIPANT_BAR_TILE_ASPECT_RATIO,
spacing: Dp = speakerViewSpacing,
peekWidth: Dp = participantBarTilePeekWidth
): Dp {
val available = availableWidth.value
val preferred = preferredWidth.value
val gap = spacing.value
val peek = peekWidth.value
val requiredWidth = tileCount * (preferred + gap) - gap
val fullyFittingTiles = floor((available + gap) / (preferred + gap)).toInt()
val cutTileVisibleWidth = available - fullyFittingTiles * (preferred + gap)
val isCutTileClearlyVisible = cutTileVisibleWidth >= peek && cutTileVisibleWidth <= preferred - peek
if (requiredWidth <= available || isCutTileClearlyVisible) return preferredWidth
val tilesToFit = max(ceil((available - peek) / (preferred + gap)).toInt(), 1)
val width = if (tilesToFit >= tileCount) {
(available - (tileCount - 1) * gap) / tileCount
} else {
(available - peek) / tilesToFit - gap
}
return floor(width).dp
}
private const val PREVIEW_PARTICIPANT_COUNT = 5
@Preview
@Composable
fun SpeakerViewPreview() {
val participants = getTestParticipants(PREVIEW_PARTICIPANT_COUNT)
ParticipantSpeakerView(
eglBase = null,
participantUiStates = participants,
speakerViewOrder = participants.mapNotNull { it.sessionKey },
isParticipantBarVisible = true,
isVoiceOnlyCall = false,
onScreenShareIconClick = {}
)
}
@@ -10,6 +10,7 @@ package com.nextcloud.talk.call.components
import android.annotation.SuppressLint
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -46,6 +47,7 @@ import kotlin.String
const val NICK_OFFSET = 4f
const val NICK_BLUR_RADIUS = 4f
const val AVATAR_SIZE_FACTOR = 0.6f
val SPEAKING_BORDER_WIDTH = 3.dp
@SuppressLint("UnusedBoxWithConstraintsScope")
@Suppress("Detekt.LongMethod")
@@ -65,9 +67,11 @@ fun ParticipantTile(
val color = Color(ColorGenerator.usernameToColor(displayName))
val tileShape = RoundedCornerShape(12.dp)
BoxWithConstraints(
modifier = modifier
.clip(RoundedCornerShape(12.dp))
.clip(tileShape)
.background(color)
) {
val avatarSize = min(maxWidth, maxHeight) * AVATAR_SIZE_FACTOR
@@ -139,6 +143,14 @@ fun ParticipantTile(
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
if (participantUiState.isActiveSpeaker) {
Box(
modifier = Modifier
.fillMaxSize()
.border(SPEAKING_BORDER_WIDTH, Color.White, tileShape)
)
}
}
}
@@ -166,7 +178,8 @@ fun ParticipantTilePreview() {
roomToken = "",
nick = "testuser one",
isConnected = true,
isAudioEnabled = false,
isAudioEnabled = true,
isSpeaking = true,
isStreamEnabled = true,
isScreenStreamEnabled = true,
raisedHand = true,
@@ -0,0 +1,78 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
// The order of the participants in the speaker view, as a list of session keys: the first one is the promoted
// participant shown fullscreen, the others are shown in the participant bar.
/**
* Returns the order when switching to the speaker view, starting from the order of the participants in the grid.
*
* The promoted participant is the one currently speaking, otherwise the previously promoted one if still in the call,
* then the most recent speaker and finally the first participant.
*/
fun initialSpeakerViewOrder(
participantSessionKeys: List<String>,
activeSpeakerSessionKeys: Set<String>,
previouslyPromotedSessionKey: String?,
speakers: List<String>
): List<String> {
val promoted = participantSessionKeys.firstOrNull { it in activeSpeakerSessionKeys }
?: previouslyPromotedSessionKey?.takeIf { it in participantSessionKeys }
?: fallbackPromotedSessionKey(participantSessionKeys, speakers)
return promoteInSpeakerView(participantSessionKeys, promoted)
}
/**
* Returns the order after the participants or their speaking state changed.
*
* Participants that left are dropped and new participants are added to the end of the participant bar. A participant
* that starts speaking is promoted. When the promoted participant stops speaking, the promotion is handed over to a
* participant that is still speaking, and when the promoted participant left, a new one is chosen like for
* [initialSpeakerViewOrder]. When several participants qualify, the one shown first is promoted.
*
* @param previousActiveSpeakerSessionKeys the participants that were speaking at the previous update
*/
fun updateSpeakerViewOrder(
order: List<String>,
participantSessionKeys: List<String>,
activeSpeakerSessionKeys: Set<String>,
previousActiveSpeakerSessionKeys: Set<String>,
speakers: List<String>
): List<String> {
val startedSpeaking = activeSpeakerSessionKeys - previousActiveSpeakerSessionKeys
val stoppedSpeaking = previousActiveSpeakerSessionKeys - activeSpeakerSessionKeys
val previouslyPromoted = order.firstOrNull()
val updatedOrder = order.filter { it in participantSessionKeys } +
participantSessionKeys.filter { it !in order }
val firstActiveSpeaker = updatedOrder.firstOrNull { it in activeSpeakerSessionKeys }
val promoted = when {
startedSpeaking.isNotEmpty() -> updatedOrder.firstOrNull { it in startedSpeaking }
// The participants that left were already dropped, so the fallback is the first one in the participant bar
previouslyPromoted !in participantSessionKeys ->
firstActiveSpeaker ?: fallbackPromotedSessionKey(updatedOrder, speakers)
previouslyPromoted in stoppedSpeaking -> firstActiveSpeaker
else -> null
}
return promoteInSpeakerView(updatedOrder, promoted)
}
/**
* Moves the participant to the front. The previously promoted participant becomes the first one in the participant
* bar, so the participants in the bar are ordered by how recently they were promoted.
*/
fun promoteInSpeakerView(order: List<String>, sessionKey: String?): List<String> {
val index = order.indexOf(sessionKey)
if (index <= 0) return order
return listOf(sessionKey!!) + order.filterIndexed { i, _ -> i != index }
}
private fun fallbackPromotedSessionKey(participantSessionKeys: List<String>, speakers: List<String>): String? =
speakers.firstOrNull { it in participantSessionKeys } ?: participantSessionKeys.firstOrNull()
@@ -122,6 +122,10 @@ public interface AppPreferences {
void setCallMicrophoneMuted(boolean value);
String getCallViewMode();
void setCallViewMode(String value);
boolean getIsKeyboardIncognito();
void setIncognitoKeyboard(boolean value);
@@ -321,6 +321,18 @@ class AppPreferencesImpl(val context: Context) : AppPreferences {
}
}
override fun getCallViewMode(): String =
runBlocking {
async { readString(CALL_VIEW_MODE).first() }
}.getCompleted()
override fun setCallViewMode(value: String) =
runBlocking<Unit> {
async {
writeString(CALL_VIEW_MODE, value)
}
}
override fun getIsKeyboardIncognito(): Boolean {
val read = runBlocking { async { readBoolean(INCOGNITO_KEYBOARD).first() } }.getCompleted()
return read
@@ -725,6 +737,7 @@ class AppPreferencesImpl(val context: Context) : AppPreferences {
const val SCREEN_SECURITY = "screen_security"
const val SCREEN_LOCK = "screen_lock"
const val CALL_MICROPHONE_MUTED = "call_microphone_muted"
const val CALL_VIEW_MODE = "call_view_mode"
const val INCOGNITO_KEYBOARD = "incognito_keyboard"
const val SHOW_ECOSYSTEM = "SHOW_ECOSYSTEM"
const val PHONE_BOOK_INTEGRATION = "phone_book_integration"
@@ -57,6 +57,18 @@ public class DataChannelMessageNotifier {
}
}
public synchronized void notifySpeaking() {
for (PeerConnectionWrapper.DataChannelMessageListener listener : new ArrayList<>(dataChannelMessageListeners)) {
listener.onSpeaking();
}
}
public synchronized void notifyStoppedSpeaking() {
for (PeerConnectionWrapper.DataChannelMessageListener listener : new ArrayList<>(dataChannelMessageListeners)) {
listener.onStoppedSpeaking();
}
}
public synchronized void notifyNickChanged(String nick) {
for (PeerConnectionWrapper.DataChannelMessageListener listener : new ArrayList<>(dataChannelMessageListeners)) {
listener.onNickChanged(nick);
@@ -98,6 +98,8 @@ public final class PeerConnectionWrapper {
void onAudioOff();
void onVideoOn();
void onVideoOff();
void onSpeaking();
void onStoppedSpeaking();
void onNickChanged(String nick);
}
@@ -650,6 +652,18 @@ public final class PeerConnectionWrapper {
return;
}
if ("speaking".equals(dataChannelMessage.getType())) {
dataChannelMessageNotifier.notifySpeaking();
return;
}
if ("stoppedSpeaking".equals(dataChannelMessage.getType())) {
dataChannelMessageNotifier.notifyStoppedSpeaking();
return;
}
}
}
@@ -71,6 +71,11 @@
android:textStyle="bold"
tools:text="Marsellus Wallace" />
<androidx.compose.ui.platform.ComposeView
android:id="@+id/callViewModeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/call_recording_indicator"
android:layout_width="wrap_content"
+4
View File
@@ -418,6 +418,10 @@ How to translate with transifex:
<string name="nc_call_button_content_description_switch_camera">Switch camera</string>
<string name="nc_call_self_video_enlarge">Enlarge self video</string>
<string name="nc_call_self_video_shrink">Shrink self video</string>
<string name="nc_call_view_mode">Call view mode</string>
<string name="nc_call_view_mode_grid">Grid view</string>
<string name="nc_call_view_mode_speaker">Speaker view</string>
<string name="nc_call_view_mode_speaker_with_participant_bar">Speaker view with participant bar</string>
<string name="nc_call_raised_hand">%1$s raised the hand</string>
<string name="raise_hand">Raise hand</string>
<string name="lower_hand">Lower hand</string>
@@ -6,7 +6,11 @@
*/
package com.nextcloud.talk.activities
import com.nextcloud.talk.call.components.CallViewMode
import com.nextcloud.talk.signaling.SignalingMessageReceiver
import com.nextcloud.talk.webrtc.PeerConnectionWrapper
import com.nextcloud.talk.webrtc.PeerConnectionWrapper.DataChannelMessageListener
import com.nextcloud.talk.webrtc.PeerConnectionWrapper.PeerConnectionObserver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
@@ -20,9 +24,13 @@ import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.webrtc.PeerConnection.IceConnectionState
@OptIn(ExperimentalCoroutinesApi::class)
@Suppress("TooManyFunctions")
class CallViewModelTest {
private lateinit var viewModel: CallViewModel
@@ -160,4 +168,151 @@ class CallViewModelTest {
assertEquals(0, viewModel.participants.value.size)
}
@Test
fun `participants that start speaking while not visible are promoted`() {
addParticipants("a", "b", "c")
viewModel.setVisibleSessionKeys(setOf("a"))
startSpeaking("c")
startSpeaking("b")
assertEquals(listOf("b", "c"), viewModel.speakers.value)
}
@Test
fun `participants that keep speaking are not promoted again`() {
addParticipants("a", "b", "c")
startSpeaking("a")
startSpeaking("b")
addParticipants("d")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(listOf("b", "a"), viewModel.speakers.value)
}
@Test
fun `visible participants that start speaking are not promoted`() {
addParticipants("a", "b")
viewModel.setVisibleSessionKeys(setOf("a", "b"))
startSpeaking("a")
assertEquals(emptyList<String>(), viewModel.speakers.value)
}
@Test
fun `speakers that left the call are dropped`() {
addParticipants("a", "b")
startSpeaking("b")
viewModel.removeParticipant("b")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(emptyList<String>(), viewModel.speakers.value)
}
@Test
fun `participants that start speaking in the speaker view are promoted in the grid too`() {
addParticipants("a", "b", "c")
testDispatcher.scheduler.advanceUntilIdle()
viewModel.setViewMode(CallViewMode.SPEAKER)
val notPromoted = viewModel.speakerViewOrder.value.last()
viewModel.setVisibleSessionKeys(setOf(viewModel.speakerViewOrder.value.first()))
startSpeaking(notPromoted)
assertEquals(notPromoted, viewModel.speakerViewOrder.value.first())
assertEquals(listOf(notPromoted), viewModel.speakers.value)
}
@Test
fun `speech that started in the grid view is not counted as started when switching to the speaker view`() {
addParticipants("a", "b", "c")
startSpeaking("b")
viewModel.setViewMode(CallViewMode.SPEAKER)
assertEquals("b", viewModel.speakerViewOrder.value.first())
startSpeaking("c")
addParticipants("d")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals("c", viewModel.speakerViewOrder.value.first())
}
@Test
fun `switching to the speaker view orders all participants`() {
addParticipants("a", "b", "c")
testDispatcher.scheduler.advanceUntilIdle()
viewModel.setViewMode(CallViewMode.SPEAKER_WITH_PARTICIPANT_BAR)
assertEquals(setOf("a", "b", "c"), viewModel.speakerViewOrder.value.toSet())
assertEquals(3, viewModel.speakerViewOrder.value.size)
}
@Test
fun `switching between speaker views keeps the order`() {
addParticipants("a", "b", "c")
testDispatcher.scheduler.advanceUntilIdle()
viewModel.setViewMode(CallViewMode.SPEAKER_WITH_PARTICIPANT_BAR)
val order = viewModel.speakerViewOrder.value
viewModel.setViewMode(CallViewMode.SPEAKER)
assertEquals(order, viewModel.speakerViewOrder.value)
}
@Test
fun `removing the promoted participant promotes another one`() {
addParticipants("a", "b", "c")
testDispatcher.scheduler.advanceUntilIdle()
viewModel.setViewMode(CallViewMode.SPEAKER)
val promoted = viewModel.speakerViewOrder.value.first()
viewModel.removeParticipant(promoted)
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(2, viewModel.speakerViewOrder.value.size)
assertFalse(promoted in viewModel.speakerViewOrder.value)
}
@Test
fun `speaker view order is not updated in the grid view`() {
addParticipants("a", "b")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(emptyList<String>(), viewModel.speakerViewOrder.value)
}
@Test
fun `restoring the view mode does not override a view mode set before`() {
viewModel.setViewMode(CallViewMode.SPEAKER)
viewModel.restoreViewMode(CallViewMode.GRID)
assertEquals(CallViewMode.SPEAKER, viewModel.viewMode.value)
}
private fun startSpeaking(sessionId: String) {
val peerConnectionWrapper: PeerConnectionWrapper = mock {}
viewModel.getParticipant(sessionId)!!.setPeerConnection(peerConnectionWrapper)
val listenerCaptor = argumentCaptor<DataChannelMessageListener>()
verify(peerConnectionWrapper).addListener(listenerCaptor.capture())
val observerCaptor = argumentCaptor<PeerConnectionObserver>()
verify(peerConnectionWrapper).addObserver(observerCaptor.capture())
observerCaptor.firstValue.onIceConnectionStateChanged(IceConnectionState.CONNECTED)
listenerCaptor.firstValue.onAudioOn()
listenerCaptor.firstValue.onSpeaking()
testDispatcher.scheduler.advanceUntilIdle()
}
private fun addParticipants(vararg sessionIds: String) {
val receiver = mock<SignalingMessageReceiver>()
sessionIds.forEach {
viewModel.addParticipant(baseUrl = "", roomToken = "", sessionId = it, signalingMessageReceiver = receiver)
}
}
}
@@ -7,6 +7,9 @@
package com.nextcloud.talk.activities
import com.nextcloud.talk.signaling.SignalingMessageReceiver
import com.nextcloud.talk.webrtc.PeerConnectionWrapper
import com.nextcloud.talk.webrtc.PeerConnectionWrapper.DataChannelMessageListener
import com.nextcloud.talk.webrtc.PeerConnectionWrapper.PeerConnectionObserver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
@@ -15,11 +18,24 @@ import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.webrtc.AudioTrack
import org.webrtc.MediaStream
import org.webrtc.PeerConnection.IceConnectionState
import org.webrtc.VideoTrack
@OptIn(ExperimentalCoroutinesApi::class)
@Suppress("TooManyFunctions")
class ParticipantHandlerTest {
private val testDispatcher = StandardTestDispatcher()
@@ -74,4 +90,175 @@ class ParticipantHandlerTest {
)
assertEquals(expectedState, handler.uiState.value)
}
@Test
fun `Speaking data channel messages update the speaking state`() {
handler = createHandler()
val (listener, _) = attachPeerConnectionWithObserver()
listener.onSpeaking()
assertTrue(handler.uiState.value.isSpeaking)
listener.onStoppedSpeaking()
assertFalse(handler.uiState.value.isSpeaking)
}
@Test
fun `Connected participant with audio who speaks is an active speaker`() {
handler = createHandler()
val (listener, observer) = attachPeerConnectionWithObserver()
connectWithAudio(listener, observer)
listener.onSpeaking()
assertTrue(handler.uiState.value.isActiveSpeaker)
}
@Test
fun `Muting audio hides the active speaker`() {
handler = createHandler()
val (listener, observer) = attachPeerConnectionWithObserver()
connectWithAudio(listener, observer)
listener.onSpeaking()
listener.onAudioOff()
assertFalse(handler.uiState.value.isActiveSpeaker)
}
@Test
fun `Speaking message while muted does not make an active speaker`() {
handler = createHandler()
val (listener, observer) = attachPeerConnectionWithObserver()
connectWithAudio(listener, observer)
listener.onAudioOff()
listener.onSpeaking()
assertFalse(handler.uiState.value.isActiveSpeaker)
}
@Test
fun `Temporary ICE disconnection hides the active speaker until reconnected`() {
handler = createHandler()
val (listener, observer) = attachPeerConnectionWithObserver()
connectWithAudio(listener, observer)
listener.onSpeaking()
observer.onIceConnectionStateChanged(IceConnectionState.DISCONNECTED)
assertFalse(handler.uiState.value.isActiveSpeaker)
observer.onIceConnectionStateChanged(IceConnectionState.CONNECTED)
assertTrue(handler.uiState.value.isActiveSpeaker)
}
@Test
fun `Removing the stream hides the active speaker`() {
handler = createHandler()
val (listener, observer) = attachPeerConnectionWithObserver()
observer.onIceConnectionStateChanged(IceConnectionState.CONNECTED)
val removedStream = MediaStream(0L).apply { audioTracks.add(mock<AudioTrack> {}) }
observer.onStreamAdded(removedStream)
listener.onSpeaking()
assertTrue(handler.uiState.value.isActiveSpeaker)
// The removed stream is passed to the observer and still lists its tracks.
observer.onStreamRemoved(removedStream)
assertFalse(handler.uiState.value.isActiveSpeaker)
assertFalse(handler.uiState.value.isAudioEnabled)
assertNull(handler.uiState.value.mediaStream)
}
@Test
fun `Removing the screen stream clears the screen share`() {
handler = createHandler()
val screenPeerConnectionWrapper: PeerConnectionWrapper = mock {}
handler.setScreenPeerConnection(screenPeerConnectionWrapper)
val observerCaptor = argumentCaptor<PeerConnectionObserver>()
verify(screenPeerConnectionWrapper).addObserver(observerCaptor.capture())
val removedStream = MediaStream(0L).apply { videoTracks.add(mock<VideoTrack> {}) }
observerCaptor.firstValue.onStreamAdded(removedStream)
assertTrue(handler.uiState.value.isScreenStreamEnabled)
// The removed stream is passed to the observer and still lists its tracks.
observerCaptor.firstValue.onStreamRemoved(removedStream)
assertFalse(handler.uiState.value.isScreenStreamEnabled)
assertNull(handler.uiState.value.screenMediaStream)
verify(onParticipantUnshareScreen).invoke("session-123")
}
@Test
fun `Removing an old stream after a new one was added keeps the new stream`() {
handler = createHandler()
val (listener, observer) = attachPeerConnectionWithObserver()
observer.onIceConnectionStateChanged(IceConnectionState.CONNECTED)
val oldStream = MediaStream(0L).apply { audioTracks.add(mock<AudioTrack> {}) }
val newStream = MediaStream(0L).apply { audioTracks.add(mock<AudioTrack> {}) }
observer.onStreamAdded(oldStream)
observer.onStreamAdded(newStream)
listener.onSpeaking()
observer.onStreamRemoved(oldStream)
assertSame(newStream, handler.uiState.value.mediaStream)
assertTrue(handler.uiState.value.isAudioEnabled)
assertTrue(handler.uiState.value.isActiveSpeaker)
}
@Test
fun `Removing an old screen stream after a new one was added keeps the screen share`() {
handler = createHandler()
val screenPeerConnectionWrapper: PeerConnectionWrapper = mock {}
handler.setScreenPeerConnection(screenPeerConnectionWrapper)
val observerCaptor = argumentCaptor<PeerConnectionObserver>()
verify(screenPeerConnectionWrapper).addObserver(observerCaptor.capture())
val oldStream = MediaStream(0L).apply { videoTracks.add(mock<VideoTrack> {}) }
val newStream = MediaStream(0L).apply { videoTracks.add(mock<VideoTrack> {}) }
observerCaptor.firstValue.onStreamAdded(oldStream)
observerCaptor.firstValue.onStreamAdded(newStream)
observerCaptor.firstValue.onStreamRemoved(oldStream)
assertSame(newStream, handler.uiState.value.screenMediaStream)
assertTrue(handler.uiState.value.isScreenStreamEnabled)
verify(onParticipantUnshareScreen, never()).invoke(any())
}
@Test
fun `Replacing the peer connection resets the speaking state`() {
handler = createHandler()
val (listener, _) = attachPeerConnectionWithObserver()
listener.onSpeaking()
handler.setPeerConnection(mock<PeerConnectionWrapper> {})
assertFalse(handler.uiState.value.isSpeaking)
}
private fun connectWithAudio(listener: DataChannelMessageListener, observer: PeerConnectionObserver) {
observer.onIceConnectionStateChanged(IceConnectionState.CONNECTED)
listener.onAudioOn()
}
private fun createHandler() =
ParticipantHandler(
sessionId = "session-123",
baseUrl = "",
roomToken = "",
signalingMessageReceiver = signalingMessageReceiver,
onParticipantShareScreen = onParticipantShareScreen,
onParticipantUnshareScreen = onParticipantUnshareScreen
)
private fun attachPeerConnectionWithObserver(): Pair<DataChannelMessageListener, PeerConnectionObserver> {
val peerConnectionWrapper: PeerConnectionWrapper = mock {}
handler.setPeerConnection(peerConnectionWrapper)
val listenerCaptor = argumentCaptor<DataChannelMessageListener>()
verify(peerConnectionWrapper).addListener(listenerCaptor.capture())
val observerCaptor = argumentCaptor<PeerConnectionObserver>()
verify(peerConnectionWrapper).addObserver(observerCaptor.capture())
return listenerCaptor.firstValue to observerCaptor.firstValue
}
}
@@ -0,0 +1,109 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
import com.nextcloud.talk.activities.ParticipantUiState
import org.junit.Assert.assertEquals
import org.junit.Test
class ParticipantOrderTest {
private val allKeys = setOf("a", "b", "c", "d")
@Test
fun `speaker that is not visible is moved to the front`() {
val result = promoteSpeakers(
speakers = listOf("a", "b"),
startedSpeaking = setOf("c"),
visibleSessionKeys = setOf("a"),
participantSessionKeys = allKeys
)
assertEquals(listOf("c", "a", "b"), result)
}
@Test
fun `existing speaker that is not visible is moved to the front`() {
val result = promoteSpeakers(
speakers = listOf("a", "b", "c"),
startedSpeaking = setOf("c"),
visibleSessionKeys = emptySet(),
participantSessionKeys = allKeys
)
assertEquals(listOf("c", "a", "b"), result)
}
@Test
fun `visible speaker is not promoted`() {
val result = promoteSpeakers(
speakers = listOf("a", "b"),
startedSpeaking = setOf("b", "c"),
visibleSessionKeys = setOf("b", "c"),
participantSessionKeys = allKeys
)
assertEquals(listOf("a", "b"), result)
}
@Test
fun `speakers that left the call are dropped`() {
val result = promoteSpeakers(
speakers = listOf("a", "x"),
startedSpeaking = setOf("y"),
visibleSessionKeys = emptySet(),
participantSessionKeys = allKeys
)
assertEquals(listOf("a"), result)
}
@Test
fun `speakers are sorted after screen sharers and before other participants in speaker order`() {
val participants = listOf(
participant("video", isStreamEnabled = true),
participant("speaker2"),
participant("screen", isScreenStreamEnabled = true),
participant("speaker1")
)
val result = sortParticipants(participants, speakers = listOf("speaker1", "speaker2"))
assertEquals(listOf("screen", "speaker1", "speaker2", "video"), result.map { it.sessionKey })
}
@Test
fun `participants without speaker priority keep the existing order`() {
val participants = listOf(
participant("muted"),
participant("audio", isAudioEnabled = true),
participant("video", isStreamEnabled = true)
)
val result = sortParticipants(participants, speakers = emptyList())
assertEquals(listOf("video", "audio", "muted"), result.map { it.sessionKey })
}
private fun participant(
sessionKey: String,
isStreamEnabled: Boolean = false,
isAudioEnabled: Boolean = false,
isScreenStreamEnabled: Boolean = false
) = ParticipantUiState(
sessionKey = sessionKey,
baseUrl = "",
roomToken = "",
nick = sessionKey,
isConnected = true,
isAudioEnabled = isAudioEnabled,
isStreamEnabled = isStreamEnabled,
isScreenStreamEnabled = isScreenStreamEnabled,
raisedHand = false,
isInternal = false
)
}
@@ -0,0 +1,184 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.call.components
import androidx.compose.ui.unit.dp
import org.junit.Assert.assertEquals
import org.junit.Test
@Suppress("TooManyFunctions")
class SpeakerViewOrderTest {
private val participants = listOf("a", "b", "c", "d")
@Test
fun `initial order promotes the participant currently speaking`() {
val result = initialSpeakerViewOrder(
participantSessionKeys = participants,
activeSpeakerSessionKeys = setOf("c"),
previouslyPromotedSessionKey = "b",
speakers = listOf("d")
)
assertEquals(listOf("c", "a", "b", "d"), result)
}
@Test
fun `initial order keeps the previously promoted participant when nobody speaks`() {
val result = initialSpeakerViewOrder(
participantSessionKeys = participants,
activeSpeakerSessionKeys = emptySet(),
previouslyPromotedSessionKey = "b",
speakers = listOf("d")
)
assertEquals(listOf("b", "a", "c", "d"), result)
}
@Test
fun `initial order falls back to the most recent speaker and then the first participant`() {
val withSpeaker = initialSpeakerViewOrder(
participantSessionKeys = participants,
activeSpeakerSessionKeys = emptySet(),
previouslyPromotedSessionKey = "left",
speakers = listOf("left", "d")
)
val withoutSpeaker = initialSpeakerViewOrder(
participantSessionKeys = participants,
activeSpeakerSessionKeys = emptySet(),
previouslyPromotedSessionKey = null,
speakers = emptyList()
)
assertEquals(listOf("d", "a", "b", "c"), withSpeaker)
assertEquals(participants, withoutSpeaker)
}
@Test
fun `participant that starts speaking is promoted and the previously promoted one leads the bar`() {
val result = update(order = participants, activeSpeakers = setOf("c"))
assertEquals(listOf("c", "a", "b", "d"), result)
}
@Test
fun `participant bar is ordered by the most recent speakers`() {
val afterC = update(order = participants, activeSpeakers = setOf("c"))
val afterD = update(order = afterC, activeSpeakers = setOf("d"), previousActiveSpeakers = setOf("c"))
val afterB = update(order = afterD, activeSpeakers = setOf("b"), previousActiveSpeakers = setOf("d"))
assertEquals(listOf("b", "d", "c", "a"), afterB)
}
@Test
fun `promotion is handed over to a participant still speaking when the promoted one stops`() {
val result = update(
order = participants,
activeSpeakers = setOf("d"),
previousActiveSpeakers = setOf("a", "d")
)
assertEquals(listOf("d", "a", "b", "c"), result)
}
@Test
fun `promoted participant stays when it stops speaking and nobody else speaks`() {
val result = update(order = participants, activeSpeakers = emptySet(), previousActiveSpeakers = setOf("a"))
assertEquals(participants, result)
}
@Test
fun `participant that stops speaking while not promoted does not change the order`() {
val result = update(
order = participants,
activeSpeakers = setOf("a"),
previousActiveSpeakers = setOf("a", "b")
)
assertEquals(participants, result)
}
@Test
fun `new participants are added to the end and participants that left are dropped`() {
val result = update(order = participants, participantSessionKeys = listOf("e", "a", "c", "d"))
assertEquals(listOf("a", "c", "d", "e"), result)
}
@Test
fun `new participant is promoted when the promoted participant left`() {
val result = update(
order = participants,
participantSessionKeys = listOf("b", "c", "d"),
speakers = listOf("c")
)
assertEquals(listOf("c", "b", "d"), result)
}
@Test
fun `first participant in the bar is promoted when the promoted participant left and nobody speaks`() {
val result = update(order = participants, participantSessionKeys = listOf("d", "c", "b"))
assertEquals(listOf("b", "c", "d"), result)
}
@Test
fun `participant shown first is promoted when several start speaking at once`() {
val result = update(
order = participants,
participantSessionKeys = listOf("d", "c", "b", "a"),
activeSpeakers = setOf("d", "c")
)
assertEquals(listOf("c", "a", "b", "d"), result)
}
@Test
fun `first participant is promoted when the order is empty`() {
val result = update(order = emptyList(), participantSessionKeys = listOf("a", "b"))
assertEquals(listOf("a", "b"), result)
}
@Test
fun `bar tiles keep their preferred width when all fit`() {
assertEquals(150.dp, participantBarTileWidth(availableWidth = 400.dp, tileCount = 2))
}
@Test
fun `bar tiles keep their preferred width when the cut tile is clearly visible`() {
// Two tiles fit fully, 84dp of the third one is visible
assertEquals(150.dp, participantBarTileWidth(availableWidth = 400.dp, tileCount = 3))
}
@Test
fun `bar tiles are narrowed so the next tile peeks in`() {
// Only 4dp of the third tile would be visible
assertEquals(144.dp, participantBarTileWidth(availableWidth = 320.dp, tileCount = 3))
}
@Test
fun `bar tiles are narrowed so all fit when only a few pixels are missing`() {
assertEquals(148.dp, participantBarTileWidth(availableWidth = 460.dp, tileCount = 3))
}
private fun update(
order: List<String>,
participantSessionKeys: List<String> = participants,
activeSpeakers: Set<String> = emptySet(),
previousActiveSpeakers: Set<String> = emptySet(),
speakers: List<String> = emptyList()
) = updateSpeakerViewOrder(
order = order,
participantSessionKeys = participantSessionKeys,
activeSpeakerSessionKeys = activeSpeakers,
previousActiveSpeakerSessionKeys = previousActiveSpeakers,
speakers = speakers
)
}
@@ -65,6 +65,20 @@ class DataChannelMessageNotifierTest {
verify(listener).onVideoOff()
}
@Test
fun testNotifySpeaking() {
notifier.addListener(listener)
notifier.notifySpeaking()
verify(listener).onSpeaking()
}
@Test
fun testNotifyStoppedSpeaking() {
notifier.addListener(listener)
notifier.notifyStoppedSpeaking()
verify(listener).onStoppedSpeaking()
}
@Test
fun testNotifyNickChanged() {
notifier.addListener(listener)
@@ -387,6 +387,20 @@ class PeerConnectionWrapperTest {
Mockito.verify(mockedDataChannelMessageListener).onVideoOff()
Mockito.verifyNoMoreInteractions(mockedDataChannelMessageListener)
statusDataChannelObserverArgumentCaptor.value.onMessage(
dataChannelMessageToBuffer(DataChannelMessageDto("speaking"))
)
Mockito.verify(mockedDataChannelMessageListener).onSpeaking()
Mockito.verifyNoMoreInteractions(mockedDataChannelMessageListener)
statusDataChannelObserverArgumentCaptor.value.onMessage(
dataChannelMessageToBuffer(DataChannelMessageDto("stoppedSpeaking"))
)
Mockito.verify(mockedDataChannelMessageListener).onStoppedSpeaking()
Mockito.verifyNoMoreInteractions(mockedDataChannelMessageListener)
}
@Test