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..8b68bc8aa19 --- /dev/null +++ b/demo-app/src/main/kotlin/io/getstream/video/android/ui/call/DemoHlsViewerScreen.kt @@ -0,0 +1,72 @@ +/* + * 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.Box +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 +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.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: 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( + call: Call, + onLeave: () -> Unit, +) { + var audioEnabled by rememberSaveable { mutableStateOf(true) } + Box(modifier = Modifier.fillMaxSize()) { + HlsVideoRenderer( + call = call, + modifier = Modifier.fillMaxSize(), + audioEnabled = audioEnabled, + ) + Box( + modifier = Modifier + .fillMaxSize() + .safeDrawingPadding(), + ) { + LivestreamPlayerOverlay( + call = call, + isAudioEnabled = audioEnabled, + onAudioToggle = { audioEnabled = it }, + ) + LeaveCallAction( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(12.dp) + .size(45.dp), + ) { 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/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7b981470d21..47eb1f0acce 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" @@ -177,6 +179,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/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-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..fa2a06291d3 --- /dev/null +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/ExoHlsPlayer.kt @@ -0,0 +1,142 @@ +/* + * 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.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 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 released = false + + internal val exoPlayer: ExoPlayer? get() = player + internal val attachedSurface: SurfaceView? get() = surface + + 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 + } + player.play() + } + + override fun detach(surfaceView: SurfaceView) { + if (released || surface !== surfaceView) return + player?.clearVideoSurfaceView(surfaceView) + surface = null + } + + 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-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 new file mode 100644 index 00000000000..89b87fd6aa1 --- /dev/null +++ b/stream-video-android-hls/src/main/kotlin/io/getstream/video/android/hls/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.hls + +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.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +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.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 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. + * + * [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, +) { + val player by call.hlsPlayer.collectAsStateWithLifecycle() + val current = player ?: return + SideEffect { current.setAudioEnabled(audioEnabled) } + val aspectRatio by current.videoAspectRatio.collectAsStateWithLifecycle() + Box( + modifier = modifier.background(Color.Black), + contentAlignment = Alignment.Center, + ) { + key(current) { + AndroidView( + 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..7acbf707609 --- /dev/null +++ b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/ExoHlsPlayerTest.kt @@ -0,0 +1,121 @@ +/* + * 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 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(player.attachedSurface).isNull() + assertThat(exoPlayer!!.playWhenReady).isTrue() + + val second = SurfaceView(application) + player.attach(second) + assertThat(player.exoPlayer).isSameInstanceAs(exoPlayer) + assertThat(player.attachedSurface).isSameInstanceAs(second) + } + + @Test + 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(second) + + player.detach(first) + + assertThat(player.attachedSurface).isSameInstanceAs(second) + 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-hls/src/test/kotlin/io/getstream/video/android/hls/HlsVideoRendererTest.kt b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/HlsVideoRendererTest.kt new file mode 100644 index 00000000000..fa0a4456bf2 --- /dev/null +++ b/stream-video-android-hls/src/test/kotlin/io/getstream/video/android/hls/HlsVideoRendererTest.kt @@ -0,0 +1,243 @@ +/* + * 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.Handler +import android.os.Looper +import android.view.SurfaceView +import android.view.View +import android.view.ViewGroup +import androidx.activity.ComponentActivity +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.BroadcastFrameClock +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 com.google.common.truth.Truth.assertThat +import io.getstream.video.android.core.Call +import io.getstream.video.android.core.call.hls.HlsPlayer +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.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +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 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 { runCatching { it.pause().stop().destroy() } } + recomposer.cancel() + recomposerScope.cancel() + } + + @Test + fun `the call's player is shown and hidden when playback ends`() { + val player = FakeHlsPlayer(URL) + val hlsPlayer = MutableStateFlow(player) + + val activity = show(call(hlsPlayer)).first + + assertThat(activity.window.decorView.findSurfaceView()).isNotNull() + assertThat(player.shownOn).isNotNull() + + hlsPlayer.value = null + settle() + + 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 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)) + + hlsPlayer.value = new + settle() + + assertThat(old.shownOn).isNull() + assertThat(new.shownOn).isNotNull() + } + + @Test + fun `hls surface keeps the stream aspect ratio instead of stretching to the tile`() { + 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) + + 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 `a call without an hls player renders nothing`() { + val activity = show(call(MutableStateFlow(null))).first + + assertThat(activity.window.decorView.findSurfaceView()).isNull() + } + + @Test + fun `the audio toggle mutes the player and a replacement player starts muted`() { + val player = FakeHlsPlayer(URL) + val hlsPlayer = MutableStateFlow(player) + val audioEnabled = mutableStateOf(true) + show(call(hlsPlayer), audioEnabled) + assertThat(player.audioEnabled).isTrue() + + audioEnabled.value = false + settle() + assertThat(player.audioEnabled).isFalse() + + val replacement = FakeHlsPlayer(OTHER_URL) + hlsPlayer.value = replacement + settle() + assertThat(replacement.audioEnabled).isFalse() + } + + private fun show( + call: Call, + audioEnabled: State = mutableStateOf(true), + ): Pair> { + val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup() + activities += controller + val activity = controller.get() + val view = ComposeView(activity).apply { + setParentCompositionContext(recomposer) + setContent { + HlsVideoRenderer( + call = call, + modifier = Modifier.fillMaxSize(), + audioEnabled = audioEnabled.value, + ) + } + } + 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)) + } + } + + private fun call(hlsPlayer: MutableStateFlow): Call = mockk { + every { this@mockk.hlsPlayer } returns hlsPlayer + } + + 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 FakeHlsPlayer( + override val playlistUrl: String, + ) : 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) { + if (shownOn === surfaceView) shownOn = null + } + + override fun setAudioEnabled(enabled: Boolean) { + audioEnabled = enabled + } + + override fun release() { + released = true + } + } +}