From 5a27e0f3c9d895be914ac322e191762713274c9e Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Fri, 6 Nov 2026 16:31:16 +0530 Subject: [PATCH 1/7] feat(compose): play an HLS grant in HlsVideoRenderer Stock LivestreamPlayer shows the playlist when the backend grants HLS. Custom screens opt in by composing HlsVideoRenderer, and VideoRenderer stays WebRTC-only. --- gradle/libs.versions.toml | 5 + stream-video-android-core/build.gradle.kts | 5 + .../android/core/call/hls/HlsPlayback.kt | 167 ++++++++++++++++++ .../core/call/hls/Media3HlsPlaybackTest.kt | 104 +++++++++++ .../api/stream-video-android-ui-compose.api | 4 + .../build.gradle.kts | 5 + .../components/livestream/LivestreamPlayer.kt | 17 +- .../ui/components/video/HlsVideoRenderer.kt | 76 ++++++++ .../components/video/HlsVideoRendererTest.kt | 165 +++++++++++++++++ 9 files changed, 544 insertions(+), 4 deletions(-) create mode 100644 stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt create mode 100644 stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt create mode 100644 stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt create mode 100644 stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 60975b4ccf0..389005fd51d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -71,6 +71,8 @@ androidxUiAutomator = "2.4.0-alpha01" androidxContraintLayout = "2.1.4" androidxEspresso = "3.5.1" androidxMedia = "1.7.0" +# Same version stream-chat-android 7.13 depends on, so an app using both resolves one Media3. +media3 = "1.6.1" paparazzi = "1.3.4" robolectric = "4.11.1" junit = "4.13.2" @@ -176,6 +178,9 @@ stream-chat-offline = { group = "io.getstream", name = "stream-chat-android-offl stream-chat-state = { group = "io.getstream", name = "stream-chat-android-state", version.ref = "streamChat" } stream-chat-ui-utils = { group = "io.getstream", name = "stream-chat-android-ui-utils", version.ref = "streamChat" } +media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" } +media3-exoplayer-hls = { group = "androidx.media3", name = "media3-exoplayer-hls", version.ref = "media3" } + kotlin-test-junit = { group = "org.jetbrains.kotlin", name = "kotlin-test-junit", version.ref = "kotlinTestJunit" } kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } diff --git a/stream-video-android-core/build.gradle.kts b/stream-video-android-core/build.gradle.kts index 824346223c0..0f36273dc2f 100644 --- a/stream-video-android-core/build.gradle.kts +++ b/stream-video-android-core/build.gradle.kts @@ -223,6 +223,11 @@ dependencies { implementation(libs.androidx.media.media) + // HLS playback. ExoPlayer only; the UI layer supplies the surface, so media3-ui is not needed. + // Version matches stream-chat-android 7.13 so an app using both gets a single Media3. + implementation(libs.media3.exoplayer) + implementation(libs.media3.exoplayer.hls) + // unit tests testImplementation(libs.stream.result) testImplementation(libs.stream.result.call) diff --git a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt new file mode 100644 index 00000000000..0611092af20 --- /dev/null +++ b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.core.call.hls + +import android.content.Context +import android.view.SurfaceView +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.common.VideoSize +import androidx.media3.exoplayer.ExoPlayer +import io.getstream.video.android.core.Call +import io.getstream.video.android.core.internal.InternalStreamVideoApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** + * Plays one HLS playlist and draws it on a [SurfaceView] supplied by the UI layer. + * + * One instance is shared by every renderer of the same [Call], so two tiles cannot start two + * players for the same broadcast. + */ +@InternalStreamVideoApi +public interface HlsPlayback { + public val playlistUrl: String + + /** + * Display width divided by height of the decoded video, or null until the first frame size is + * known. A [SurfaceView] stretches frames to its own bounds, so the UI sizes the surface with it. + */ + public val videoAspectRatio: StateFlow + + public fun attach(surfaceView: SurfaceView) + + public fun detach(surfaceView: SurfaceView) + + public fun release() +} + +internal class Media3HlsPlayback( + context: Context, + override val playlistUrl: String, +) : HlsPlayback { + + internal val player: ExoPlayer = ExoPlayer.Builder(context.applicationContext).build() + + private val _videoAspectRatio = MutableStateFlow(null) + override val videoAspectRatio: StateFlow = _videoAspectRatio + + init { + try { + player.addListener( + object : Player.Listener { + override fun onVideoSizeChanged(videoSize: VideoSize) { + videoAspectRatioOf(videoSize)?.let { _videoAspectRatio.value = it } + } + }, + ) + player.setMediaItem(MediaItem.fromUri(playlistUrl)) + player.playWhenReady = true + player.prepare() + } catch (error: Throwable) { + player.release() + throw error + } + } + + private var attached: SurfaceView? = null + private var released = false + + override fun attach(surfaceView: SurfaceView) { + if (released || attached === surfaceView) return + attached?.let { player.clearVideoSurfaceView(it) } + player.setVideoSurfaceView(surfaceView) + attached = surfaceView + } + + override fun detach(surfaceView: SurfaceView) { + if (released || attached !== surfaceView) return + player.clearVideoSurfaceView(surfaceView) + attached = null + } + + override fun release() { + if (released) return + released = true + attached = null + player.release() + } +} + +/** Display aspect ratio of [videoSize], accounting for non-square pixels. Null while unknown. */ +internal fun videoAspectRatioOf(videoSize: VideoSize): Float? { + if (videoSize.width <= 0 || videoSize.height <= 0) return null + return videoSize.width * videoSize.pixelWidthHeightRatio / videoSize.height +} + +/** + * Hands out one [HlsPlayback] per [Call], reference counted across the renderers that show it. + */ +@InternalStreamVideoApi +public object HlsPlaybackStore { + + private class Ref(val playback: HlsPlayback, var count: Int) + + private val byCall = HashMap() + + /** + * Builds the [HlsPlayback] for a playlist. Tests replace this so renderers can be exercised + * without starting a decoder. + */ + public var factory: (Context, String) -> HlsPlayback = { context, playlistUrl -> + Media3HlsPlayback(context, playlistUrl) + } + + public fun acquire(context: Context, call: Call, playlistUrl: String): HlsPlayback { + synchronized(byCall) { + val existing = byCall[call] + if (existing != null && existing.playback.playlistUrl == playlistUrl) { + existing.count += 1 + return existing.playback + } + // Drop the previous player before creating the next one. A factory failure must not + // leave a released player in the map, or the next acquire would release it again. + if (existing != null) { + byCall.remove(call) + existing.playback.release() + } + val created = factory(context, playlistUrl) + byCall[call] = Ref(created, count = 1) + return created + } + } + + public fun release(call: Call, playback: HlsPlayback) { + synchronized(byCall) { + val existing = byCall[call] ?: return + if (existing.playback !== playback) return + existing.count -= 1 + if (existing.count <= 0) { + byCall.remove(call) + playback.release() + } + } + } + + /** Drops every player. Test-only. */ + public fun reset() { + synchronized(byCall) { + byCall.values.forEach { it.playback.release() } + byCall.clear() + } + } +} diff --git a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt new file mode 100644 index 00000000000..e287160a9c1 --- /dev/null +++ b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.core.call.hls + +import android.content.Context +import android.view.SurfaceView +import androidx.media3.common.VideoSize +import com.google.common.truth.Truth.assertThat +import io.getstream.video.android.core.Call +import io.mockk.mockk +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +internal class Media3HlsPlaybackTest { + + private companion object { + const val URL = "https://example.com/live.m3u8" + } + + private val defaultFactory = HlsPlaybackStore.factory + private val created = mutableListOf() + + @After + fun tearDown() { + HlsPlaybackStore.reset() + HlsPlaybackStore.factory = defaultFactory + } + + @Test + fun `one call shares a single player until the last renderer leaves`() { + val call = mockk() + HlsPlaybackStore.factory = { _, url -> FakeHlsPlayback(url).also { created += it } } + + val context = mockk(relaxed = true) + val first = HlsPlaybackStore.acquire(context, call, URL) + val second = HlsPlaybackStore.acquire(context, call, URL) + + assertThat(second).isSameInstanceAs(first) + assertThat(created).hasSize(1) + + HlsPlaybackStore.release(call, first) + assertThat(created.single().released).isFalse() + HlsPlaybackStore.release(call, second) + assertThat(created.single().released).isTrue() + } + + @Test + fun `exoplayer is pointed at the playlist`() { + val playback = Media3HlsPlayback( + context = RuntimeEnvironment.getApplication(), + playlistUrl = "https://example.com/live.m3u8", + ) + try { + assertThat(playback.player.currentMediaItem?.localConfiguration?.uri.toString()) + .isEqualTo("https://example.com/live.m3u8") + assertThat(playback.player.playWhenReady).isTrue() + } finally { + playback.release() + } + } + + @Test + fun `aspect ratio uses the display shape and stays unknown without a frame size`() { + assertThat(videoAspectRatioOf(VideoSize(1920, 1080))).isWithin(0.001f).of(16f / 9f) + assertThat(videoAspectRatioOf(VideoSize(960, 1080, 2f))).isWithin(0.001f).of(16f / 9f) + assertThat(videoAspectRatioOf(VideoSize.UNKNOWN)).isNull() + } + + private class FakeHlsPlayback( + override val playlistUrl: String, + ) : HlsPlayback { + override val videoAspectRatio = MutableStateFlow(null) + var released = false + + override fun attach(surfaceView: SurfaceView) = Unit + + override fun detach(surfaceView: SurfaceView) = Unit + + override fun release() { + released = true + } + } +} diff --git a/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api b/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api index fba5d264a19..d74c04bf882 100644 --- a/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api +++ b/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api @@ -2069,6 +2069,10 @@ public final class io/getstream/video/android/compose/ui/components/participants public static final fun ParticipantInformation (Lio/getstream/video/android/core/model/CallStatus;Ljava/util/List;ZLandroidx/compose/runtime/Composer;II)V } +public final class io/getstream/video/android/compose/ui/components/video/HlsVideoRendererKt { + public static final fun HlsVideoRenderer (Lio/getstream/video/android/core/Call;Landroidx/compose/ui/Modifier;Landroidx/compose/runtime/Composer;II)V +} + public final class io/getstream/video/android/compose/ui/components/video/VideoRendererKt { public static final fun VideoRenderer (Landroidx/compose/ui/Modifier;Lio/getstream/video/android/core/Call;Lio/getstream/video/android/core/ParticipantState$Media;Lio/getstream/video/android/compose/ui/components/video/config/VideoRendererConfig;Lkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V public static final fun VideoRenderer (Lio/getstream/video/android/core/Call;Lio/getstream/video/android/core/ParticipantState$Media;Landroidx/compose/ui/Modifier;Lio/getstream/video/android/compose/ui/components/video/VideoScalingType;Lkotlin/jvm/functions/Function3;Lkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V diff --git a/stream-video-android-ui-compose/build.gradle.kts b/stream-video-android-ui-compose/build.gradle.kts index 2b71cd58ce6..017f39f1ee9 100644 --- a/stream-video-android-ui-compose/build.gradle.kts +++ b/stream-video-android-ui-compose/build.gradle.kts @@ -25,6 +25,11 @@ android { defaultConfig { minSdk = libs.versions.minSdk.get().toInt() } + + testOptions { + unitTests.isIncludeAndroidResources = true + unitTests.isReturnDefaultValues = true + } } // Paparazzi renders and compresses every snapshot in the forked test worker, which defaults to a diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt index 02e5abcc569..0ad41ae33ab 100644 --- a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt +++ b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt @@ -29,11 +29,13 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.lifecycle.compose.collectAsStateWithLifecycle import io.getstream.video.android.compose.ui.components.livestream.state.LivestreamState +import io.getstream.video.android.compose.ui.components.video.HlsVideoRenderer import io.getstream.video.android.compose.ui.components.video.config.VideoRendererConfig import io.getstream.video.android.compose.ui.components.video.config.videoRenderConfig import io.getstream.video.android.core.Call import io.getstream.video.android.core.ParticipantState import io.getstream.video.android.core.RealtimeConnection +import io.getstream.video.android.core.model.PlaybackType import io.getstream.video.android.core.sorting.bySourcePriority import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine @@ -137,7 +139,9 @@ public fun LivestreamPlayer( ) val livestream by livestreamFlow.collectAsStateWithLifecycle(initialValue = null) + val playback by call.state.playbackType.collectAsStateWithLifecycle() val hostVideoAvailable = livestream?.enabled == true + val playingHls = playback is PlaybackType.Hls val connection by call.state.connection.collectAsStateWithLifecycle() val endedAt by call.state.endedAt.collectAsStateWithLifecycle() @@ -171,6 +175,7 @@ public fun LivestreamPlayer( videoRendererConfig = videoRendererConfig, livestreamFlow = livestreamFlow, hostVideoAvailable = hostVideoAvailable, + playingHls = playingHls, livestreamState = livestreamState, rendererContent = wrappedRenderer, overlayContent = wrappedOverlay, @@ -191,6 +196,7 @@ internal fun LivestreamPlayerImpl( videoRendererConfig: VideoRendererConfig, livestreamFlow: Flow, hostVideoAvailable: Boolean, + playingHls: Boolean, livestreamState: LivestreamState, rendererContent: @Composable BoxScope.(Call) -> Unit, overlayContent: @Composable BoxScope.(Call) -> Unit, @@ -225,10 +231,13 @@ internal fun LivestreamPlayerImpl( } LivestreamState.LIVE -> { - if (hostVideoAvailable) { - rendererContent.invoke(this, call) - } else { - liveStreamHostVideoNotAvailableContent.invoke(this, call) + when { + playingHls -> HlsVideoRenderer( + call = call, + modifier = Modifier.fillMaxSize(), + ) + hostVideoAvailable -> rendererContent.invoke(this, call) + else -> liveStreamHostVideoNotAvailableContent.invoke(this, call) } overlayContent.invoke(this, call) } diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt new file mode 100644 index 00000000000..09fa494b6c3 --- /dev/null +++ b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.compose.ui.components.video + +import android.view.SurfaceView +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.viewinterop.AndroidView +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import io.getstream.video.android.core.Call +import io.getstream.video.android.core.call.hls.HlsPlaybackStore +import io.getstream.video.android.core.model.PlaybackType + +/** + * Plays the call's HLS broadcast. + * + * Renders nothing while [Call.state.playbackType] is not [PlaybackType.Hls]. The playlist is on + * the call. One player is shared by every [HlsVideoRenderer] of the same call, and released when + * the last one leaves. + * + * The broadcast is an already composed layout, so the frame is fitted rather than cropped. + */ +@Composable +public fun HlsVideoRenderer( + call: Call, + modifier: Modifier = Modifier, +) { + val playbackType by call.state.playbackType.collectAsStateWithLifecycle() + val playlistUrl = (playbackType as? PlaybackType.Hls)?.playlistUrl ?: return + val context = LocalContext.current + val playback = remember(call, playlistUrl) { + HlsPlaybackStore.acquire(context, call, playlistUrl) + } + DisposableEffect(playback) { + onDispose { HlsPlaybackStore.release(call, playback) } + } + val aspectRatio by playback.videoAspectRatio.collectAsStateWithLifecycle() + Box( + modifier = modifier.background(Color.Black), + contentAlignment = Alignment.Center, + ) { + AndroidView( + factory = { viewContext -> + SurfaceView(viewContext).also { playback.attach(it) } + }, + onRelease = { surface -> playback.detach(surface) }, + modifier = (aspectRatio?.let { Modifier.aspectRatio(it) } ?: Modifier.fillMaxSize()) + .testTag("hls_video_renderer"), + ) + } +} diff --git a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt b/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt new file mode 100644 index 00000000000..b5e3c64e300 --- /dev/null +++ b/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.compose.ui.components.video + +import android.os.Looper +import android.view.SurfaceView +import android.view.View +import android.view.ViewGroup +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import com.google.common.truth.Truth.assertThat +import io.getstream.video.android.core.Call +import io.getstream.video.android.core.CallState +import io.getstream.video.android.core.call.hls.HlsPlayback +import io.getstream.video.android.core.call.hls.HlsPlaybackStore +import io.getstream.video.android.core.model.PlaybackType +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +internal class HlsVideoRendererTest { + + private companion object { + const val URL = "https://example.com/live.m3u8" + } + + private val defaultFactory = HlsPlaybackStore.factory + private val created = mutableListOf() + private val activities = mutableListOf>() + + @After + fun tearDown() { + activities.forEach { it.pause().stop().destroy() } + HlsPlaybackStore.reset() + HlsPlaybackStore.factory = defaultFactory + } + + @Test + fun `hls playback renders the playlist`() { + val playlistUrl = URL + HlsPlaybackStore.factory = { _, url -> + FakeHlsPlayback(url).also { created += it } + } + val playback = MutableStateFlow(PlaybackType.Hls(playlistUrl)) + + val activity = show(playback) + + assertThat(containsSurfaceView(activity.window.decorView)).isTrue() + assertThat(created.map { it.playlistUrl }).containsExactly(playlistUrl) + assertThat(created.single().attachCount).isEqualTo(1) + + playback.value = PlaybackType.WebRtc + shadowOf(Looper.getMainLooper()).idle() + + assertThat(containsSurfaceView(activity.window.decorView)).isFalse() + assertThat(created.single().released).isTrue() + } + + @Test + fun `hls surface keeps the stream aspect ratio instead of stretching to the tile`() { + HlsPlaybackStore.factory = { _, url -> + FakeHlsPlayback(url).also { + it.videoAspectRatio.value = 16f / 9f + created += it + } + } + val activity = show(MutableStateFlow(PlaybackType.Hls(URL))) + val container = activity.findViewById(android.R.id.content) + assertThat(container.height).isGreaterThan(container.width) + + val surface = activity.window.decorView.findSurfaceView()!! + assertThat(surface.width).isEqualTo(container.width) + assertThat(surface.width.toFloat() / surface.height).isWithin(0.02f).of(16f / 9f) + } + + @Test + fun `webrtc playback does not create an hls player`() { + HlsPlaybackStore.factory = { _, url -> + FakeHlsPlayback(url).also { created += it } + } + + val activity = show(MutableStateFlow(PlaybackType.WebRtc)) + + assertThat(containsSurfaceView(activity.window.decorView)).isFalse() + assertThat(created).isEmpty() + } + + private fun show(playback: MutableStateFlow): ComponentActivity { + val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() + activities += controller + val activity = controller.get() + activity.setContent { + HlsVideoRenderer( + call = call(playback), + modifier = Modifier.fillMaxSize(), + ) + } + shadowOf(Looper.getMainLooper()).idle() + return activity + } + + private fun call(playback: MutableStateFlow): Call { + val state = mockk() + every { state.playbackType } returns playback + return mockk { + every { this@mockk.state } returns state + } + } + + private fun containsSurfaceView(view: View): Boolean = view.findSurfaceView() != null + + private fun View.findSurfaceView(): SurfaceView? { + if (this is SurfaceView) return this + if (this is ViewGroup) { + for (index in 0 until childCount) { + getChildAt(index).findSurfaceView()?.let { return it } + } + } + return null + } + + private class FakeHlsPlayback( + override val playlistUrl: String, + ) : HlsPlayback { + override val videoAspectRatio = MutableStateFlow(null) + var attachCount = 0 + var released = false + + override fun attach(surfaceView: SurfaceView) { + attachCount += 1 + } + + override fun detach(surfaceView: SurfaceView) = Unit + + override fun release() { + released = true + } + } +} From 55df870f4ca28427991d50c4b7d21cb8d091306c Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Tue, 10 Nov 2026 14:22:30 +0530 Subject: [PATCH 2/7] fix(compose): acquire the HLS player in an effect and inject the store --- .../android/core/call/hls/HlsPlayback.kt | 22 +-- .../core/call/hls/Media3HlsPlaybackTest.kt | 93 +++++++-- .../ui/components/video/HlsVideoRenderer.kt | 48 +++-- .../components/video/HlsVideoRendererTest.kt | 177 +++++++++++++++--- 4 files changed, 263 insertions(+), 77 deletions(-) diff --git a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt index 0611092af20..27633691357 100644 --- a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt +++ b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt @@ -110,22 +110,18 @@ internal fun videoAspectRatioOf(videoSize: VideoSize): Float? { /** * Hands out one [HlsPlayback] per [Call], reference counted across the renderers that show it. + * + * @param factory Builds the [HlsPlayback] for a playlist. */ @InternalStreamVideoApi -public object HlsPlaybackStore { +public class HlsPlaybackStore( + private val factory: (Context, String) -> HlsPlayback = ::Media3HlsPlayback, +) { private class Ref(val playback: HlsPlayback, var count: Int) private val byCall = HashMap() - /** - * Builds the [HlsPlayback] for a playlist. Tests replace this so renderers can be exercised - * without starting a decoder. - */ - public var factory: (Context, String) -> HlsPlayback = { context, playlistUrl -> - Media3HlsPlayback(context, playlistUrl) - } - public fun acquire(context: Context, call: Call, playlistUrl: String): HlsPlayback { synchronized(byCall) { val existing = byCall[call] @@ -156,12 +152,4 @@ public object HlsPlaybackStore { } } } - - /** Drops every player. Test-only. */ - public fun reset() { - synchronized(byCall) { - byCall.values.forEach { it.playback.release() } - byCall.clear() - } - } } diff --git a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt index e287160a9c1..dff585fd854 100644 --- a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt +++ b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt @@ -23,7 +23,6 @@ import com.google.common.truth.Truth.assertThat import io.getstream.video.android.core.Call import io.mockk.mockk import kotlinx.coroutines.flow.MutableStateFlow -import org.junit.After import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -36,50 +35,112 @@ internal class Media3HlsPlaybackTest { private companion object { const val URL = "https://example.com/live.m3u8" + const val OTHER_URL = "https://example.com/other.m3u8" } - private val defaultFactory = HlsPlaybackStore.factory private val created = mutableListOf() - - @After - fun tearDown() { - HlsPlaybackStore.reset() - HlsPlaybackStore.factory = defaultFactory - } + private val store = HlsPlaybackStore { _, url -> FakeHlsPlayback(url).also { created += it } } + private val context = mockk(relaxed = true) @Test fun `one call shares a single player until the last renderer leaves`() { val call = mockk() - HlsPlaybackStore.factory = { _, url -> FakeHlsPlayback(url).also { created += it } } - val context = mockk(relaxed = true) - val first = HlsPlaybackStore.acquire(context, call, URL) - val second = HlsPlaybackStore.acquire(context, call, URL) + val first = store.acquire(context, call, URL) + val second = store.acquire(context, call, URL) assertThat(second).isSameInstanceAs(first) assertThat(created).hasSize(1) - HlsPlaybackStore.release(call, first) + store.release(call, first) assertThat(created.single().released).isFalse() - HlsPlaybackStore.release(call, second) + store.release(call, second) assertThat(created.single().released).isTrue() } + @Test + fun `a new playlist releases the previous player before the next one starts`() { + val call = mockk() + + val old = store.acquire(context, call, URL) + val new = store.acquire(context, call, OTHER_URL) + + assertThat(new).isNotSameInstanceAs(old) + assertThat(created.map { it.playlistUrl }).containsExactly(URL, OTHER_URL).inOrder() + assertThat(created[0].released).isTrue() + assertThat(created[1].released).isFalse() + } + + @Test + fun `releasing a replaced player leaves the current one playing`() { + val call = mockk() + val old = store.acquire(context, call, URL) + store.acquire(context, call, OTHER_URL) + + store.release(call, old) + + assertThat(created[1].released).isFalse() + } + + @Test + fun `different calls get different players`() { + val first = store.acquire(context, mockk(), URL) + val second = store.acquire(context, mockk(), URL) + + assertThat(second).isNotSameInstanceAs(first) + assertThat(created).hasSize(2) + } + + @Test + fun `a failing factory leaves nothing behind for the next acquire`() { + val call = mockk() + var fail = true + val failing = HlsPlaybackStore { _, url -> + if (fail) error("decoder unavailable") + FakeHlsPlayback(url).also { created += it } + } + + assertThat(runCatching { failing.acquire(context, call, URL) }.isFailure).isTrue() + fail = false + failing.acquire(context, call, URL) + + assertThat(created).hasSize(1) + assertThat(created.single().released).isFalse() + } + @Test fun `exoplayer is pointed at the playlist`() { val playback = Media3HlsPlayback( context = RuntimeEnvironment.getApplication(), - playlistUrl = "https://example.com/live.m3u8", + playlistUrl = URL, ) try { assertThat(playback.player.currentMediaItem?.localConfiguration?.uri.toString()) - .isEqualTo("https://example.com/live.m3u8") + .isEqualTo(URL) assertThat(playback.player.playWhenReady).isTrue() } finally { playback.release() } } + @Test + fun `swapping surfaces and calling after release does not throw`() { + val application = RuntimeEnvironment.getApplication() + val playback = Media3HlsPlayback(context = application, playlistUrl = URL) + val first = SurfaceView(application) + val second = SurfaceView(application) + + playback.attach(first) + playback.attach(first) + playback.attach(second) + playback.detach(first) + playback.detach(second) + playback.release() + playback.release() + playback.attach(first) + playback.detach(first) + } + @Test fun `aspect ratio uses the display shape and stays unknown without a frame size`() { assertThat(videoAspectRatioOf(VideoSize(1920, 1080))).isWithin(0.001f).of(16f / 9f) diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt index 09fa494b6c3..ddfefb23306 100644 --- a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt +++ b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt @@ -24,7 +24,10 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -33,6 +36,7 @@ import androidx.compose.ui.platform.testTag import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.compose.collectAsStateWithLifecycle import io.getstream.video.android.core.Call +import io.getstream.video.android.core.call.hls.HlsPlayback import io.getstream.video.android.core.call.hls.HlsPlaybackStore import io.getstream.video.android.core.model.PlaybackType @@ -49,28 +53,44 @@ import io.getstream.video.android.core.model.PlaybackType public fun HlsVideoRenderer( call: Call, modifier: Modifier = Modifier, +) { + HlsVideoRendererImpl(call = call, store = defaultHlsPlaybackStore, modifier = modifier) +} + +private val defaultHlsPlaybackStore = HlsPlaybackStore() + +@Composable +internal fun HlsVideoRendererImpl( + call: Call, + store: HlsPlaybackStore, + modifier: Modifier = Modifier, ) { val playbackType by call.state.playbackType.collectAsStateWithLifecycle() val playlistUrl = (playbackType as? PlaybackType.Hls)?.playlistUrl ?: return val context = LocalContext.current - val playback = remember(call, playlistUrl) { - HlsPlaybackStore.acquire(context, call, playlistUrl) - } - DisposableEffect(playback) { - onDispose { HlsPlaybackStore.release(call, playback) } + var playback by remember(store, call, playlistUrl) { mutableStateOf(null) } + // Acquired here rather than in remember: an abandoned composition never runs onDispose, + // so a player started during composition would never be released. + DisposableEffect(store, call, playlistUrl) { + val acquired = store.acquire(context, call, playlistUrl) + playback = acquired + onDispose { store.release(call, acquired) } } - val aspectRatio by playback.videoAspectRatio.collectAsStateWithLifecycle() + val current = playback ?: return + val aspectRatio by current.videoAspectRatio.collectAsStateWithLifecycle() Box( modifier = modifier.background(Color.Black), contentAlignment = Alignment.Center, ) { - AndroidView( - factory = { viewContext -> - SurfaceView(viewContext).also { playback.attach(it) } - }, - onRelease = { surface -> playback.detach(surface) }, - modifier = (aspectRatio?.let { Modifier.aspectRatio(it) } ?: Modifier.fillMaxSize()) - .testTag("hls_video_renderer"), - ) + key(current) { + AndroidView( + factory = { viewContext -> + SurfaceView(viewContext).also { current.attach(it) } + }, + onRelease = { surface -> current.detach(surface) }, + modifier = (aspectRatio?.let { Modifier.aspectRatio(it) } ?: Modifier.fillMaxSize()) + .testTag("hls_video_renderer"), + ) + } } } diff --git a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt b/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt index b5e3c64e300..7faf4e12468 100644 --- a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt +++ b/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt @@ -16,14 +16,26 @@ package io.getstream.video.android.compose.ui.components.video +import android.os.Handler import android.os.Looper import android.view.SurfaceView import android.view.View import android.view.ViewGroup import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.AbstractApplier +import androidx.compose.runtime.BroadcastFrameClock +import androidx.compose.runtime.Composition +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Recomposer +import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalContext +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.compose.LocalLifecycleOwner import com.google.common.truth.Truth.assertThat import io.getstream.video.android.core.Call import io.getstream.video.android.core.CallState @@ -32,15 +44,23 @@ import io.getstream.video.android.core.call.hls.HlsPlaybackStore import io.getstream.video.android.core.model.PlaybackType import io.mockk.every import io.mockk.mockk +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.android.asCoroutineDispatcher +import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch import org.junit.After import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment import org.robolectric.Shadows.shadowOf import org.robolectric.android.controller.ActivityController import org.robolectric.annotation.Config +import java.time.Duration +import kotlin.coroutines.EmptyCoroutineContext @RunWith(RobolectricTestRunner::class) @Config(sdk = [33]) @@ -48,48 +68,72 @@ internal class HlsVideoRendererTest { private companion object { const val URL = "https://example.com/live.m3u8" + const val OTHER_URL = "https://example.com/other.m3u8" + const val FRAMES = 5 + const val FRAME_MS = 20L } - private val defaultFactory = HlsPlaybackStore.factory private val created = mutableListOf() + private var aspectRatio: Float? = null + private val store = HlsPlaybackStore { _, url -> + FakeHlsPlayback(url).also { + it.videoAspectRatio.value = aspectRatio + created += it + } + } private val activities = mutableListOf>() + // Compose caches the window recomposer's dispatcher per thread, bound to the first test's + // Choreographer, so later tests would never get a frame. Each test drives its own. + private val frameClock = BroadcastFrameClock() + private val recomposerScope = CoroutineScope( + Handler(Looper.getMainLooper()).asCoroutineDispatcher() + frameClock + Job(), + ) + private val recomposer = Recomposer(recomposerScope.coroutineContext).also { recomposer -> + recomposerScope.launch { recomposer.runRecomposeAndApplyChanges() } + } + @After fun tearDown() { - activities.forEach { it.pause().stop().destroy() } - HlsPlaybackStore.reset() - HlsPlaybackStore.factory = defaultFactory + activities.forEach { runCatching { it.pause().stop().destroy() } } + recomposer.cancel() + recomposerScope.cancel() } @Test fun `hls playback renders the playlist`() { - val playlistUrl = URL - HlsPlaybackStore.factory = { _, url -> - FakeHlsPlayback(url).also { created += it } - } - val playback = MutableStateFlow(PlaybackType.Hls(playlistUrl)) + val playback = MutableStateFlow(PlaybackType.Hls(URL)) val activity = show(playback) assertThat(containsSurfaceView(activity.window.decorView)).isTrue() - assertThat(created.map { it.playlistUrl }).containsExactly(playlistUrl) + assertThat(created.map { it.playlistUrl }).containsExactly(URL) assertThat(created.single().attachCount).isEqualTo(1) playback.value = PlaybackType.WebRtc - shadowOf(Looper.getMainLooper()).idle() + settle() assertThat(containsSurfaceView(activity.window.decorView)).isFalse() assertThat(created.single().released).isTrue() } + @Test + fun `a new playlist attaches the new player and releases the old one`() { + val playback = MutableStateFlow(PlaybackType.Hls(URL)) + show(playback) + + playback.value = PlaybackType.Hls(OTHER_URL) + settle() + + assertThat(created.map { it.playlistUrl }).containsExactly(URL, OTHER_URL).inOrder() + assertThat(created[0].released).isTrue() + assertThat(created[1].released).isFalse() + assertThat(created[1].attachCount).isEqualTo(1) + } + @Test fun `hls surface keeps the stream aspect ratio instead of stretching to the tile`() { - HlsPlaybackStore.factory = { _, url -> - FakeHlsPlayback(url).also { - it.videoAspectRatio.value = 16f / 9f - created += it - } - } + aspectRatio = 16f / 9f val activity = show(MutableStateFlow(PlaybackType.Hls(URL))) val container = activity.findViewById(android.R.id.content) assertThat(container.height).isGreaterThan(container.width) @@ -101,28 +145,87 @@ internal class HlsVideoRendererTest { @Test fun `webrtc playback does not create an hls player`() { - HlsPlaybackStore.factory = { _, url -> - FakeHlsPlayback(url).also { created += it } - } - val activity = show(MutableStateFlow(PlaybackType.WebRtc)) assertThat(containsSurfaceView(activity.window.decorView)).isFalse() assertThat(created).isEmpty() } - private fun show(playback: MutableStateFlow): ComponentActivity { + @Test + fun `an abandoned composition does not start a player`() { + val call = call(MutableStateFlow(PlaybackType.Hls(URL))) + // A private recomposer keeps the failing composition away from the main-thread one + // that the activity-based tests share. + val recomposer = Recomposer(EmptyCoroutineContext) + val composition = Composition(NoNodeApplier(), recomposer) + + val result = runCatching { + composition.setContent { + CompositionLocalProvider( + LocalContext provides RuntimeEnvironment.getApplication(), + LocalLifecycleOwner provides ResumedLifecycleOwner(), + ) { + HlsVideoRendererImpl(call = call, store = store) + } + error("composition abandoned before it was applied") + } + } + runCatching { composition.dispose() } + recomposer.cancel() + + assertThat(result.isFailure).isTrue() + assertThat(created).isEmpty() + } + + @Test + fun `two renderers of one call share a player and the second release stops it`() { + val playback = MutableStateFlow(PlaybackType.Hls(URL)) + val call = call(playback) + + val first = show(call) + val second = show(call) + + assertThat(created).hasSize(1) + activities.remove(first.second) + first.second.pause().stop().destroy() + assertThat(created.single().released).isFalse() + + activities.remove(second.second) + second.second.pause().stop().destroy() + assertThat(created.single().released).isTrue() + } + + private fun show(playback: MutableStateFlow): ComponentActivity = + show(call(playback)).first + + private fun show(call: Call): Pair> { val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() activities += controller val activity = controller.get() - activity.setContent { - HlsVideoRenderer( - call = call(playback), - modifier = Modifier.fillMaxSize(), - ) + val view = ComposeView(activity).apply { + setParentCompositionContext(recomposer) + setContent { + HlsVideoRendererImpl( + call = call, + store = store, + modifier = Modifier.fillMaxSize(), + ) + } + } + activity.setContentView(view) + settle() + return activity to controller + } + + /** Runs the frames that follow, so state written by an effect is composed and laid out. */ + private fun settle() { + val looper = shadowOf(Looper.getMainLooper()) + repeat(FRAMES) { + Snapshot.sendApplyNotifications() + looper.idle() + frameClock.sendFrame(System.nanoTime()) + looper.idleFor(Duration.ofMillis(FRAME_MS)) } - shadowOf(Looper.getMainLooper()).idle() - return activity } private fun call(playback: MutableStateFlow): Call { @@ -145,6 +248,20 @@ internal class HlsVideoRendererTest { return null } + private class NoNodeApplier : AbstractApplier(Unit) { + override fun insertTopDown(index: Int, instance: Unit) = Unit + override fun insertBottomUp(index: Int, instance: Unit) = Unit + override fun remove(index: Int, count: Int) = Unit + override fun move(from: Int, to: Int, count: Int) = Unit + override fun onClear() = Unit + } + + private class ResumedLifecycleOwner : LifecycleOwner { + override val lifecycle: Lifecycle = LifecycleRegistry.createUnsafe(this).apply { + currentState = Lifecycle.State.RESUMED + } + } + private class FakeHlsPlayback( override val playlistUrl: String, ) : HlsPlayback { From 565093ff7c2052b02c57b90fc3dc6976622004de Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Mon, 16 Nov 2026 16:59:51 +0530 Subject: [PATCH 3/7] fix(compose): mute HLS playback from the livestream audio toggle --- .../android/core/call/hls/HlsPlayback.kt | 11 ++++++- .../core/call/hls/Media3HlsPlaybackTest.kt | 21 ++++++++++++++ .../api/stream-video-android-ui-compose.api | 2 +- .../components/livestream/LivestreamPlayer.kt | 3 ++ .../ui/components/video/HlsVideoRenderer.kt | 16 +++++++++- .../components/video/HlsVideoRendererTest.kt | 29 ++++++++++++++++++- 6 files changed, 78 insertions(+), 4 deletions(-) diff --git a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt index 27633691357..553ee95fd13 100644 --- a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt +++ b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt @@ -31,7 +31,8 @@ import kotlinx.coroutines.flow.StateFlow * Plays one HLS playlist and draws it on a [SurfaceView] supplied by the UI layer. * * One instance is shared by every renderer of the same [Call], so two tiles cannot start two - * players for the same broadcast. + * players for the same broadcast. The player draws to one surface at a time: showing the same call + * in two renderers at once is not supported. */ @InternalStreamVideoApi public interface HlsPlayback { @@ -47,6 +48,9 @@ public interface HlsPlayback { public fun detach(surfaceView: SurfaceView) + /** Mutes the broadcast audio when [enabled] is false. Playback continues either way. */ + public fun setAudioEnabled(enabled: Boolean) + public fun release() } @@ -94,6 +98,11 @@ internal class Media3HlsPlayback( attached = null } + override fun setAudioEnabled(enabled: Boolean) { + if (released) return + player.volume = if (enabled) 1f else 0f + } + override fun release() { if (released) return released = true diff --git a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt index dff585fd854..82441acbae2 100644 --- a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt +++ b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt @@ -141,6 +141,25 @@ internal class Media3HlsPlaybackTest { playback.detach(first) } + @Test + fun `disabling audio mutes the player without stopping it`() { + val playback = Media3HlsPlayback( + context = RuntimeEnvironment.getApplication(), + playlistUrl = URL, + ) + try { + playback.setAudioEnabled(false) + assertThat(playback.player.volume).isEqualTo(0f) + assertThat(playback.player.playWhenReady).isTrue() + + playback.setAudioEnabled(true) + assertThat(playback.player.volume).isEqualTo(1f) + } finally { + playback.release() + } + playback.setAudioEnabled(false) + } + @Test fun `aspect ratio uses the display shape and stays unknown without a frame size`() { assertThat(videoAspectRatioOf(VideoSize(1920, 1080))).isWithin(0.001f).of(16f / 9f) @@ -158,6 +177,8 @@ internal class Media3HlsPlaybackTest { override fun detach(surfaceView: SurfaceView) = Unit + override fun setAudioEnabled(enabled: Boolean) = Unit + override fun release() { released = true } diff --git a/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api b/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api index d74c04bf882..8b78bf9793d 100644 --- a/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api +++ b/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api @@ -2070,7 +2070,7 @@ public final class io/getstream/video/android/compose/ui/components/participants } public final class io/getstream/video/android/compose/ui/components/video/HlsVideoRendererKt { - public static final fun HlsVideoRenderer (Lio/getstream/video/android/core/Call;Landroidx/compose/ui/Modifier;Landroidx/compose/runtime/Composer;II)V + public static final fun HlsVideoRenderer (Lio/getstream/video/android/core/Call;Landroidx/compose/ui/Modifier;ZLandroidx/compose/runtime/Composer;II)V } public final class io/getstream/video/android/compose/ui/components/video/VideoRendererKt { diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt index 0ad41ae33ab..bd683884c9e 100644 --- a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt +++ b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt @@ -176,6 +176,7 @@ public fun LivestreamPlayer( livestreamFlow = livestreamFlow, hostVideoAvailable = hostVideoAvailable, playingHls = playingHls, + isAudioEnabled = isAudioEnabled, livestreamState = livestreamState, rendererContent = wrappedRenderer, overlayContent = wrappedOverlay, @@ -197,6 +198,7 @@ internal fun LivestreamPlayerImpl( livestreamFlow: Flow, hostVideoAvailable: Boolean, playingHls: Boolean, + isAudioEnabled: Boolean, livestreamState: LivestreamState, rendererContent: @Composable BoxScope.(Call) -> Unit, overlayContent: @Composable BoxScope.(Call) -> Unit, @@ -235,6 +237,7 @@ internal fun LivestreamPlayerImpl( playingHls -> HlsVideoRenderer( call = call, modifier = Modifier.fillMaxSize(), + audioEnabled = isAudioEnabled, ) hostVideoAvailable -> rendererContent.invoke(this, call) else -> liveStreamHostVideoNotAvailableContent.invoke(this, call) diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt index ddfefb23306..89f64df667b 100644 --- a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt +++ b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt @@ -23,6 +23,7 @@ import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf @@ -48,13 +49,24 @@ import io.getstream.video.android.core.model.PlaybackType * the last one leaves. * * The broadcast is an already composed layout, so the frame is fitted rather than cropped. + * + * [Call.setIncomingAudioEnabled] only reaches WebRTC tracks, so HLS audio is muted through + * [audioEnabled] instead. + * + * @param audioEnabled Plays the broadcast audio when true, mutes it when false. */ @Composable public fun HlsVideoRenderer( call: Call, modifier: Modifier = Modifier, + audioEnabled: Boolean = true, ) { - HlsVideoRendererImpl(call = call, store = defaultHlsPlaybackStore, modifier = modifier) + HlsVideoRendererImpl( + call = call, + store = defaultHlsPlaybackStore, + modifier = modifier, + audioEnabled = audioEnabled, + ) } private val defaultHlsPlaybackStore = HlsPlaybackStore() @@ -64,6 +76,7 @@ internal fun HlsVideoRendererImpl( call: Call, store: HlsPlaybackStore, modifier: Modifier = Modifier, + audioEnabled: Boolean = true, ) { val playbackType by call.state.playbackType.collectAsStateWithLifecycle() val playlistUrl = (playbackType as? PlaybackType.Hls)?.playlistUrl ?: return @@ -77,6 +90,7 @@ internal fun HlsVideoRendererImpl( onDispose { store.release(call, acquired) } } val current = playback ?: return + SideEffect { current.setAudioEnabled(audioEnabled) } val aspectRatio by current.videoAspectRatio.collectAsStateWithLifecycle() Box( modifier = modifier.background(Color.Black), diff --git a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt b/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt index 7faf4e12468..ef9ebbd4592 100644 --- a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt +++ b/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt @@ -28,6 +28,8 @@ import androidx.compose.runtime.BroadcastFrameClock import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Recomposer +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView @@ -195,10 +197,29 @@ internal class HlsVideoRendererTest { assertThat(created.single().released).isTrue() } + @Test + fun `the audio toggle mutes the player and a replacement player starts muted`() { + val playback = MutableStateFlow(PlaybackType.Hls(URL)) + val audioEnabled = mutableStateOf(true) + show(call(playback), audioEnabled) + assertThat(created.single().audioEnabled).isTrue() + + audioEnabled.value = false + settle() + assertThat(created.single().audioEnabled).isFalse() + + playback.value = PlaybackType.Hls(OTHER_URL) + settle() + assertThat(created[1].audioEnabled).isFalse() + } + private fun show(playback: MutableStateFlow): ComponentActivity = show(call(playback)).first - private fun show(call: Call): Pair> { + private fun show( + call: Call, + audioEnabled: State = mutableStateOf(true), + ): Pair> { val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() activities += controller val activity = controller.get() @@ -209,6 +230,7 @@ internal class HlsVideoRendererTest { call = call, store = store, modifier = Modifier.fillMaxSize(), + audioEnabled = audioEnabled.value, ) } } @@ -268,6 +290,7 @@ internal class HlsVideoRendererTest { override val videoAspectRatio = MutableStateFlow(null) var attachCount = 0 var released = false + var audioEnabled: Boolean? = null override fun attach(surfaceView: SurfaceView) { attachCount += 1 @@ -275,6 +298,10 @@ internal class HlsVideoRendererTest { override fun detach(surfaceView: SurfaceView) = Unit + override fun setAudioEnabled(enabled: Boolean) { + audioEnabled = enabled + } + override fun release() { released = true } From 5031fa79714a2b24b9daddead3f8a967a5c2d32d Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Thu, 19 Nov 2026 19:59:35 +0530 Subject: [PATCH 4/7] feat(hls): move ExoPlayer playback and renderer into an opt-in module Adds stream-video-android-hls with ExoHlsPlayerFactory and the Compose HlsVideoRenderer. Core and ui-compose no longer depend on Media3, and the process-wide playback store is gone: the renderer attaches to the call's player and detaches (pauses) on dispose, while the SDK releases it on leave. The demo app registers the factory and shows a minimal HLS viewer screen when a call joins over HLS. --- demo-app/build.gradle.kts | 1 + .../getstream/video/android/CallActivity.kt | 35 +++- .../android/ui/call/DemoHlsViewerScreen.kt | 65 ++++++ .../android/util/StreamVideoInitHelper.kt | 2 + scripts/release/local-release | 1 + settings.gradle.kts | 1 + stream-video-android-bom/build.gradle.kts | 1 + stream-video-android-core/build.gradle.kts | 5 - .../android/core/call/hls/HlsPlayback.kt | 164 --------------- .../core/call/hls/Media3HlsPlaybackTest.kt | 186 ------------------ .../api/stream-video-android-hls.api | 10 + stream-video-android-hls/build.gradle.kts | 60 ++++++ .../src/main/AndroidManifest.xml | 17 ++ .../video/android/hls/ExoHlsPlayer.kt | 156 +++++++++++++++ .../video/android/hls}/HlsVideoRenderer.kt | 53 +---- .../video/android/hls/ExoHlsPlayerTest.kt | 117 +++++++++++ .../android/hls}/HlsVideoRendererTest.kt | 186 ++++++------------ .../api/stream-video-android-ui-compose.api | 4 - .../build.gradle.kts | 5 - .../components/livestream/LivestreamPlayer.kt | 20 +- 20 files changed, 537 insertions(+), 552 deletions(-) create mode 100644 demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt delete mode 100644 stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt delete mode 100644 stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt create mode 100644 stream-video-android-hls/api/stream-video-android-hls.api create mode 100644 stream-video-android-hls/build.gradle.kts create mode 100644 stream-video-android-hls/src/main/AndroidManifest.xml create mode 100644 stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt rename {stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video => stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls}/HlsVideoRenderer.kt (55%) create mode 100644 stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt rename {stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video => stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls}/HlsVideoRendererTest.kt (50%) diff --git a/demo-app/build.gradle.kts b/demo-app/build.gradle.kts index 95c8d976467..09a52bf7384 100644 --- a/demo-app/build.gradle.kts +++ b/demo-app/build.gradle.kts @@ -213,6 +213,7 @@ dependencies { implementation(project(":stream-video-android-ui-compose")) implementation(project(":stream-video-android-ui-xml")) implementation(project(":stream-video-android-filters-video")) + implementation(project(":stream-video-android-hls")) compileOnly(project(":stream-video-android-previewdata")) implementation(libs.androidx.media.media) diff --git a/demo-app/src/main/kotlin/io/getstream/video/android/CallActivity.kt b/demo-app/src/main/kotlin/io/getstream/video/android/CallActivity.kt index 95fbf2ff0c9..ff9c0de77aa 100644 --- a/demo-app/src/main/kotlin/io/getstream/video/android/CallActivity.kt +++ b/demo-app/src/main/kotlin/io/getstream/video/android/CallActivity.kt @@ -28,6 +28,7 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import io.getstream.chat.android.client.ChatClient import io.getstream.chat.android.models.Filters import io.getstream.chat.android.models.querysort.QuerySortByField @@ -42,9 +43,11 @@ import io.getstream.video.android.core.StreamVideo import io.getstream.video.android.core.call.state.CallAction import io.getstream.video.android.core.e2ee.E2EEEventType import io.getstream.video.android.core.e2ee.StreamEncryptionManager +import io.getstream.video.android.core.model.PlaybackType import io.getstream.video.android.datastore.delegate.StreamUserDataStore import io.getstream.video.android.ui.call.CallScreen import io.getstream.video.android.ui.call.DemoComponentFactory +import io.getstream.video.android.ui.call.DemoHlsViewerScreen import io.getstream.video.android.ui.common.StreamActivityUiDelegate import io.getstream.video.android.ui.common.StreamCallActivity import io.getstream.video.android.ui.common.StreamCallActivityConfiguration @@ -83,7 +86,7 @@ class CallActivity : ComposeStreamCallActivity() { private const val E2EE_TAG = "CallActivityE2EE" } - override val uiDelegate: StreamActivityUiDelegate = StreamDemoUiDelegate() + override val uiDelegate: StreamActivityUiDelegate = DemoHlsUiDelegate() var observeCallReadyToJoinJob: Job? = null var observeRingingJob: Job? = null private val previousRingingStates = ConcurrentHashMap.newKeySet() @@ -233,7 +236,35 @@ class CallActivity : ComposeStreamCallActivity() { DemoE2eeKeys.remember(call.cid, passphrase, manager) } - private class StreamDemoUiDelegate : StreamCallActivityComposeDelegate() { + /** + * Shows [DemoHlsViewerScreen] when the call was joined as an HLS viewer, and the regular demo + * UI otherwise. + */ + private class DemoHlsUiDelegate : StreamDemoUiDelegate() { + + // Kotlin 1.9 cannot call super on a member extension, so the default root comes from a + // delegate that does not override it. + private val webRtcDelegate = StreamDemoUiDelegate() + + @StreamCallActivityDelicateApi + @Composable + override fun StreamCallActivity.RootContent(call: Call) { + val playbackType by call.state.playbackType.collectAsStateWithLifecycle() + if (playbackType is PlaybackType.Hls) { + DemoHlsViewerScreen( + call = call, + onLeave = { + leave(call) + safeFinish() + }, + ) + } else { + with(webRtcDelegate) { RootContent(call) } + } + } + } + + private open class StreamDemoUiDelegate : StreamCallActivityComposeDelegate() { override val componentFactory = DemoComponentFactory diff --git a/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt b/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt new file mode 100644 index 00000000000..32e3fd7df39 --- /dev/null +++ b/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.ui.call + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import io.getstream.video.android.compose.ui.components.call.controls.actions.LeaveCallAction +import io.getstream.video.android.compose.ui.components.call.controls.actions.ToggleSpeakerphoneAction +import io.getstream.video.android.core.Call +import io.getstream.video.android.hls.HlsVideoRenderer + +/** + * The viewer screen for a call the backend serves as HLS. It is what an app with its own UI + * writes: the broadcast, a mute toggle and a leave button. + */ +@Composable +fun DemoHlsViewerScreen( + call: Call, + onLeave: () -> Unit, +) { + var audioEnabled by rememberSaveable { mutableStateOf(true) } + Box(modifier = Modifier.fillMaxSize()) { + HlsVideoRenderer( + call = call, + modifier = Modifier.fillMaxSize(), + audioEnabled = audioEnabled, + ) + Row( + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(24.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + ToggleSpeakerphoneAction(isSpeakerphoneEnabled = audioEnabled) { + audioEnabled = it.isEnabled + } + LeaveCallAction { onLeave() } + } + } +} diff --git a/demo-app/src/main/kotlin/io/getstream/video/android/util/StreamVideoInitHelper.kt b/demo-app/src/main/kotlin/io/getstream/video/android/util/StreamVideoInitHelper.kt index 08b23e89fc3..856a994f5ad 100644 --- a/demo-app/src/main/kotlin/io/getstream/video/android/util/StreamVideoInitHelper.kt +++ b/demo-app/src/main/kotlin/io/getstream/video/android/util/StreamVideoInitHelper.kt @@ -50,6 +50,7 @@ import io.getstream.video.android.core.sounds.enableRingingCallVibrationConfig import io.getstream.video.android.data.services.stream.GetAuthDataResponse import io.getstream.video.android.data.services.stream.StreamService import io.getstream.video.android.datastore.delegate.StreamUserDataStore +import io.getstream.video.android.hls.ExoHlsPlayerFactory import io.getstream.video.android.model.ApiKey import io.getstream.video.android.model.StreamCallId import io.getstream.video.android.model.User @@ -506,6 +507,7 @@ object StreamVideoInitHelper { telecomConfig = TelecomConfig(context.packageName), connectOnInit = false, rejectCallWhenBusy = false, + hlsPlayerFactory = ExoHlsPlayerFactory(), ).apply { sfuId?.takeIf { it.isNotBlank() }?.let(::forceSfuId) }.build() diff --git a/scripts/release/local-release b/scripts/release/local-release index 64c01a99dfd..923ded0b720 100755 --- a/scripts/release/local-release +++ b/scripts/release/local-release @@ -114,6 +114,7 @@ modules=( "stream-video-android-ui-core" "stream-video-android-ui-compose" "stream-video-android-filters-video" + "stream-video-android-hls" "stream-video-android-ui-xml" ) diff --git a/settings.gradle.kts b/settings.gradle.kts index 29c214df250..faaa1e08cb8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,7 @@ include(":stream-video-android-ui-core") include(":stream-video-android-ui-xml") include(":stream-video-android-ui-compose") include(":stream-video-android-filters-video") +include(":stream-video-android-hls") include(":stream-video-android-previewdata") include(":stream-video-android-bom") diff --git a/stream-video-android-bom/build.gradle.kts b/stream-video-android-bom/build.gradle.kts index d8fb15c4002..5d8d0241145 100644 --- a/stream-video-android-bom/build.gradle.kts +++ b/stream-video-android-bom/build.gradle.kts @@ -19,6 +19,7 @@ dependencies { api(project(":stream-video-android-ui-xml")) api(project(":stream-video-android-ui-compose")) api(project(":stream-video-android-filters-video")) + api(project(":stream-video-android-hls")) api(project(":stream-video-android-previewdata")) } } diff --git a/stream-video-android-core/build.gradle.kts b/stream-video-android-core/build.gradle.kts index d0a1bf0746e..13175d65316 100644 --- a/stream-video-android-core/build.gradle.kts +++ b/stream-video-android-core/build.gradle.kts @@ -224,11 +224,6 @@ dependencies { implementation(libs.androidx.media.media) - // HLS playback. ExoPlayer only; the UI layer supplies the surface, so media3-ui is not needed. - // Version matches stream-chat-android 7.13 so an app using both gets a single Media3. - implementation(libs.media3.exoplayer) - implementation(libs.media3.exoplayer.hls) - // unit tests testImplementation(libs.stream.result) testImplementation(libs.stream.result.call) diff --git a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt deleted file mode 100644 index 553ee95fd13..00000000000 --- a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/hls/HlsPlayback.kt +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. - * - * Licensed under the Stream License; - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://github.com/GetStream/stream-video-android/blob/main/LICENSE - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.getstream.video.android.core.call.hls - -import android.content.Context -import android.view.SurfaceView -import androidx.media3.common.MediaItem -import androidx.media3.common.Player -import androidx.media3.common.VideoSize -import androidx.media3.exoplayer.ExoPlayer -import io.getstream.video.android.core.Call -import io.getstream.video.android.core.internal.InternalStreamVideoApi -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow - -/** - * Plays one HLS playlist and draws it on a [SurfaceView] supplied by the UI layer. - * - * One instance is shared by every renderer of the same [Call], so two tiles cannot start two - * players for the same broadcast. The player draws to one surface at a time: showing the same call - * in two renderers at once is not supported. - */ -@InternalStreamVideoApi -public interface HlsPlayback { - public val playlistUrl: String - - /** - * Display width divided by height of the decoded video, or null until the first frame size is - * known. A [SurfaceView] stretches frames to its own bounds, so the UI sizes the surface with it. - */ - public val videoAspectRatio: StateFlow - - public fun attach(surfaceView: SurfaceView) - - public fun detach(surfaceView: SurfaceView) - - /** Mutes the broadcast audio when [enabled] is false. Playback continues either way. */ - public fun setAudioEnabled(enabled: Boolean) - - public fun release() -} - -internal class Media3HlsPlayback( - context: Context, - override val playlistUrl: String, -) : HlsPlayback { - - internal val player: ExoPlayer = ExoPlayer.Builder(context.applicationContext).build() - - private val _videoAspectRatio = MutableStateFlow(null) - override val videoAspectRatio: StateFlow = _videoAspectRatio - - init { - try { - player.addListener( - object : Player.Listener { - override fun onVideoSizeChanged(videoSize: VideoSize) { - videoAspectRatioOf(videoSize)?.let { _videoAspectRatio.value = it } - } - }, - ) - player.setMediaItem(MediaItem.fromUri(playlistUrl)) - player.playWhenReady = true - player.prepare() - } catch (error: Throwable) { - player.release() - throw error - } - } - - private var attached: SurfaceView? = null - private var released = false - - override fun attach(surfaceView: SurfaceView) { - if (released || attached === surfaceView) return - attached?.let { player.clearVideoSurfaceView(it) } - player.setVideoSurfaceView(surfaceView) - attached = surfaceView - } - - override fun detach(surfaceView: SurfaceView) { - if (released || attached !== surfaceView) return - player.clearVideoSurfaceView(surfaceView) - attached = null - } - - override fun setAudioEnabled(enabled: Boolean) { - if (released) return - player.volume = if (enabled) 1f else 0f - } - - override fun release() { - if (released) return - released = true - attached = null - player.release() - } -} - -/** Display aspect ratio of [videoSize], accounting for non-square pixels. Null while unknown. */ -internal fun videoAspectRatioOf(videoSize: VideoSize): Float? { - if (videoSize.width <= 0 || videoSize.height <= 0) return null - return videoSize.width * videoSize.pixelWidthHeightRatio / videoSize.height -} - -/** - * Hands out one [HlsPlayback] per [Call], reference counted across the renderers that show it. - * - * @param factory Builds the [HlsPlayback] for a playlist. - */ -@InternalStreamVideoApi -public class HlsPlaybackStore( - private val factory: (Context, String) -> HlsPlayback = ::Media3HlsPlayback, -) { - - private class Ref(val playback: HlsPlayback, var count: Int) - - private val byCall = HashMap() - - public fun acquire(context: Context, call: Call, playlistUrl: String): HlsPlayback { - synchronized(byCall) { - val existing = byCall[call] - if (existing != null && existing.playback.playlistUrl == playlistUrl) { - existing.count += 1 - return existing.playback - } - // Drop the previous player before creating the next one. A factory failure must not - // leave a released player in the map, or the next acquire would release it again. - if (existing != null) { - byCall.remove(call) - existing.playback.release() - } - val created = factory(context, playlistUrl) - byCall[call] = Ref(created, count = 1) - return created - } - } - - public fun release(call: Call, playback: HlsPlayback) { - synchronized(byCall) { - val existing = byCall[call] ?: return - if (existing.playback !== playback) return - existing.count -= 1 - if (existing.count <= 0) { - byCall.remove(call) - playback.release() - } - } - } -} diff --git a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt b/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt deleted file mode 100644 index 82441acbae2..00000000000 --- a/stream-video-android-core/src/test/kotlin/io/getstream/video/android/core/call/hls/Media3HlsPlaybackTest.kt +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. - * - * Licensed under the Stream License; - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://github.com/GetStream/stream-video-android/blob/main/LICENSE - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.getstream.video.android.core.call.hls - -import android.content.Context -import android.view.SurfaceView -import androidx.media3.common.VideoSize -import com.google.common.truth.Truth.assertThat -import io.getstream.video.android.core.Call -import io.mockk.mockk -import kotlinx.coroutines.flow.MutableStateFlow -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [33]) -internal class Media3HlsPlaybackTest { - - private companion object { - const val URL = "https://example.com/live.m3u8" - const val OTHER_URL = "https://example.com/other.m3u8" - } - - private val created = mutableListOf() - private val store = HlsPlaybackStore { _, url -> FakeHlsPlayback(url).also { created += it } } - private val context = mockk(relaxed = true) - - @Test - fun `one call shares a single player until the last renderer leaves`() { - val call = mockk() - - val first = store.acquire(context, call, URL) - val second = store.acquire(context, call, URL) - - assertThat(second).isSameInstanceAs(first) - assertThat(created).hasSize(1) - - store.release(call, first) - assertThat(created.single().released).isFalse() - store.release(call, second) - assertThat(created.single().released).isTrue() - } - - @Test - fun `a new playlist releases the previous player before the next one starts`() { - val call = mockk() - - val old = store.acquire(context, call, URL) - val new = store.acquire(context, call, OTHER_URL) - - assertThat(new).isNotSameInstanceAs(old) - assertThat(created.map { it.playlistUrl }).containsExactly(URL, OTHER_URL).inOrder() - assertThat(created[0].released).isTrue() - assertThat(created[1].released).isFalse() - } - - @Test - fun `releasing a replaced player leaves the current one playing`() { - val call = mockk() - val old = store.acquire(context, call, URL) - store.acquire(context, call, OTHER_URL) - - store.release(call, old) - - assertThat(created[1].released).isFalse() - } - - @Test - fun `different calls get different players`() { - val first = store.acquire(context, mockk(), URL) - val second = store.acquire(context, mockk(), URL) - - assertThat(second).isNotSameInstanceAs(first) - assertThat(created).hasSize(2) - } - - @Test - fun `a failing factory leaves nothing behind for the next acquire`() { - val call = mockk() - var fail = true - val failing = HlsPlaybackStore { _, url -> - if (fail) error("decoder unavailable") - FakeHlsPlayback(url).also { created += it } - } - - assertThat(runCatching { failing.acquire(context, call, URL) }.isFailure).isTrue() - fail = false - failing.acquire(context, call, URL) - - assertThat(created).hasSize(1) - assertThat(created.single().released).isFalse() - } - - @Test - fun `exoplayer is pointed at the playlist`() { - val playback = Media3HlsPlayback( - context = RuntimeEnvironment.getApplication(), - playlistUrl = URL, - ) - try { - assertThat(playback.player.currentMediaItem?.localConfiguration?.uri.toString()) - .isEqualTo(URL) - assertThat(playback.player.playWhenReady).isTrue() - } finally { - playback.release() - } - } - - @Test - fun `swapping surfaces and calling after release does not throw`() { - val application = RuntimeEnvironment.getApplication() - val playback = Media3HlsPlayback(context = application, playlistUrl = URL) - val first = SurfaceView(application) - val second = SurfaceView(application) - - playback.attach(first) - playback.attach(first) - playback.attach(second) - playback.detach(first) - playback.detach(second) - playback.release() - playback.release() - playback.attach(first) - playback.detach(first) - } - - @Test - fun `disabling audio mutes the player without stopping it`() { - val playback = Media3HlsPlayback( - context = RuntimeEnvironment.getApplication(), - playlistUrl = URL, - ) - try { - playback.setAudioEnabled(false) - assertThat(playback.player.volume).isEqualTo(0f) - assertThat(playback.player.playWhenReady).isTrue() - - playback.setAudioEnabled(true) - assertThat(playback.player.volume).isEqualTo(1f) - } finally { - playback.release() - } - playback.setAudioEnabled(false) - } - - @Test - fun `aspect ratio uses the display shape and stays unknown without a frame size`() { - assertThat(videoAspectRatioOf(VideoSize(1920, 1080))).isWithin(0.001f).of(16f / 9f) - assertThat(videoAspectRatioOf(VideoSize(960, 1080, 2f))).isWithin(0.001f).of(16f / 9f) - assertThat(videoAspectRatioOf(VideoSize.UNKNOWN)).isNull() - } - - private class FakeHlsPlayback( - override val playlistUrl: String, - ) : HlsPlayback { - override val videoAspectRatio = MutableStateFlow(null) - var released = false - - override fun attach(surfaceView: SurfaceView) = Unit - - override fun detach(surfaceView: SurfaceView) = Unit - - override fun setAudioEnabled(enabled: Boolean) = Unit - - override fun release() { - released = true - } - } -} diff --git a/stream-video-android-hls/api/stream-video-android-hls.api b/stream-video-android-hls/api/stream-video-android-hls.api new file mode 100644 index 00000000000..65f4feb45d6 --- /dev/null +++ b/stream-video-android-hls/api/stream-video-android-hls.api @@ -0,0 +1,10 @@ +public final class io/getstream/video/android/hls/ExoHlsPlayerFactory : io/getstream/video/android/core/call/hls/HlsPlayerFactory { + public static final field $stable I + public fun ()V + public fun create (Landroid/content/Context;Ljava/lang/String;)Lio/getstream/video/android/core/call/hls/HlsPlayer; +} + +public final class io/getstream/video/android/hls/HlsVideoRendererKt { + public static final fun HlsVideoRenderer (Lio/getstream/video/android/core/Call;Landroidx/compose/ui/Modifier;ZLandroidx/compose/runtime/Composer;II)V +} + diff --git a/stream-video-android-hls/build.gradle.kts b/stream-video-android-hls/build.gradle.kts new file mode 100644 index 00000000000..499cb6dba8f --- /dev/null +++ b/stream-video-android-hls/build.gradle.kts @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +plugins { + id("io.getstream.video.android.library.compose") +} + +android { + namespace = "io.getstream.video.android.hls" + compileSdk = libs.versions.compileSdk.get().toInt() + + defaultConfig { + minSdk = libs.versions.minSdk.get().toInt() + } + + testOptions { + unitTests.isIncludeAndroidResources = true + unitTests.isReturnDefaultValues = true + } +} + +baselineProfile { + baselineProfileOutputDir = "." + filter { + include("io.getstream.video.android.hls.**") + } +} + +dependencies { + api(project(":stream-video-android-core")) + + // ExoPlayer only; the renderer supplies the surface, so media3-ui is not needed. + // Version matches stream-chat-android 7.13 so an app using both gets a single Media3. + implementation(libs.media3.exoplayer) + implementation(libs.media3.exoplayer.hls) + + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.runtime) + implementation(libs.androidx.compose.foundation) + implementation(libs.androidx.lifecycle.runtime.compose) + + testImplementation(libs.junit) + testImplementation(libs.truth) + testImplementation(libs.mockk) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.activity.compose) +} diff --git a/stream-video-android-hls/src/main/AndroidManifest.xml b/stream-video-android-hls/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..4fc7567453b --- /dev/null +++ b/stream-video-android-hls/src/main/AndroidManifest.xml @@ -0,0 +1,17 @@ + + + diff --git a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt new file mode 100644 index 00000000000..1d8246ccac6 --- /dev/null +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.hls + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.view.SurfaceView +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.common.VideoSize +import androidx.media3.exoplayer.ExoPlayer +import io.getstream.video.android.core.StreamVideoBuilder +import io.getstream.video.android.core.call.hls.HlsPlayer +import io.getstream.video.android.core.call.hls.HlsPlayerFactory +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** + * Plays HLS broadcasts with Media3 ExoPlayer. Pass it to [StreamVideoBuilder] to enable HLS + * playback, and show a call with [HlsVideoRenderer]. + * + * ```kotlin + * StreamVideoBuilder( + * context = context, + * apiKey = apiKey, + * user = user, + * token = token, + * hlsPlayerFactory = ExoHlsPlayerFactory(), + * ).build() + * ``` + */ +public class ExoHlsPlayerFactory : HlsPlayerFactory { + + override fun create(context: Context, playlistUrl: String): HlsPlayer = + ExoHlsPlayer(context.applicationContext, playlistUrl) +} + +/** + * [HlsPlayer] backed by ExoPlayer. ExoPlayer is bound to the thread that builds it, so it is built + * on the main thread at the first [attach] rather than when the call joins. + */ +internal class ExoHlsPlayer( + private val context: Context, + override val playlistUrl: String, +) : HlsPlayer { + + private companion object { + /** A pause longer than this resumes at the live edge instead of where playback stopped. */ + const val RESUME_AT_LIVE_EDGE_AFTER_MS = 10_000L + } + + private val mainHandler = Handler(Looper.getMainLooper()) + + private val _videoAspectRatio = MutableStateFlow(null) + override val videoAspectRatio: StateFlow = _videoAspectRatio.asStateFlow() + + // Main thread only. + private var player: ExoPlayer? = null + private var surface: SurfaceView? = null + private var audioEnabled = true + private var pausedAt: Long? = null + private var released = false + + internal val exoPlayer: ExoPlayer? get() = player + + override fun attach(surfaceView: SurfaceView) { + if (released) return + val player = player ?: buildPlayer().also { player = it } + if (surface !== surfaceView) { + surface?.let(player::clearVideoSurfaceView) + player.setVideoSurfaceView(surfaceView) + surface = surfaceView + } + val pausedFor = pausedAt?.let { SystemClock.elapsedRealtime() - it } + if (pausedFor != null && pausedFor > RESUME_AT_LIVE_EDGE_AFTER_MS && player.isCurrentMediaItemLive) { + player.seekToDefaultPosition() + } + pausedAt = null + player.play() + } + + override fun detach(surfaceView: SurfaceView) { + if (released || surface !== surfaceView) return + val player = player ?: return + player.pause() + player.clearVideoSurfaceView(surfaceView) + surface = null + pausedAt = SystemClock.elapsedRealtime() + } + + override fun setAudioEnabled(enabled: Boolean) { + audioEnabled = enabled + player?.volume = volumeFor(enabled) + } + + override fun release() { + if (Looper.myLooper() == Looper.getMainLooper()) { + releaseOnMain() + } else { + mainHandler.post(::releaseOnMain) + } + } + + private fun releaseOnMain() { + if (released) return + released = true + surface = null + player?.release() + player = null + } + + private fun buildPlayer(): ExoPlayer { + val player = ExoPlayer.Builder(context).build() + try { + player.addListener( + object : Player.Listener { + override fun onVideoSizeChanged(videoSize: VideoSize) { + videoAspectRatioOf(videoSize)?.let { _videoAspectRatio.value = it } + } + }, + ) + player.volume = volumeFor(audioEnabled) + player.setMediaItem(MediaItem.fromUri(playlistUrl)) + player.prepare() + } catch (error: Throwable) { + player.release() + throw error + } + return player + } + + private fun volumeFor(enabled: Boolean): Float = if (enabled) 1f else 0f +} + +/** Display aspect ratio of [videoSize], accounting for non-square pixels. Null while unknown. */ +internal fun videoAspectRatioOf(videoSize: VideoSize): Float? { + if (videoSize.width <= 0 || videoSize.height <= 0) return null + return videoSize.width * videoSize.pixelWidthHeightRatio / videoSize.height +} diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt similarity index 55% rename from stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt rename to stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt index 89f64df667b..14882edaa17 100644 --- a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRenderer.kt +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package io.getstream.video.android.compose.ui.components.video +package io.getstream.video.android.hls import android.view.SurfaceView import androidx.compose.foundation.background @@ -22,31 +22,25 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.compose.collectAsStateWithLifecycle import io.getstream.video.android.core.Call -import io.getstream.video.android.core.call.hls.HlsPlayback -import io.getstream.video.android.core.call.hls.HlsPlaybackStore import io.getstream.video.android.core.model.PlaybackType /** - * Plays the call's HLS broadcast. + * Shows the call's HLS broadcast. * - * Renders nothing while [Call.state.playbackType] is not [PlaybackType.Hls]. The playlist is on - * the call. One player is shared by every [HlsVideoRenderer] of the same call, and released when - * the last one leaves. + * Renders nothing unless [Call.state.playbackType] is [PlaybackType.Hls], which requires an + * [ExoHlsPlayerFactory] registered on the client. The call owns the player: this renderer plays + * it while shown and pauses it when removed, and leaving the call releases it. Recreating the + * renderer, for example on rotation, resumes the same player without loading the stream again. * * The broadcast is an already composed layout, so the frame is fitted rather than cropped. * @@ -61,35 +55,8 @@ public fun HlsVideoRenderer( modifier: Modifier = Modifier, audioEnabled: Boolean = true, ) { - HlsVideoRendererImpl( - call = call, - store = defaultHlsPlaybackStore, - modifier = modifier, - audioEnabled = audioEnabled, - ) -} - -private val defaultHlsPlaybackStore = HlsPlaybackStore() - -@Composable -internal fun HlsVideoRendererImpl( - call: Call, - store: HlsPlaybackStore, - modifier: Modifier = Modifier, - audioEnabled: Boolean = true, -) { - val playbackType by call.state.playbackType.collectAsStateWithLifecycle() - val playlistUrl = (playbackType as? PlaybackType.Hls)?.playlistUrl ?: return - val context = LocalContext.current - var playback by remember(store, call, playlistUrl) { mutableStateOf(null) } - // Acquired here rather than in remember: an abandoned composition never runs onDispose, - // so a player started during composition would never be released. - DisposableEffect(store, call, playlistUrl) { - val acquired = store.acquire(context, call, playlistUrl) - playback = acquired - onDispose { store.release(call, acquired) } - } - val current = playback ?: return + val player by call.hlsPlayer.collectAsStateWithLifecycle() + val current = player ?: return SideEffect { current.setAudioEnabled(audioEnabled) } val aspectRatio by current.videoAspectRatio.collectAsStateWithLifecycle() Box( @@ -98,9 +65,7 @@ internal fun HlsVideoRendererImpl( ) { key(current) { AndroidView( - factory = { viewContext -> - SurfaceView(viewContext).also { current.attach(it) } - }, + factory = { context -> SurfaceView(context).also { current.attach(it) } }, onRelease = { surface -> current.detach(surface) }, modifier = (aspectRatio?.let { Modifier.aspectRatio(it) } ?: Modifier.fillMaxSize()) .testTag("hls_video_renderer"), diff --git a/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt new file mode 100644 index 00000000000..f419014478e --- /dev/null +++ b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-video-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.video.android.hls + +import android.os.Looper +import android.view.SurfaceView +import androidx.media3.common.VideoSize +import com.google.common.truth.Truth.assertThat +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import kotlin.concurrent.thread + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +internal class ExoHlsPlayerTest { + + private companion object { + const val URL = "https://example.com/live.m3u8" + } + + private val application = RuntimeEnvironment.getApplication() + private val player = ExoHlsPlayerFactory().create(application, URL) as ExoHlsPlayer + + @After + fun tearDown() { + player.release() + } + + @Test + fun `creating the player does not build exoplayer until a surface is attached`() { + assertThat(player.exoPlayer).isNull() + + player.attach(SurfaceView(application)) + + val exoPlayer = player.exoPlayer!! + assertThat(exoPlayer.currentMediaItem?.localConfiguration?.uri.toString()).isEqualTo(URL) + assertThat(exoPlayer.playWhenReady).isTrue() + } + + @Test + fun `detaching pauses and a later attach resumes the same exoplayer`() { + val first = SurfaceView(application) + player.attach(first) + val exoPlayer = player.exoPlayer + + player.detach(first) + assertThat(exoPlayer!!.playWhenReady).isFalse() + + player.attach(SurfaceView(application)) + assertThat(player.exoPlayer).isSameInstanceAs(exoPlayer) + assertThat(exoPlayer.playWhenReady).isTrue() + } + + @Test + fun `detaching a surface that is no longer shown keeps playing`() { + val first = SurfaceView(application) + player.attach(first) + player.attach(SurfaceView(application)) + + player.detach(first) + + assertThat(player.exoPlayer!!.playWhenReady).isTrue() + } + + @Test + fun `audio muted before the first attach applies to the new exoplayer`() { + player.setAudioEnabled(false) + player.attach(SurfaceView(application)) + assertThat(player.exoPlayer!!.volume).isEqualTo(0f) + assertThat(player.exoPlayer!!.playWhenReady).isTrue() + + player.setAudioEnabled(true) + assertThat(player.exoPlayer!!.volume).isEqualTo(1f) + } + + @Test + fun `release from another thread runs on the main thread and ends playback`() { + val surface = SurfaceView(application) + player.attach(surface) + + thread { player.release() }.join() + assertThat(player.exoPlayer).isNotNull() + shadowOf(Looper.getMainLooper()).idle() + + assertThat(player.exoPlayer).isNull() + player.attach(surface) + player.detach(surface) + player.setAudioEnabled(false) + assertThat(player.exoPlayer).isNull() + } + + @Test + fun `aspect ratio uses the display shape and stays unknown without a frame size`() { + assertThat(videoAspectRatioOf(VideoSize(1920, 1080))).isWithin(0.001f).of(16f / 9f) + assertThat(videoAspectRatioOf(VideoSize(960, 1080, 2f))).isWithin(0.001f).of(16f / 9f) + assertThat(videoAspectRatioOf(VideoSize.UNKNOWN)).isNull() + } +} diff --git a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/HlsVideoRendererTest.kt similarity index 50% rename from stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt rename to stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/HlsVideoRendererTest.kt index ef9ebbd4592..fa0a4456bf2 100644 --- a/stream-video-android-ui-compose/src/test/kotlin/io/getstream/video/android/compose/ui/components/video/HlsVideoRendererTest.kt +++ b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/HlsVideoRendererTest.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package io.getstream.video.android.compose.ui.components.video +package io.getstream.video.android.hls import android.os.Handler import android.os.Looper @@ -23,27 +23,16 @@ import android.view.View import android.view.ViewGroup import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.AbstractApplier import androidx.compose.runtime.BroadcastFrameClock -import androidx.compose.runtime.Composition -import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Recomposer import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView -import androidx.compose.ui.platform.LocalContext -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.LifecycleRegistry -import androidx.lifecycle.compose.LocalLifecycleOwner import com.google.common.truth.Truth.assertThat import io.getstream.video.android.core.Call -import io.getstream.video.android.core.CallState -import io.getstream.video.android.core.call.hls.HlsPlayback -import io.getstream.video.android.core.call.hls.HlsPlaybackStore -import io.getstream.video.android.core.model.PlaybackType +import io.getstream.video.android.core.call.hls.HlsPlayer import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.CoroutineScope @@ -57,12 +46,10 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment import org.robolectric.Shadows.shadowOf import org.robolectric.android.controller.ActivityController import org.robolectric.annotation.Config import java.time.Duration -import kotlin.coroutines.EmptyCoroutineContext @RunWith(RobolectricTestRunner::class) @Config(sdk = [33]) @@ -75,14 +62,6 @@ internal class HlsVideoRendererTest { const val FRAME_MS = 20L } - private val created = mutableListOf() - private var aspectRatio: Float? = null - private val store = HlsPlaybackStore { _, url -> - FakeHlsPlayback(url).also { - it.videoAspectRatio.value = aspectRatio - created += it - } - } private val activities = mutableListOf>() // Compose caches the window recomposer's dispatcher per thread, bound to the first test's @@ -103,40 +82,58 @@ internal class HlsVideoRendererTest { } @Test - fun `hls playback renders the playlist`() { - val playback = MutableStateFlow(PlaybackType.Hls(URL)) + fun `the call's player is shown and hidden when playback ends`() { + val player = FakeHlsPlayer(URL) + val hlsPlayer = MutableStateFlow(player) - val activity = show(playback) + val activity = show(call(hlsPlayer)).first - assertThat(containsSurfaceView(activity.window.decorView)).isTrue() - assertThat(created.map { it.playlistUrl }).containsExactly(URL) - assertThat(created.single().attachCount).isEqualTo(1) + assertThat(activity.window.decorView.findSurfaceView()).isNotNull() + assertThat(player.shownOn).isNotNull() - playback.value = PlaybackType.WebRtc + hlsPlayer.value = null settle() - assertThat(containsSurfaceView(activity.window.decorView)).isFalse() - assertThat(created.single().released).isTrue() + assertThat(activity.window.decorView.findSurfaceView()).isNull() + assertThat(player.shownOn).isNull() + assertThat(player.released).isFalse() + } + + @Test + fun `a recreated renderer resumes the same player without releasing it`() { + val player = FakeHlsPlayer(URL) + val call = call(MutableStateFlow(player)) + + val (_, first) = show(call) + activities.remove(first) + first.pause().stop().destroy() + assertThat(player.shownOn).isNull() + + show(call) + + assertThat(player.shownOn).isNotNull() + assertThat(player.attachCount).isEqualTo(2) + assertThat(player.released).isFalse() } @Test - fun `a new playlist attaches the new player and releases the old one`() { - val playback = MutableStateFlow(PlaybackType.Hls(URL)) - show(playback) + fun `a replacement player is shown in place of the previous one`() { + val old = FakeHlsPlayer(URL) + val new = FakeHlsPlayer(OTHER_URL) + val hlsPlayer = MutableStateFlow(old) + show(call(hlsPlayer)) - playback.value = PlaybackType.Hls(OTHER_URL) + hlsPlayer.value = new settle() - assertThat(created.map { it.playlistUrl }).containsExactly(URL, OTHER_URL).inOrder() - assertThat(created[0].released).isTrue() - assertThat(created[1].released).isFalse() - assertThat(created[1].attachCount).isEqualTo(1) + assertThat(old.shownOn).isNull() + assertThat(new.shownOn).isNotNull() } @Test fun `hls surface keeps the stream aspect ratio instead of stretching to the tile`() { - aspectRatio = 16f / 9f - val activity = show(MutableStateFlow(PlaybackType.Hls(URL))) + val player = FakeHlsPlayer(URL).apply { videoAspectRatio.value = 16f / 9f } + val activity = show(call(MutableStateFlow(player))).first val container = activity.findViewById(android.R.id.content) assertThat(container.height).isGreaterThan(container.width) @@ -146,76 +143,30 @@ internal class HlsVideoRendererTest { } @Test - fun `webrtc playback does not create an hls player`() { - val activity = show(MutableStateFlow(PlaybackType.WebRtc)) - - assertThat(containsSurfaceView(activity.window.decorView)).isFalse() - assertThat(created).isEmpty() - } - - @Test - fun `an abandoned composition does not start a player`() { - val call = call(MutableStateFlow(PlaybackType.Hls(URL))) - // A private recomposer keeps the failing composition away from the main-thread one - // that the activity-based tests share. - val recomposer = Recomposer(EmptyCoroutineContext) - val composition = Composition(NoNodeApplier(), recomposer) - - val result = runCatching { - composition.setContent { - CompositionLocalProvider( - LocalContext provides RuntimeEnvironment.getApplication(), - LocalLifecycleOwner provides ResumedLifecycleOwner(), - ) { - HlsVideoRendererImpl(call = call, store = store) - } - error("composition abandoned before it was applied") - } - } - runCatching { composition.dispose() } - recomposer.cancel() - - assertThat(result.isFailure).isTrue() - assertThat(created).isEmpty() - } - - @Test - fun `two renderers of one call share a player and the second release stops it`() { - val playback = MutableStateFlow(PlaybackType.Hls(URL)) - val call = call(playback) + fun `a call without an hls player renders nothing`() { + val activity = show(call(MutableStateFlow(null))).first - val first = show(call) - val second = show(call) - - assertThat(created).hasSize(1) - activities.remove(first.second) - first.second.pause().stop().destroy() - assertThat(created.single().released).isFalse() - - activities.remove(second.second) - second.second.pause().stop().destroy() - assertThat(created.single().released).isTrue() + assertThat(activity.window.decorView.findSurfaceView()).isNull() } @Test fun `the audio toggle mutes the player and a replacement player starts muted`() { - val playback = MutableStateFlow(PlaybackType.Hls(URL)) + val player = FakeHlsPlayer(URL) + val hlsPlayer = MutableStateFlow(player) val audioEnabled = mutableStateOf(true) - show(call(playback), audioEnabled) - assertThat(created.single().audioEnabled).isTrue() + show(call(hlsPlayer), audioEnabled) + assertThat(player.audioEnabled).isTrue() audioEnabled.value = false settle() - assertThat(created.single().audioEnabled).isFalse() + assertThat(player.audioEnabled).isFalse() - playback.value = PlaybackType.Hls(OTHER_URL) + val replacement = FakeHlsPlayer(OTHER_URL) + hlsPlayer.value = replacement settle() - assertThat(created[1].audioEnabled).isFalse() + assertThat(replacement.audioEnabled).isFalse() } - private fun show(playback: MutableStateFlow): ComponentActivity = - show(call(playback)).first - private fun show( call: Call, audioEnabled: State = mutableStateOf(true), @@ -226,9 +177,8 @@ internal class HlsVideoRendererTest { val view = ComposeView(activity).apply { setParentCompositionContext(recomposer) setContent { - HlsVideoRendererImpl( + HlsVideoRenderer( call = call, - store = store, modifier = Modifier.fillMaxSize(), audioEnabled = audioEnabled.value, ) @@ -250,16 +200,10 @@ internal class HlsVideoRendererTest { } } - private fun call(playback: MutableStateFlow): Call { - val state = mockk() - every { state.playbackType } returns playback - return mockk { - every { this@mockk.state } returns state - } + private fun call(hlsPlayer: MutableStateFlow): Call = mockk { + every { this@mockk.hlsPlayer } returns hlsPlayer } - private fun containsSurfaceView(view: View): Boolean = view.findSurfaceView() != null - private fun View.findSurfaceView(): SurfaceView? { if (this is SurfaceView) return this if (this is ViewGroup) { @@ -270,33 +214,23 @@ internal class HlsVideoRendererTest { return null } - private class NoNodeApplier : AbstractApplier(Unit) { - override fun insertTopDown(index: Int, instance: Unit) = Unit - override fun insertBottomUp(index: Int, instance: Unit) = Unit - override fun remove(index: Int, count: Int) = Unit - override fun move(from: Int, to: Int, count: Int) = Unit - override fun onClear() = Unit - } - - private class ResumedLifecycleOwner : LifecycleOwner { - override val lifecycle: Lifecycle = LifecycleRegistry.createUnsafe(this).apply { - currentState = Lifecycle.State.RESUMED - } - } - - private class FakeHlsPlayback( + private class FakeHlsPlayer( override val playlistUrl: String, - ) : HlsPlayback { + ) : HlsPlayer { override val videoAspectRatio = MutableStateFlow(null) + var shownOn: SurfaceView? = null var attachCount = 0 var released = false var audioEnabled: Boolean? = null override fun attach(surfaceView: SurfaceView) { attachCount += 1 + shownOn = surfaceView } - override fun detach(surfaceView: SurfaceView) = Unit + override fun detach(surfaceView: SurfaceView) { + if (shownOn === surfaceView) shownOn = null + } override fun setAudioEnabled(enabled: Boolean) { audioEnabled = enabled diff --git a/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api b/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api index 8b78bf9793d..fba5d264a19 100644 --- a/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api +++ b/stream-video-android-ui-compose/api/stream-video-android-ui-compose.api @@ -2069,10 +2069,6 @@ public final class io/getstream/video/android/compose/ui/components/participants public static final fun ParticipantInformation (Lio/getstream/video/android/core/model/CallStatus;Ljava/util/List;ZLandroidx/compose/runtime/Composer;II)V } -public final class io/getstream/video/android/compose/ui/components/video/HlsVideoRendererKt { - public static final fun HlsVideoRenderer (Lio/getstream/video/android/core/Call;Landroidx/compose/ui/Modifier;ZLandroidx/compose/runtime/Composer;II)V -} - public final class io/getstream/video/android/compose/ui/components/video/VideoRendererKt { public static final fun VideoRenderer (Landroidx/compose/ui/Modifier;Lio/getstream/video/android/core/Call;Lio/getstream/video/android/core/ParticipantState$Media;Lio/getstream/video/android/compose/ui/components/video/config/VideoRendererConfig;Lkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V public static final fun VideoRenderer (Lio/getstream/video/android/core/Call;Lio/getstream/video/android/core/ParticipantState$Media;Landroidx/compose/ui/Modifier;Lio/getstream/video/android/compose/ui/components/video/VideoScalingType;Lkotlin/jvm/functions/Function3;Lkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V diff --git a/stream-video-android-ui-compose/build.gradle.kts b/stream-video-android-ui-compose/build.gradle.kts index dd333f75015..68c95972a0b 100644 --- a/stream-video-android-ui-compose/build.gradle.kts +++ b/stream-video-android-ui-compose/build.gradle.kts @@ -25,11 +25,6 @@ android { defaultConfig { minSdk = libs.versions.minSdk.get().toInt() } - - testOptions { - unitTests.isIncludeAndroidResources = true - unitTests.isReturnDefaultValues = true - } } // Paparazzi renders and compresses every snapshot in the forked test worker, which defaults to a diff --git a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt index bd683884c9e..02e5abcc569 100644 --- a/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt +++ b/stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/livestream/LivestreamPlayer.kt @@ -29,13 +29,11 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.lifecycle.compose.collectAsStateWithLifecycle import io.getstream.video.android.compose.ui.components.livestream.state.LivestreamState -import io.getstream.video.android.compose.ui.components.video.HlsVideoRenderer import io.getstream.video.android.compose.ui.components.video.config.VideoRendererConfig import io.getstream.video.android.compose.ui.components.video.config.videoRenderConfig import io.getstream.video.android.core.Call import io.getstream.video.android.core.ParticipantState import io.getstream.video.android.core.RealtimeConnection -import io.getstream.video.android.core.model.PlaybackType import io.getstream.video.android.core.sorting.bySourcePriority import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine @@ -139,9 +137,7 @@ public fun LivestreamPlayer( ) val livestream by livestreamFlow.collectAsStateWithLifecycle(initialValue = null) - val playback by call.state.playbackType.collectAsStateWithLifecycle() val hostVideoAvailable = livestream?.enabled == true - val playingHls = playback is PlaybackType.Hls val connection by call.state.connection.collectAsStateWithLifecycle() val endedAt by call.state.endedAt.collectAsStateWithLifecycle() @@ -175,8 +171,6 @@ public fun LivestreamPlayer( videoRendererConfig = videoRendererConfig, livestreamFlow = livestreamFlow, hostVideoAvailable = hostVideoAvailable, - playingHls = playingHls, - isAudioEnabled = isAudioEnabled, livestreamState = livestreamState, rendererContent = wrappedRenderer, overlayContent = wrappedOverlay, @@ -197,8 +191,6 @@ internal fun LivestreamPlayerImpl( videoRendererConfig: VideoRendererConfig, livestreamFlow: Flow, hostVideoAvailable: Boolean, - playingHls: Boolean, - isAudioEnabled: Boolean, livestreamState: LivestreamState, rendererContent: @Composable BoxScope.(Call) -> Unit, overlayContent: @Composable BoxScope.(Call) -> Unit, @@ -233,14 +225,10 @@ internal fun LivestreamPlayerImpl( } LivestreamState.LIVE -> { - when { - playingHls -> HlsVideoRenderer( - call = call, - modifier = Modifier.fillMaxSize(), - audioEnabled = isAudioEnabled, - ) - hostVideoAvailable -> rendererContent.invoke(this, call) - else -> liveStreamHostVideoNotAvailableContent.invoke(this, call) + if (hostVideoAvailable) { + rendererContent.invoke(this, call) + } else { + liveStreamHostVideoNotAvailableContent.invoke(this, call) } overlayContent.invoke(this, call) } From d40fdff6653261415d581ed556d06b50c4c78da2 Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Thu, 19 Nov 2026 20:30:03 +0530 Subject: [PATCH 5/7] refactor(hls): leave resume position to ExoPlayer defaults --- .../io/getstream/video/android/hls/ExoHlsPlayer.kt | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt index 1d8246ccac6..9dc8073edf5 100644 --- a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt @@ -19,7 +19,6 @@ package io.getstream.video.android.hls import android.content.Context import android.os.Handler import android.os.Looper -import android.os.SystemClock import android.view.SurfaceView import androidx.media3.common.MediaItem import androidx.media3.common.Player @@ -61,11 +60,6 @@ internal class ExoHlsPlayer( override val playlistUrl: String, ) : HlsPlayer { - private companion object { - /** A pause longer than this resumes at the live edge instead of where playback stopped. */ - const val RESUME_AT_LIVE_EDGE_AFTER_MS = 10_000L - } - private val mainHandler = Handler(Looper.getMainLooper()) private val _videoAspectRatio = MutableStateFlow(null) @@ -75,7 +69,6 @@ internal class ExoHlsPlayer( private var player: ExoPlayer? = null private var surface: SurfaceView? = null private var audioEnabled = true - private var pausedAt: Long? = null private var released = false internal val exoPlayer: ExoPlayer? get() = player @@ -88,11 +81,6 @@ internal class ExoHlsPlayer( player.setVideoSurfaceView(surfaceView) surface = surfaceView } - val pausedFor = pausedAt?.let { SystemClock.elapsedRealtime() - it } - if (pausedFor != null && pausedFor > RESUME_AT_LIVE_EDGE_AFTER_MS && player.isCurrentMediaItemLive) { - player.seekToDefaultPosition() - } - pausedAt = null player.play() } @@ -102,7 +90,6 @@ internal class ExoHlsPlayer( player.pause() player.clearVideoSurfaceView(surfaceView) surface = null - pausedAt = SystemClock.elapsedRealtime() } override fun setAudioEnabled(enabled: Boolean) { From 1d355da8f10e070ee74693f873994ab6265cf84b Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Thu, 19 Nov 2026 21:06:10 +0530 Subject: [PATCH 6/7] feat(hls): keep playing while no renderer is shown, like WebRTC --- .../getstream/video/android/hls/ExoHlsPlayer.kt | 5 ++--- .../video/android/hls/HlsVideoRenderer.kt | 7 ++++--- .../video/android/hls/ExoHlsPlayerTest.kt | 16 ++++++++++------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt index 9dc8073edf5..fa2a06291d3 100644 --- a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt @@ -72,6 +72,7 @@ internal class ExoHlsPlayer( private var released = false internal val exoPlayer: ExoPlayer? get() = player + internal val attachedSurface: SurfaceView? get() = surface override fun attach(surfaceView: SurfaceView) { if (released) return @@ -86,9 +87,7 @@ internal class ExoHlsPlayer( override fun detach(surfaceView: SurfaceView) { if (released || surface !== surfaceView) return - val player = player ?: return - player.pause() - player.clearVideoSurfaceView(surfaceView) + player?.clearVideoSurfaceView(surfaceView) surface = null } diff --git a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt index 14882edaa17..89b87fd6aa1 100644 --- a/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/HlsVideoRenderer.kt @@ -38,9 +38,10 @@ import io.getstream.video.android.core.model.PlaybackType * Shows the call's HLS broadcast. * * Renders nothing unless [Call.state.playbackType] is [PlaybackType.Hls], which requires an - * [ExoHlsPlayerFactory] registered on the client. The call owns the player: this renderer plays - * it while shown and pauses it when removed, and leaving the call releases it. Recreating the - * renderer, for example on rotation, resumes the same player without loading the stream again. + * [ExoHlsPlayerFactory] registered on the client. The call owns the player: this renderer only + * shows its video, playback and audio continue while it is not shown, and leaving the call + * releases it. Recreating the renderer, for example on rotation, shows the same player without + * loading the stream again. * * The broadcast is an already composed layout, so the frame is fitted rather than cropped. * diff --git a/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt index f419014478e..7acbf707609 100644 --- a/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt +++ b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt @@ -57,27 +57,31 @@ internal class ExoHlsPlayerTest { } @Test - fun `detaching pauses and a later attach resumes the same exoplayer`() { + fun `detaching keeps playing and a later attach shows the same exoplayer`() { val first = SurfaceView(application) player.attach(first) val exoPlayer = player.exoPlayer player.detach(first) - assertThat(exoPlayer!!.playWhenReady).isFalse() + assertThat(player.attachedSurface).isNull() + assertThat(exoPlayer!!.playWhenReady).isTrue() - player.attach(SurfaceView(application)) + val second = SurfaceView(application) + player.attach(second) assertThat(player.exoPlayer).isSameInstanceAs(exoPlayer) - assertThat(exoPlayer.playWhenReady).isTrue() + assertThat(player.attachedSurface).isSameInstanceAs(second) } @Test - fun `detaching a surface that is no longer shown keeps playing`() { + fun `detaching a surface that is no longer shown keeps the current surface`() { val first = SurfaceView(application) + val second = SurfaceView(application) player.attach(first) - player.attach(SurfaceView(application)) + player.attach(second) player.detach(first) + assertThat(player.attachedSurface).isSameInstanceAs(second) assertThat(player.exoPlayer!!.playWhenReady).isTrue() } From 58d7f4f2428ca82f7808b35c1148dde496879bbf Mon Sep 17 00:00:00 2001 From: pratimmallick Date: Fri, 20 Nov 2026 20:24:08 +0530 Subject: [PATCH 7/7] feat(demo): show the livestream overlay on the HLS viewer screen --- .../android/ui/call/DemoHlsViewerScreen.kt | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt b/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt index 32e3fd7df39..8b68bc8aa19 100644 --- a/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt +++ b/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt @@ -16,11 +16,11 @@ package io.getstream.video.android.ui.call -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -30,13 +30,14 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import io.getstream.video.android.compose.ui.components.call.controls.actions.LeaveCallAction -import io.getstream.video.android.compose.ui.components.call.controls.actions.ToggleSpeakerphoneAction +import io.getstream.video.android.compose.ui.components.livestream.LivestreamPlayerOverlay import io.getstream.video.android.core.Call import io.getstream.video.android.hls.HlsVideoRenderer /** - * The viewer screen for a call the backend serves as HLS. It is what an app with its own UI - * writes: the broadcast, a mute toggle and a leave button. + * The viewer screen for a call the backend serves as HLS: the broadcast under the same overlay as + * the WebRTC livestream player (live badge, participant count, duration and a mute toggle), plus a + * leave button. */ @Composable fun DemoHlsViewerScreen( @@ -50,16 +51,22 @@ fun DemoHlsViewerScreen( modifier = Modifier.fillMaxSize(), audioEnabled = audioEnabled, ) - Row( + Box( modifier = Modifier - .align(Alignment.BottomCenter) - .padding(24.dp), - horizontalArrangement = Arrangement.spacedBy(16.dp), + .fillMaxSize() + .safeDrawingPadding(), ) { - ToggleSpeakerphoneAction(isSpeakerphoneEnabled = audioEnabled) { - audioEnabled = it.isEnabled - } - LeaveCallAction { onLeave() } + LivestreamPlayerOverlay( + call = call, + isAudioEnabled = audioEnabled, + onAudioToggle = { audioEnabled = it }, + ) + LeaveCallAction( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(12.dp) + .size(45.dp), + ) { onLeave() } } } }