diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt index 594ea7ef3b..518008a0e9 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt @@ -14,6 +14,7 @@ import org.siloserver.silo.model.download.DownloadQuality import org.siloserver.silo.model.settings.EffectiveSettingValue import org.siloserver.silo.model.settings.LanguageOptions import org.siloserver.silo.model.settings.PlaybackSettingsKeys +import org.siloserver.silo.model.settings.PlaybackSpeedRange import org.siloserver.silo.model.settings.QualityPresets import org.siloserver.silo.model.settings.SettingKeys import org.siloserver.silo.model.settings.SettingScope @@ -263,8 +264,12 @@ class AndroidPlayerSettingsStore( override val hdrEnabledFlow: Flow = profileScopedFlow(true) { p, s -> p.boolFor(s, PlaybackSettingsKeys.HdrEnabled, true) } + // Off until the server says otherwise: the contract default is false, so + // defaulting on here sent Profile 7 sources down the HDR10 path before the + // first refresh (or offline) when the server would have played them as + // Dolby Vision. override val dvProfile7HDR10FallbackFlow: Flow = - profileScopedFlow(true) { p, s -> p.boolFor(s, PlaybackSettingsKeys.DvProfile7HDR10Fallback, true) } + profileScopedFlow(false) { p, s -> p.boolFor(s, PlaybackSettingsKeys.DvProfile7HDR10Fallback, false) } override val dolbyVisionEnabledFlow: Flow = profileScopedFlow(true) { p, s -> p.boolFor(s, PlaybackSettingsKeys.DolbyVisionEnabled, true) } @@ -312,7 +317,10 @@ class AndroidPlayerSettingsStore( // ---- Doubles ------------------------------------------------------- override val playbackSpeedFlow: Flow = profileScopedFlow(1.0) { p, s -> - p.stringFor(s, PlaybackSettingsKeys.PlaybackSpeed, "1.0").toDoubleOrNull() ?: 1.0 + // Normalized on read too, so a value an older build stored outside + // the contract range (up to 4.0) is not played back as is. + p.stringFor(s, PlaybackSettingsKeys.PlaybackSpeed, "1.0").toDoubleOrNull() + ?.let(PlaybackSpeedRange::normalize) ?: 1.0 } // ---- Ints ---------------------------------------------------------- @@ -478,7 +486,9 @@ class AndroidPlayerSettingsStore( writeStringLocal(PlaybackSettingsKeys.DefaultDownloadQuality, DownloadQuality.fromWire(value).wire) override suspend fun setPlaybackSpeed(value: Double) { - val clamped = value.coerceIn(0.25, 4.0) + // The server refuses a speed outside the contract range or off its + // step, and the flusher then drops the write for good. + val clamped = PlaybackSpeedRange.normalize(value) withScope { scope, store -> store.edit { it[stringPreferencesKey(scope.keyPrefix + PlaybackSettingsKeys.PlaybackSpeed)] = clamped.toString() } serverSettingsFlusher.enqueue( diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStoreTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStoreTest.kt index 89079ad8a6..9c3cf2f6ec 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStoreTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStoreTest.kt @@ -465,12 +465,40 @@ class AndroidPlayerSettingsStoreTest { ) @Test - fun `setPlaybackSpeed clamps out-of-range values`() = runTest { + fun `setPlaybackSpeed clamps to the contract range and step`() = runTest { val store = newStore() store.setPlaybackSpeed(10.0) - assertEquals(4.0, store.playbackSpeedFlow.first(), 0.0) + assertEquals(3.0, store.playbackSpeedFlow.first(), 0.0) + store.setPlaybackSpeed(3.5) + assertEquals(3.0, store.playbackSpeedFlow.first(), 0.0) store.setPlaybackSpeed(0.01) assertEquals(0.25, store.playbackSpeedFlow.first(), 0.0) + // Off the 0.05 grid: the server would refuse it and the write would + // be dropped, so it is snapped before it is stored or sent. + store.setPlaybackSpeed(1.33) + assertEquals(1.35, store.playbackSpeedFlow.first(), 0.0) + assertEquals( + listOf("3.0", "3.0", "0.25", "1.35"), + fakeFlusher.calls.filter { it.key == PlaybackSettingsKeys.PlaybackSpeed }.map { it.value }, + ) + } + + @Test + fun `a playback speed stored by an older build is normalized on read`() = runTest { + // Older builds clamped to 4.0, so a stored speed can sit outside the + // contract range until the next server refresh, or forever offline. + val store = newStoreSeededWith { prefs -> + prefs[stringPreferencesKey(PlaybackSettingsKeys.PlaybackSpeed)] = "3.5" + } + assertEquals(3.0, store.playbackSpeedFlow.first(), 0.0) + } + + @Test + fun `Profile 7 HDR10 fallback defaults off before the first refresh`() = runTest { + // The contract default is false; reading true before hydration (or + // offline) sent Profile 7 sources down the HDR10 path. + assertFalse(newStore().dvProfile7HDR10FallbackFlow.first()) + assertFalse(newStore(profileId = null).dvProfile7HDR10FallbackFlow.first()) } @Test diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/auth/ProfileSwitchTeardown.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/auth/ProfileSwitchTeardown.kt new file mode 100644 index 0000000000..ad9adc59c8 --- /dev/null +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/auth/ProfileSwitchTeardown.kt @@ -0,0 +1,71 @@ +package org.siloserver.silo.android.auth + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.withTimeoutOrNull +import org.siloserver.silo.common.settings.CardPresentationStore +import org.siloserver.silo.common.settings.OverlayPrefsStore +import org.siloserver.silo.common.settings.PlayerSettingsStore +import org.siloserver.silo.common.settings.SeekIntervalStore +import org.siloserver.silo.common.settings.TitleArtStore +import org.siloserver.silo.model.profile.ActiveProfileStore + +/** + * The phone's "Switch Profile", shared by the profile menu and Settings. + * + * Settings writes wait in the flusher's debounce for a moment, and the flusher + * drops a write once its profile is no longer active. So the pending writes are + * pushed first, while the profile they were made on is still the active one + * (the TV switch does the same). Then the shell is left and the per-profile + * caches are dropped, or the next profile keeps rendering, and writing back, + * the previous one's values. + */ +class ProfileSwitchTeardown( + private val playerSettingsStore: PlayerSettingsStore, + private val overlayPrefsStore: OverlayPrefsStore, + private val activeProfileStore: ActiveProfileStore, + private val cardPresentationStore: CardPresentationStore, + private val seekIntervalStore: SeekIntervalStore, + private val titleArtStore: TitleArtStore, + private val flushTimeoutMs: Long = FLUSH_TIMEOUT_MS, +) { + private val _switching = MutableStateFlow(false) + + /** True while a switch is pushing settings; the shell shows progress and blocks input. */ + val switching: StateFlow = _switching.asStateFlow() + + /** + * Push pending settings, then call [leaveShell] and drop per-profile state. + * + * The push is bounded: against an unreachable server each write can wait + * out a connect timeout, and the switch must not hang on that. A write + * still unsent when the bound passes stays queued under the old profile, + * as it would have without this flush. + * + * A request made while a switch is already running is ignored, so a + * second tap during the push cannot open a second profile picker. + * Returns whether this call performed the switch. + */ + suspend fun switchProfile(leaveShell: () -> Unit): Boolean { + if (!_switching.compareAndSet(expect = false, update = true)) return false + try { + withTimeoutOrNull(flushTimeoutMs) { playerSettingsStore.flushPendingDeviceSettings() } + // Navigate before clearing: clearing while the shell is still composed + // repaints it with default cards behind the picker. + leaveShell() + overlayPrefsStore.clear() + activeProfileStore.reset() + cardPresentationStore.clear() + seekIntervalStore.clear() + titleArtStore.clear() + } finally { + _switching.value = false + } + return true + } + + private companion object { + const val FLUSH_TIMEOUT_MS = 5_000L + } +} diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt index bb6f36065d..374480462c 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt @@ -529,6 +529,9 @@ val androidModule = module { single { org.siloserver.silo.android.auth.SignOutTeardown(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } + single { + org.siloserver.silo.android.auth.ProfileSwitchTeardown(get(), get(), get(), get(), get(), get()) + } viewModel { SettingsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } viewModel { DiagnosticsViewModel(get()) } viewModel { DownloadsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/AppNavigation.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/AppNavigation.kt index 625b2296fa..ab651d9a68 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/AppNavigation.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/AppNavigation.kt @@ -22,6 +22,11 @@ import org.siloserver.silo.android.cast.GOOGLE_CAST_LEGACY_SEEK_INTERVALS import org.siloserver.silo.android.ui.screens.auth.DevicePairingWrongServerScreen import org.siloserver.silo.android.ui.screens.auth.DevicePairingUnknownServerScreen import androidx.compose.runtime.collectAsState +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import org.siloserver.silo.android.ui.components.LoadingIndicator import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect @@ -181,11 +186,25 @@ fun AppNavigation( val seekIntervalStore: org.siloserver.silo.common.settings.SeekIntervalStore = koinInject() val titleArtStore: TitleArtStore = koinInject() val signOutTeardown: org.siloserver.silo.android.auth.SignOutTeardown = koinInject() + val profileSwitchTeardown: org.siloserver.silo.android.auth.ProfileSwitchTeardown = koinInject() val siloCastController: SiloCastController = koinInject() // Lives as long as the nav host, so work started from a destination that is // popped in the same gesture (re-hydrating after a profile switch) is not // cancelled with that destination's own scope. val navScope = rememberCoroutineScope() + val profileSwitching by profileSwitchTeardown.switching.collectAsState() + // Both "Switch Profile" entry points (profile menu, Settings) run here, so + // leaving a tab while settings are pushed cannot cancel the switch; the + // teardown ignores a repeat request while one is in flight. + val switchProfile: () -> Unit = remember(navController, profileSwitchTeardown) { + { + navScope.launch { + profileSwitchTeardown.switchProfile { + navController.navigate(Route.ProfileSelection.route) + } + } + } + } val diagnosticsViewModel = koinViewModel() val diagnosticsState by diagnosticsViewModel.state.collectAsState() var activePlayerTargetProvider by remember { @@ -390,6 +409,7 @@ fun AppNavigation( CompositionLocalProvider( LocalSharedTransitionScope provides this, LocalHeroSourceHandoff provides heroSourceHandoff, + LocalProfileSwitch provides switchProfile, ) { Box(modifier = Modifier.fillMaxSize()) { // The first-run screens draw over one shared brand-light backdrop that @@ -951,16 +971,9 @@ fun AppNavigation( onPairDevice = { navController.navigate(Route.PairDevice().route) }, - onSwitchProfile = { - // Leave the shell first, then drop the per-profile caches - // (see the profile-menu path in MainScreen). - navController.navigate(Route.ProfileSelection.route) - overlayPrefsStore.clear() - activeProfileStore.reset() - cardPresentationStore.clear() - seekIntervalStore.clear() - titleArtStore.clear() - }, + // Same switch as the profile menu: push pending settings, + // leave the shell, then drop the per-profile caches. + onSwitchProfile = switchProfile, onNavigateToWatchlist = { navController.navigate(Route.Watchlist.route) }, onNavigateToFavorites = { navController.navigate(Route.Favorites.route) }, onNavigateToHistory = { navController.navigate(Route.History.route) }, @@ -1689,6 +1702,26 @@ fun AppNavigation( enabled = currentRoute != null && currentRoute !in companionHiddenRoutes, ) org.siloserver.silo.android.ui.screens.profiles.HouseholdReverifyHost() + + // While a profile switch pushes pending settings (bounded at a few + // seconds), show that it is under way and take input, so nothing else + // can be opened over a switch that is about to leave the shell. + if (profileSwitching) { + // System Back too: composed after the NavHost, this handler wins, so + // Back can neither pop the screen under the switch nor close the + // app and cancel it. + BackHandler {} + Box( + modifier = Modifier + .fillMaxSize() + .background(Color.Black.copy(alpha = 0.4f)) + .pointerInput(Unit) { + awaitPointerEventScope { while (true) awaitPointerEvent().changes.forEach { it.consume() } } + }, + ) { + LoadingIndicator() + } + } } } } diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/LocalProfileSwitch.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/LocalProfileSwitch.kt new file mode 100644 index 0000000000..fd39d0845a --- /dev/null +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/LocalProfileSwitch.kt @@ -0,0 +1,10 @@ +package org.siloserver.silo.android.ui.navigation + +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * Starts "Switch Profile" in the navigation host's scope, which outlives the + * tab screen the request came from. Run from a tab's own scope, opening a + * title while settings were still being pushed cancelled the switch. + */ +val LocalProfileSwitch = staticCompositionLocalOf<() -> Unit> { {} } diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt index 00b37680cf..f5579ed143 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt @@ -34,7 +34,6 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController -import org.siloserver.silo.model.profile.ActiveProfileStore import org.siloserver.silo.android.ui.components.MainAppHeaderBodyHeight import org.siloserver.silo.android.ui.components.MainAppTopBar import org.siloserver.silo.android.ui.components.TabTopBarActions @@ -76,8 +75,6 @@ import org.siloserver.silo.model.feature.MetadataAiFeatureStore import org.siloserver.silo.model.feature.RequestsFeatureStore import org.siloserver.silo.common.network.ServerReachabilityMonitor import org.siloserver.silo.common.network.ServerReachabilityStatus -import org.siloserver.silo.common.settings.CardPresentationStore -import org.siloserver.silo.common.settings.OverlayPrefsStore import org.siloserver.silo.android.ui.theme.siloPageBackdrop import org.siloserver.silo.network.ApiResult import org.siloserver.silo.network.ServerRegistry @@ -164,12 +161,8 @@ fun MainScreen( val requestsFeatureStore: RequestsFeatureStore = koinInject() val metadataAiFeatureStore: MetadataAiFeatureStore = koinInject() val shuffleFeatureStore: org.siloserver.silo.model.feature.ShuffleFeatureStore = koinInject() - val overlayPrefsStore: OverlayPrefsStore = koinInject() - val activeProfileStore: ActiveProfileStore = koinInject() - val cardPresentationStore: CardPresentationStore = koinInject() - val seekIntervalStore: org.siloserver.silo.common.settings.SeekIntervalStore = koinInject() - val titleArtStore: org.siloserver.silo.common.settings.TitleArtStore = koinInject() val signOutTeardown: org.siloserver.silo.android.auth.SignOutTeardown = koinInject() + val switchProfile = org.siloserver.silo.android.ui.navigation.LocalProfileSwitch.current val reachabilityState by reachabilityMonitor.state.collectAsState() val requestsEnabled by requestsFeatureStore.isEnabled.collectAsState() val reachabilityScope = rememberCoroutineScope() @@ -303,21 +296,12 @@ fun MainScreen( } /** - * Profile-menu "Switch Profile". Overlays and card presentation are cached - * per profile and the app never backgrounds during an in-app switch, so - * drop them here or the next profile keeps rendering — and writing back — - * the previous one's values. Navigate first: clearing while the shell is - * still composed repaints it with default cards behind the picker (the - * TV shell's switch-profile path takes the same order). + * Profile-menu "Switch Profile": pushes pending settings while this + * profile is still active, then leaves the shell and drops the per-profile + * caches (see [org.siloserver.silo.android.auth.ProfileSwitchTeardown]). + * Runs in the navigation host's scope ([org.siloserver.silo.android.ui.navigation.LocalProfileSwitch]). */ - fun switchProfileFromMenu() { - navController.navigate(Route.ProfileSelection.route) - overlayPrefsStore.clear() - activeProfileStore.reset() - cardPresentationStore.clear() - seekIntervalStore.clear() - titleArtStore.clear() - } + fun switchProfileFromMenu() = switchProfile() val requestsMenuAction: (() -> Unit)? = if (requestsEnabled) { { navController.navigate(Route.Requests.route) } } else { diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsViewModel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsViewModel.kt index 0300c41aa1..9f90fd5a51 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsViewModel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsViewModel.kt @@ -84,7 +84,7 @@ data class SettingsUiState( val autoSkipCredits: Boolean = false, val pictureInPictureEnabled: Boolean = true, val dolbyVisionEnabled: Boolean = true, - val dvProfile7HDR10Fallback: Boolean = true, + val dvProfile7HDR10Fallback: Boolean = false, val subtitleMatchesDevice: Boolean = false, val showAudiobooks: Boolean = false, val subtitleAppearance: org.siloserver.silo.model.settings.SubtitleAppearance = diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/auth/ProfileSwitchTeardownTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/auth/ProfileSwitchTeardownTest.kt new file mode 100644 index 0000000000..e49f071df9 --- /dev/null +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/auth/ProfileSwitchTeardownTest.kt @@ -0,0 +1,124 @@ +package org.siloserver.silo.android.auth + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.http.HttpStatusCode +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.siloserver.silo.common.settings.PlayerSettingsStore +import org.siloserver.silo.common.settings.SeekIntervalStore +import org.siloserver.silo.common.settings.TitleArtStore +import org.siloserver.silo.model.profile.ActiveProfileStore +import org.siloserver.silo.network.TokenManagerImpl +import org.siloserver.silo.network.api.ProfileApi +import org.siloserver.silo.network.apiv2.ApiV2Gate +import org.siloserver.silo.repository.ProfileRepository +import java.lang.reflect.Proxy +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * A settings write waits out the flusher's debounce, and the flusher drops it + * once its profile is no longer active. The phone switch has to push pending + * writes before it leaves the shell, as the TV switch does. + */ +class ProfileSwitchTeardownTest { + private val http = HttpClient(MockEngine { respond("", HttpStatusCode.NoContent) }) + + @AfterTest fun tearDown() = http.close() + + @Test + fun pendingSettingsAreFlushedBeforeLeavingTheShell() = runTest { + val events = mutableListOf() + val settings = object : PlayerSettingsStore by idle() { + override suspend fun flushPendingDeviceSettings() { + events += "flush" + } + } + val teardown = teardown(settings, onClear = { events += "clear:$it" }) + + teardown.switchProfile { events += "leave" } + + assertEquals("flush", events.first()) + assertEquals("leave", events[1], "the shell is left only after the flush") + assertEquals( + setOf("clear:overlays", "clear:cards", "clear:seek", "clear:titleArt"), + events.drop(2).toSet(), + ) + } + + @Test + fun aFlushThatCannotFinishDoesNotBlockTheSwitch() = runTest { + var left = false + val settings = object : PlayerSettingsStore by idle() { + override suspend fun flushPendingDeviceSettings() = awaitCancellation() + } + + teardown(settings, flushTimeoutMs = 5_000).switchProfile { left = true } + + assertEquals(true, left) + assertEquals(5_000, currentTime) + } + + @Test + fun aSecondRequestWhileSwitchingIsIgnored() = runTest { + val flushGate = CompletableDeferred() + val settings = object : PlayerSettingsStore by idle() { + override suspend fun flushPendingDeviceSettings() = flushGate.await() + } + val teardown = teardown(settings) + var left = 0 + + val first = async { teardown.switchProfile { left++ } } + runCurrent() + assertTrue(teardown.switching.value, "the first switch is still pushing settings") + // A second tap during the push must not open a second profile picker. + assertFalse(teardown.switchProfile { left++ }) + + flushGate.complete(Unit) + assertTrue(first.await()) + assertEquals(1, left) + assertFalse(teardown.switching.value) + + // Once finished, the next switch runs normally. + assertTrue(teardown.switchProfile { left++ }) + assertEquals(2, left) + } + + private fun teardown( + settings: PlayerSettingsStore, + onClear: (String) -> Unit = {}, + flushTimeoutMs: Long = 5_000, + ) = ProfileSwitchTeardown( + playerSettingsStore = settings, + overlayPrefsStore = recordingClear("overlays", onClear), + activeProfileStore = ActiveProfileStore(ProfileRepository(ProfileApi(http, ApiV2Gate.Unrestricted), TokenManagerImpl())), + cardPresentationStore = recordingClear("cards", onClear), + seekIntervalStore = recordingClear("seek", onClear), + titleArtStore = recordingClear("titleArt", onClear), + flushTimeoutMs = flushTimeoutMs, + ) + + /** A store that reports its `clear()` and otherwise answers nothing. */ + private inline fun recordingClear(name: String, crossinline onClear: (String) -> Unit): T = + Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ -> + if (method.name == "clear") onClear(name) + if (Flow::class.java.isAssignableFrom(method.returnType)) emptyFlow() else Unit + } as T + + /** Collaborators the switch doesn't depend on: they answer nothing and emit nothing. */ + private inline fun idle(): T = + Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ -> + if (Flow::class.java.isAssignableFrom(method.returnType)) emptyFlow() else Unit + } as T +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsViewModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsViewModel.kt index 3fd1420870..98122ae775 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsViewModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsViewModel.kt @@ -124,7 +124,7 @@ class TvSettingsViewModel( val dolbyVisionEnabled: Boolean = true, val showAudiobooksTab: Boolean = false, val subtitleMatchesDevice: Boolean = false, - val dvProfile7HDR10Fallback: Boolean = true, + val dvProfile7HDR10Fallback: Boolean = false, val forceHdrPassthrough: Boolean = false, val trueBlackBars: Boolean = false, val autoSkipCredits: Boolean = false, diff --git a/shared/src/androidUnitTest/kotlin/org/siloserver/silo/model/settings/PlayerSettingsContractTest.kt b/shared/src/androidUnitTest/kotlin/org/siloserver/silo/model/settings/PlayerSettingsContractTest.kt new file mode 100644 index 0000000000..dfe4c545c9 --- /dev/null +++ b/shared/src/androidUnitTest/kotlin/org/siloserver/silo/model/settings/PlayerSettingsContractTest.kt @@ -0,0 +1,56 @@ +package org.siloserver.silo.model.settings + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.double +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse + +/** + * Pins the client-side restatements of manifest facts to the vendored + * manifest, so a re-vendor that changes them fails here. + */ +class PlayerSettingsContractTest { + + private val definitions by lazy { + val raw = checkNotNull(javaClass.classLoader?.getResource("settings/v1/manifest.json")) { + "Missing test resource settings/v1/manifest.json" + }.readText() + Json.parseToJsonElement(raw).jsonObject.getValue("definitions").jsonArray + .map { it.jsonObject } + .associateBy { it.getValue("key").jsonPrimitive.content } + } + + @Test + fun playbackSpeedBoundsMatchTheManifest() { + val schema = definitions.getValue(SettingKeys.PLAYER_PLAYBACK_SPEED) + .getValue("value_schema").jsonObject + assertEquals(PlaybackSpeedRange.MIN, schema.getValue("minimum").jsonPrimitive.double) + assertEquals(PlaybackSpeedRange.MAX, schema.getValue("maximum").jsonPrimitive.double) + assertEquals(PlaybackSpeedRange.STEP, schema.getValue("step").jsonPrimitive.double) + } + + @Test + fun profile7FallbackDefaultsOff() { + // AndroidPlayerSettingsStore falls back to this before the first + // refresh; it has to agree with what the server would resolve. + assertFalse( + definitions.getValue(SettingKeys.PLAYER_DV_PROFILE7_HDR10_FALLBACK) + .getValue("default_value").jsonPrimitive.boolean, + ) + } + + @Test + fun normalizeClampsAndSnapsToTheStep() { + assertEquals(3.0, PlaybackSpeedRange.normalize(4.0)) + assertEquals(0.25, PlaybackSpeedRange.normalize(0.01)) + assertEquals(1.35, PlaybackSpeedRange.normalize(1.33)) + assertEquals(1.25, PlaybackSpeedRange.normalize(1.25)) + assertEquals(2.5, PlaybackSpeedRange.normalize(2.5)) + assertEquals(1.0, PlaybackSpeedRange.normalize(Double.NaN)) + } +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSpeedRange.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSpeedRange.kt new file mode 100644 index 0000000000..5d5542ed44 --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSpeedRange.kt @@ -0,0 +1,27 @@ +package org.siloserver.silo.model.settings + +import kotlin.math.roundToLong + +/** + * The bounds of `player.playback_speed`: 0.25..3.0 in 0.05 steps. + * + * The generated [SettingKeys] carry no value bounds yet, so they are restated + * here and pinned to the vendored manifest by `PlayerSettingsContractTest`. + * The server enforces the step as well as the range, so a value off the grid is + * refused like one out of range, and the write is dropped. + */ +object PlaybackSpeedRange { + const val MIN = 0.25 + const val MAX = 3.0 + const val STEP = 0.05 + + /** [value] clamped to the range and rounded to the nearest step. */ + fun normalize(value: Double): Double { + if (value.isNaN()) return 1.0 + val clamped = value.coerceIn(MIN, MAX) + // Steps per unit (20), so the result is a whole number of steps + // divided once, which lands on the nearest double to the step value. + val stepsPerUnit = (1 / STEP).roundToLong() + return (clamped * stepsPerUnit).roundToLong().toDouble() / stepsPerUnit + } +}