From 6ad4de4a4ba7ff1a54e29eeca2da85c23f5af799 Mon Sep 17 00:00:00 2001 From: Rhainland Date: Wed, 18 Nov 2026 11:04:01 +0100 Subject: [PATCH 1/4] fix(player): time Up Next from the end of the file, not the credits marker The Show Next Up setting offers "At end" and "N seconds before end", but on an episode with a credits marker both apps opened the card at the credits start whatever was chosen. The TV player never read the setting at all. Both players now open Up Next when playback crosses the chosen number of seconds before the end of the file, and only when the stream ends for "At end", as the iOS and tvOS player already does. Credits markers still drive Skip Credits; skipping credits that run to the end ends the stream, which opens the card. The TV settings screen now assumes the same 30-second default as the settings store and the server. Fixes #910 --- .../ui/screens/player/PlayerViewModel.kt | 38 ++++++++----------- ...erViewModelLoadOwnershipIntegrationTest.kt | 30 +++++++++++++++ .../tv/ui/screens/player/TvPlayerViewModel.kt | 32 +++++++++------- .../screens/settings/TvSettingsViewModel.kt | 2 +- .../silo/domain/player/MarkerTimeline.kt | 15 -------- .../silo/domain/player/NextUpPrompt.kt | 25 ++++++++++++ .../silo/domain/player/MarkerTimelineTest.kt | 12 ------ .../silo/domain/player/NextUpPromptTest.kt | 26 +++++++++++++ 8 files changed, 117 insertions(+), 63 deletions(-) create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/NextUpPromptTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt index 1c4aa77d21..2b3a174bd4 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt @@ -94,6 +94,7 @@ import org.siloserver.silo.model.catalog.FileVersion import org.siloserver.silo.model.catalog.VersionChapter import org.siloserver.silo.domain.player.MarkerKind import org.siloserver.silo.domain.player.MarkerTimeline +import org.siloserver.silo.domain.player.NextUpPrompt import org.siloserver.silo.model.catalog.MarkerSegment import org.siloserver.silo.model.catalog.TimeRange import org.siloserver.silo.model.settings.SubtitleAppearance @@ -1036,8 +1037,7 @@ class PlayerViewModel( .stateIn(viewModelScope, SharingStarted.Eagerly, IntroSkipMode.Default) val autoPlayNextEnabled: StateFlow = playerSettingsStore.autoPlayNextFlow .stateIn(viewModelScope, SharingStarted.Eagerly, true) - // Seconds before end to surface the Up Next card when no credits marker - // exists (0 = only at end). Credits marker wins when present. + // Seconds before the end of the file to surface Up Next (0 = only at end). private val nextUpPromptSeconds: StateFlow = playerSettingsStore.nextUpPromptSecondsFlow .stateIn(viewModelScope, SharingStarted.Eagerly, 30) @@ -3304,22 +3304,16 @@ class PlayerViewModel( ) } - // F2: surface the Up Next card when playback CROSSES the credits point - // (only on the before->after transition, so resuming inside the credits - // doesn't instantly trigger it). Without a credits marker, fall back to - // crossing (duration - nextUpPromptSeconds); 0 = only at end (iOS parity). - if (!seekWasActive) { - val creditsStart = _uiState.value.markerTimeline.upNextCreditsStart() - if (creditsStart != null) { - if (previousPosition < creditsStart && positionSec >= creditsStart) onApproachingEnd() - } else { - val promptSeconds = nextUpPromptSeconds.value - val duration = _uiState.value.duration - if (promptSeconds > 0 && duration > 0) { - val promptStart = duration - promptSeconds - if (previousPosition < promptStart && positionSec >= promptStart) onApproachingEnd() - } - } + // Surface Up Next when playback crosses the chosen point before the end + // of the file. Only the crossing counts, so resuming or seeking past it + // doesn't open the card; the stream ending still does. + if ( + !seekWasActive && + NextUpPrompt.crossesPromptPoint( + previousPosition, positionSec, _uiState.value.duration, nextUpPromptSeconds.value, + ) + ) { + onApproachingEnd() } // Forward to the lifecycle so its 10s reporter has a fresh sample. @@ -6174,12 +6168,12 @@ class PlayerViewModel( } /** - * Credits reached (primary) or stream ended (fallback) — surface the Up Next - * card. When auto-play is on and the consecutive-auto-advance streak is + * The Next Up point before the end was crossed, or the stream ended — + * surface the Up Next card. When auto-play is on and the consecutive-auto-advance streak is * below the pass-out threshold, the card runs a countdown that plays the * next episode at zero. Once the streak hits the threshold (or auto-play is * off), the card shows WITHOUT a countdown so the user must explicitly - * choose (the pass-out gate). The credits prompt is once per episode; + * choose (the pass-out gate). The before-end prompt is once per episode; * a dismissed card reopens when playback ends. * * [videoEnded] is true on STATE_ENDED — the card reads "Playing Next"; a @@ -6262,7 +6256,7 @@ class PlayerViewModel( // Two anchors (iOS parity — silo-apple's PlayerViewModel derives the // countdown from movieTime and only auto-plays once playback truly // ends): - // - Card committed BEFORE the end (credits / prompt crossing): the + // - Card committed BEFORE the end (before-end crossing): the // countdown mirrors the remaining playback time, so it freezes on // pause, grows on a backward seek, and the advance fires only when // the player reports STATE_ENDED — never truncating the tail of an diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt index b32a921c2e..f733fadb67 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt @@ -456,6 +456,36 @@ class PlayerViewModelLoadOwnershipIntegrationTest { } } + @Test + fun nextUpOpensAtThePromptSecondsBeforeTheFileEndNotAtTheCreditsMarker() = runTest(dispatcher) { + val starter = DeferredNonCooperativeStarter() + val fixture = playerViewModel(starter, backgroundScope) + val store = ViewModelStore().also { it.put("player", fixture.viewModel) } + try { + val viewModel = fixture.viewModel + viewModel.loadContent("episode-a", preferredFileId = 1) + starter.awaitRequestCount(1) + starter.complete(0, ready(starter.request(0), "session-a")) + viewModel.awaitState { it.sessionId == "session-a" && !it.isLoading } + viewModel.onMediaMountApplied(viewModel.uiState.value.mediaMountGeneration) + viewModel.offerNextEpisode() + viewModel.mutableUiState().update { + it.copy(credits = org.siloserver.silo.model.catalog.TimeRange(1000.0, 1200.0)) + } + + // The fake settings store chooses 30 seconds before the end. + viewModel.onPositionChanged(999_000L, 1_200_000L) + viewModel.onPositionChanged(1_001_000L, 1_200_000L) + assertFalse(viewModel.uiState.value.showUpNext) + viewModel.onPositionChanged(1_169_500L, 1_200_000L) + assertFalse(viewModel.uiState.value.showUpNext) + viewModel.onPositionChanged(1_170_500L, 1_200_000L) + assertTrue(viewModel.uiState.value.showUpNext) + } finally { + store.clear() + } + } + @Test fun keepWatchingSuppressesCreditsPromptButReopensNextUpAtPlaybackEnd() = runTest(dispatcher) { val starter = DeferredNonCooperativeStarter() diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt index 5847428ae1..358b46aac2 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt @@ -109,6 +109,7 @@ import org.siloserver.silo.model.catalog.AudioTrack import org.siloserver.silo.model.catalog.FileVersion import org.siloserver.silo.domain.player.MarkerKind import org.siloserver.silo.domain.player.MarkerTimeline +import org.siloserver.silo.domain.player.NextUpPrompt import org.siloserver.silo.model.catalog.MarkerSegment import org.siloserver.silo.model.catalog.TimeRange import org.siloserver.silo.model.catalog.VersionChapter @@ -2008,6 +2009,9 @@ class TvPlayerViewModel( // Per-profile "Still watching?" threshold (default 3; 0 = off). val passOutThreshold: StateFlow = playerSettingsStore.passOutThresholdFlow .stateIn(viewModelScope, SharingStarted.Eagerly, 3) + // Seconds before the end of the file to surface Up Next (0 = only at end). + private val nextUpPromptSeconds: StateFlow = playerSettingsStore.nextUpPromptSecondsFlow + .stateIn(viewModelScope, SharingStarted.Eagerly, 30) val hdrEnabled: StateFlow = playerSettingsStore.hdrEnabledFlow .stateIn(viewModelScope, SharingStarted.Eagerly, true) val dolbyVisionEnabled: StateFlow = playerSettingsStore.dolbyVisionEnabledFlow @@ -3880,14 +3884,16 @@ class TvPlayerViewModel( if (positionSec > 0 && transientNetworkRetries > 0) { transientNetworkRetries = 0 } - // F2: auto-advance / prompt when playback CROSSES the credits point — - // only on the transition from before to after, so resuming an episode - // whose saved position is already inside the credits doesn't instantly - // skip to the next one (a seek into credits also won't trigger it). - if (!seekWasActive) { - _uiState.value.markerTimeline.upNextCreditsStart()?.let { creditsStart -> - if (previousPosition < creditsStart && positionSec >= creditsStart) onApproachingEnd() - } + // Surface Up Next when playback crosses the chosen point before the end + // of the file. Only the crossing counts, so resuming or seeking past it + // doesn't open the card; the stream ending still does. + if ( + !seekWasActive && + NextUpPrompt.crossesPromptPoint( + previousPosition, positionSec, _uiState.value.duration, nextUpPromptSeconds.value, + ) + ) { + onApproachingEnd() } // Forward to the lifecycle so its 10s reporter has a fresh sample. sessionLifecycle.reportPosition( @@ -5367,12 +5373,12 @@ class TvPlayerViewModel( * pass-out threshold, the overlay starts a countdown ring that plays the * next episode at zero. Once the streak hits the pass-out threshold (or * auto-play is off), the overlay shows with NO countdown so the user must - * explicitly choose Play Now / Keep Watching (the pass-out gate). The credits + * explicitly choose Play Now / Keep Watching (the pass-out gate). The before-end * prompt is once per episode; a dismissed card reopens when playback ends. * * [videoEnded] true when the stream has actually ended (STATE_ENDED) — the * panel reads "End of playback" / "Playing Next" and hides Keep Watching; - * false at the credits-crossing while video is still rolling. + * false at the before-end crossing while video is still rolling. */ fun onApproachingEnd(videoEnded: Boolean = false) { if (nextUpTransitionGate.isActive) return @@ -5451,7 +5457,7 @@ class TvPlayerViewModel( } /** - * Surface Up Next on demand, ahead of the credits trigger. + * Surface Up Next on demand, ahead of the before-end trigger. * * Routed through the same commit the automatic timing uses so the overlay, * the countdown gating and the auto-advance accounting behave identically — @@ -5509,7 +5515,7 @@ class TvPlayerViewModel( nextUpCountdownJob?.cancel() nextUpCountdownJob = viewModelScope.launch { // Two anchors, matching phone and tvOS: - // - Card committed BEFORE the end (credits crossing): the countdown + // - Card committed BEFORE the end (before-end crossing): the countdown // mirrors the remaining playback time, so it freezes on pause, // grows on a backward seek, and the advance fires only once the // player reports the stream ended. A fixed wall clock here cut off @@ -6614,7 +6620,7 @@ class TvPlayerViewModel( */ fun onSelectIntroPrompt(): Double? { val target = introAutoSkipController.select() ?: return null - // Pre-write the resolved source position so the credits crossing check + // Pre-write the resolved source position so the Next Up crossing check // treats this as a deliberate jump. The caller routes the actual seek // through either the room controller or seekImmediate; the latter owns // the pending-position guard for solo playback. 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 15af51d852..7989b93d9b 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 @@ -168,7 +168,7 @@ class TvSettingsViewModel( val passOutThreshold: Int = 3, // Seconds before the end of an episode to surface the Up-Next prompt // (0 = at the very end). Mirrors tvOS `nextUpPromptSeconds`. - val nextUpPromptSeconds: Int = 10, + val nextUpPromptSeconds: Int = 30, /** * Keys this device holds its own value for. A profile-layered control * whose key is absent shows "Use profile setting" as its choice. diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt index c1b7ffa5d3..d12e0f626d 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt @@ -53,21 +53,6 @@ class MarkerTimeline private constructor(private val regions: List= start - 1) start = minOf(start, range.start) - } - return start - } - companion object { val EMPTY = MarkerTimeline(emptyList()) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt new file mode 100644 index 0000000000..b5597323b6 --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt @@ -0,0 +1,25 @@ +package org.siloserver.silo.domain.player + +/** + * When the Up Next card opens before an episode ends: `playback.next_up_prompt_seconds` + * before the end of the file, matching iOS/tvOS (`PlayerNextUpCompletionPolicy`) and the + * web. Credits markers drive Skip Credits only; they do not move this point. + */ +object NextUpPrompt { + /** + * True when playback moves from [previousPosition] to [position] across the point + * [promptSeconds] before [duration]. Only the crossing counts, so resuming or seeking + * past that point doesn't open the card. [promptSeconds] 0 ("At end") or an unknown + * duration never opens it early; the card then waits for the stream to end. + */ + fun crossesPromptPoint( + previousPosition: Double, + position: Double, + duration: Double, + promptSeconds: Int, + ): Boolean { + if (promptSeconds <= 0 || duration <= 0) return false + val promptStart = duration - promptSeconds + return previousPosition < promptStart && position >= promptStart + } +} diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt index 1c09aca187..7349fc41b5 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt @@ -87,16 +87,4 @@ class MarkerTimelineTest { assertEquals(TimeRange(30.0, 90.0), twoIntros.occurrenceAt(MarkerKind.Intro, 300.0)) assertEquals(TimeRange(600.0, 660.0), twoIntros.occurrenceAt(MarkerKind.Intro, 600.0)) } - - @Test fun upNextWaitsForTheLastCreditsRangeSoAMidCreditsScenePlays() { - assertEquals(3189.0, timeline.upNextCreditsStart()) - val touching = MarkerTimeline.resolve( - segments = listOf(MarkerSegment("credits", 1200.0, 1250.0), MarkerSegment("credits", 1250.5, 1300.0)), - intro = null, credits = null, recap = null, preview = null, - ) - assertEquals(1200.0, touching.upNextCreditsStart()) - val single = MarkerTimeline.resolve(null, intro = null, credits = TimeRange(1200.0, 1260.0), recap = null, preview = null) - assertEquals(1200.0, single.upNextCreditsStart()) - assertNull(MarkerTimeline.EMPTY.upNextCreditsStart()) - } } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/NextUpPromptTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/NextUpPromptTest.kt new file mode 100644 index 0000000000..c72ef76efb --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/NextUpPromptTest.kt @@ -0,0 +1,26 @@ +package org.siloserver.silo.domain.player + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class NextUpPromptTest { + // A 48:12 episode whose credits marker starts at 46:31: the marker must + // not move the prompt (silo-android#910). + private val duration = 2892.0 + + @Test fun promptOpensWhenPlaybackCrossesTheChosenSecondsBeforeTheEnd() { + assertTrue(NextUpPrompt.crossesPromptPoint(2861.6, 2862.1, duration, promptSeconds = 30)) + assertTrue(NextUpPrompt.crossesPromptPoint(2881.5, 2882.0, duration, promptSeconds = 10)) + assertFalse(NextUpPrompt.crossesPromptPoint(2791.0, 2792.0, duration, promptSeconds = 30)) + } + + @Test fun playbackAlreadyPastThePointDoesNotReopenThePrompt() { + assertFalse(NextUpPrompt.crossesPromptPoint(2870.0, 2870.5, duration, promptSeconds = 30)) + } + + @Test fun atEndAndUnknownDurationNeverOpenBeforeTheStreamEnds() { + assertFalse(NextUpPrompt.crossesPromptPoint(2891.0, 2892.0, duration, promptSeconds = 0)) + assertFalse(NextUpPrompt.crossesPromptPoint(10.0, 11.0, 0.0, promptSeconds = 30)) + } +} From 445ca87c190423029e17cbcae34ef20ba02d9ea0 Mon Sep 17 00:00:00 2001 From: Rhainland Date: Wed, 18 Nov 2026 11:14:50 +0100 Subject: [PATCH 2/4] fix(tv): keep returning the series page to the next episode from the credits Moving Up Next to the end of the file also moved the point at which the TV player treats an episode as finished for the series page. Leaving during the closing credits then opened the series on the episode just watched, and leaving after an early prompt during the final scene opened it on the next one. Record the closing-credits crossing on its own again, and count the Up Next prompt only when the stream has ended. Update the comments that still described the credits-based trigger. --- .../ui/screens/player/PlayerViewModel.kt | 14 ++++++------- .../tv/ui/screens/player/TvPlayerScreen.kt | 4 ++-- .../tv/ui/screens/player/TvPlayerViewModel.kt | 21 +++++++++++++------ .../silo/domain/player/MarkerTimeline.kt | 15 +++++++++++++ .../silo/domain/player/NextUpPrompt.kt | 4 ++-- .../silo/domain/player/MarkerTimelineTest.kt | 12 +++++++++++ 6 files changed, 53 insertions(+), 17 deletions(-) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt index 2b3a174bd4..ccff3c7b9a 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt @@ -702,7 +702,7 @@ class PlayerViewModel( val awaitingFirstFrame: Boolean get() = startedContentId != contentId - /** The marker occurrences the skip controls and Up Next read. */ + /** The marker occurrences the skip controls read. */ val markerTimeline: MarkerTimeline by lazy { MarkerTimeline.resolve(markerSegments, intro = intro, credits = credits, recap = recap, preview = preview) } @@ -1071,7 +1071,7 @@ class PlayerViewModel( // same VM persists across episodes and the guard accumulates the streak. // The guard reads the threshold lazily so a settings change applies live. private val autoPlayGuard = AutoPlayGuard(threshold = { passOutThreshold.value }) - // Once-per-episode guard for the credits/ended trigger; reset on each load. + // Once-per-episode guard for the before-end/ended trigger; reset on each load. private var autoAdvanceHandled = false // End point fired before the next episode resolved — remember it (and the // strongest videoEnded flag seen) so resolveNextEpisode can commit the card. @@ -4822,8 +4822,8 @@ class PlayerViewModel( /** * Adopt the playing file's marker ranges (a `markers_updated` event or a - * reconcile read). The intro auto-skip observer and the credits-based F2 - * trigger read these from UiState, so updating them takes effect + * reconcile read). The intro auto-skip observer and the skip controls + * read these from UiState, so updating them takes effect * immediately. Passing `null` clears a marker the server says no longer * applies. */ @@ -6156,7 +6156,7 @@ class PlayerViewModel( it.copy(nextEpisode = info) } if (_uiState.value.contentId != forContentId) return@launch - // If the credits/end point already fired while we were still + // If the before-end/end point already fired while we were still // resolving, the card couldn't arm — commit it now with the // strongest video-ended flag observed. if (!autoAdvanceHandled) { @@ -6196,7 +6196,7 @@ class PlayerViewModel( } if (autoAdvanceHandled) { if (videoEnded) { - // Keep Watching dismisses the credits prompt, but finishing the + // Keep Watching dismisses the before-end prompt, but finishing the // episode must still offer Play Now without restarting its timer. _uiState.update { it.copy(showUpNext = true, upNextVideoEnded = true) } } @@ -6302,7 +6302,7 @@ class PlayerViewModel( /** * Up Next dismiss — cancel the countdown and stay on the current playback. - * Suppress further credits prompts; playback end still reopens the card. + * Suppress further before-end prompts; playback end still reopens the card. */ fun dismissUpNext() { if (nextUpTransitionGate.isActive) return diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt index 237e656540..089fb0ba09 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt @@ -2483,7 +2483,7 @@ fun TvPlayerScreen( } else { // seekImmediate pre-writes position so a scrub // committed into the credits region isn't mistaken - // for natural playback crossing the credits point. + // for natural playback crossing the Up Next point. viewModel.seekImmediate(targetSec) } viewModel.setControlsVisible(true) @@ -2623,7 +2623,7 @@ fun TvPlayerScreen( } else { // Solo: seekImmediate pre-writes position so a // chapter jump into credits isn't mistaken for - // natural playback crossing the credits point. + // natural playback crossing the Up Next point. viewModel.seekImmediate(sec) } } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt index 358b46aac2..8077933766 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt @@ -1862,8 +1862,8 @@ class TvPlayerViewModel( // ---- Next-episode auto-advance (F2) ---- private var autoAdvanceCount: Int = launchArgs.autoAdvanceCount private var autoAdvanceHandled = false // once-per-item guard - // The credits or the end of this item was reached. Unlike autoAdvanceHandled, - // opening Up Next by hand or Keep Watching never sets it. + // Playback reached the closing credits or the end of this item. Unlike + // autoAdvanceHandled, opening Up Next by hand or Keep Watching never sets it. private var reachedCreditsOrEnd = false // The identity generation this player was launched under. private val launchIdentityGeneration: Long? = identityTransitions?.generation?.value @@ -3895,6 +3895,13 @@ class TvPlayerViewModel( ) { onApproachingEnd() } + // Playing into the closing credits counts as finishing the episode for + // the series page, though Up Next waits for the prompt point. + if (!seekWasActive && roomId == null) { + _uiState.value.markerTimeline.finalCreditsStart()?.let { creditsStart -> + if (previousPosition < creditsStart && positionSec >= creditsStart) reachedCreditsOrEnd = true + } + } // Forward to the lifecycle so its 10s reporter has a fresh sample. sessionLifecycle.reportPosition( positionSec = positionSec, @@ -5240,7 +5247,7 @@ class TvPlayerViewModel( /** * Adopt the playing file's marker ranges (a `markers_updated` event or a - * reconcile read). Skip-intro and the credits-based F2 trigger read these + * reconcile read). Skip-intro and the skip controls read these * from UiState, so the update takes effect immediately; `null` clears a * marker the server dropped. */ @@ -5364,7 +5371,7 @@ class TvPlayerViewModel( } /** - * Called by the screen when the credits point is reached (primary) or the + * Called when playback crosses the Up Next point before the end or the * stream ends (fallback). Surfaces the Up-Next overlay — a 16:9 mini-player * beside the next-episode panel — as the end-of-playback surface (mirrors * tvOS PlayerNextUpScreen), replacing the old "Still watching?" dialog. @@ -5387,8 +5394,10 @@ class TvPlayerViewModel( // transport gate. if (roomId != null) return // Recorded before the once-per-item guard below, which Keep Watching on - // a hand-opened Up Next also sets. - reachedCreditsOrEnd = true + // a hand-opened Up Next also sets. The before-end prompt can open while + // the story is still playing, so only the end counts here; the closing + // credits are recorded where playback crosses them. + if (videoEnded) reachedCreditsOrEnd = true if (shufflePlayback != null) { // A multi-part pick plays its later parts before the shuffle moves on. shuffleNextPartFileId?.let { fileId -> diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt index d12e0f626d..6a906a425a 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/MarkerTimeline.kt @@ -53,6 +53,21 @@ class MarkerTimeline private constructor(private val regions: List= start - 1) start = minOf(start, range.start) + } + return start + } + companion object { val EMPTY = MarkerTimeline(emptyList()) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt index b5597323b6..70f4df3e0c 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt @@ -2,8 +2,8 @@ package org.siloserver.silo.domain.player /** * When the Up Next card opens before an episode ends: `playback.next_up_prompt_seconds` - * before the end of the file, matching iOS/tvOS (`PlayerNextUpCompletionPolicy`) and the - * web. Credits markers drive Skip Credits only; they do not move this point. + * before the end of the file, as on iOS/tvOS (`PlayerNextUpCompletionPolicy`). Credits + * markers drive Skip Credits; they do not move this point. */ object NextUpPrompt { /** diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt index 7349fc41b5..77ab2ef89e 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/domain/player/MarkerTimelineTest.kt @@ -87,4 +87,16 @@ class MarkerTimelineTest { assertEquals(TimeRange(30.0, 90.0), twoIntros.occurrenceAt(MarkerKind.Intro, 300.0)) assertEquals(TimeRange(600.0, 660.0), twoIntros.occurrenceAt(MarkerKind.Intro, 600.0)) } + + @Test fun finalCreditsStartSkipsAMidCreditsScene() { + assertEquals(3189.0, timeline.finalCreditsStart()) + val touching = MarkerTimeline.resolve( + segments = listOf(MarkerSegment("credits", 1200.0, 1250.0), MarkerSegment("credits", 1250.5, 1300.0)), + intro = null, credits = null, recap = null, preview = null, + ) + assertEquals(1200.0, touching.finalCreditsStart()) + val single = MarkerTimeline.resolve(null, intro = null, credits = TimeRange(1200.0, 1260.0), recap = null, preview = null) + assertEquals(1200.0, single.finalCreditsStart()) + assertNull(MarkerTimeline.EMPTY.finalCreditsStart()) + } } From 9a0ef16d22f0c4d7d41a8cc61053104280f4aeb5 Mon Sep 17 00:00:00 2001 From: Rhainland Date: Wed, 18 Nov 2026 11:30:09 +0100 Subject: [PATCH 3/4] feat(player): let viewers turn Next Up off Viewers who would rather go back to the series at the end of an episode cannot turn the Next Up card off; Auto-play Next only stops its countdown. The Show Next Up picker on phone and TV now offers Off first. It writes playback.next_up_enabled (settings revision 30), and choosing a time turns Next Up back on. With Off the player opens no card before or at the end and closes the way Back does when playback ends; a shuffle still moves on. One control owns both Next Up keys, so Use profile setting clears them together. A server whose settings manifest lacks the key is never sent it: the picker hides Off and Next Up stays on there, as with the buffering quality mode. The settings bindings and the vendored manifest move to revision 30. --- .../settings/AndroidPlayerSettingsStore.kt | 65 +++++++++++++------ .../silo/common/settings/NextUpChoice.kt | 44 +++++++++++++ .../common/settings/PlayerSettingsStore.kt | 17 +++++ .../AndroidPlayerSettingsStoreTest.kt | 37 +++++++++++ .../silo/common/settings/NextUpChoiceTest.kt | 16 +++++ .../android/ui/screens/player/PlayerScreen.kt | 5 ++ .../ui/screens/player/PlayerViewModel.kt | 16 +++++ .../ui/screens/settings/PlaybackSettings.kt | 27 ++++---- .../ui/screens/settings/SettingsPages.kt | 4 +- .../ui/screens/settings/SettingsViewModel.kt | 16 ++++- ...erViewModelLoadOwnershipIntegrationTest.kt | 37 ++++++++++- .../tv/ui/screens/player/TvPlayerScreen.kt | 4 ++ .../tv/ui/screens/player/TvPlayerViewModel.kt | 19 ++++++ .../ui/screens/settings/TvSettingsScreen.kt | 36 +++++----- .../screens/settings/TvSettingsViewModel.kt | 18 ++++- .../model/settings/PlaybackSettingsKeys.kt | 13 +++- .../silo/model/settings/SettingKeys.kt | 6 +- .../commonTest/resources/settings/v1/SOURCE | 8 +-- .../resources/settings/v1/conformance.json | 4 +- .../resources/settings/v1/manifest.json | 18 ++++- 20 files changed, 341 insertions(+), 69 deletions(-) create mode 100644 android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt create mode 100644 android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt 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 0eb825548b..daee0ba622 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 @@ -268,18 +268,21 @@ class AndroidPlayerSettingsStore( } /** - * Whether the active server's manifest defines - * `playback.buffering_quality_mode`: null until its manifest is read. + * Whether the active server's manifest defines [key], one of + * [PlaybackSettingsKeys.ManifestDetectedKeys]: null until its manifest is read. */ - private val bufferingQualityModeDefined: Flow = + private fun manifestDefines(key: String): Flow = if (contractRevision == null) { flowOf(true) } else { combine(currentScopeFlow, contractRevision.known) { scope, _ -> - scope?.let { contractRevision.stores(it.serverUrl, PlaybackSettingsKeys.BufferingQualityMode) } + scope?.let { contractRevision.stores(it.serverUrl, key) } }.distinctUntilChanged() } + private val bufferingQualityModeDefined: Flow = + manifestDefines(PlaybackSettingsKeys.BufferingQualityMode) + // No legacy boolean behind this one: an absent or unknown value is the // contract default. Until the server's manifest is read, the last mode // seen here applies; a server without the setting plays the default, and @@ -297,6 +300,21 @@ class AndroidPlayerSettingsStore( override val bufferingQualityModeSupportedFlow: Flow = bufferingQualityModeDefined.map { it == true }.distinctUntilChanged() + private val nextUpEnabledDefined: Flow = + manifestDefines(PlaybackSettingsKeys.NextUpEnabled) + + // As with the buffering mode: until the manifest is read the last choice + // seen applies, and a server without the setting keeps Next Up on. + override val nextUpEnabledFlow: Flow = + combine( + profileScopedFlow(true) { p, s -> p.boolFor(s, PlaybackSettingsKeys.NextUpEnabled, true) }, + nextUpEnabledDefined, + ) { enabled, defined -> enabled || defined == false } + .distinctUntilChanged() + + override val nextUpEnabledSupportedFlow: Flow = + nextUpEnabledDefined.map { it == true }.distinctUntilChanged() + // ---- Booleans ------------------------------------------------------ override val autoSkipCreditsFlow: Flow = profileScopedFlow(false) { p, s -> p.boolFor(s, PlaybackSettingsKeys.AutoSkipCredits, false) } @@ -525,22 +543,10 @@ class AndroidPlayerSettingsStore( /** * Settings offers this only while the server's manifest defines the key - * ([bufferingQualityModeSupportedFlow]). Like [setCellularQuality] it is - * marked unconfirmed, so a write the flusher held while the manifest was - * unknown is sent again by the first refresh rather than replaced with - * the server's default. + * ([bufferingQualityModeSupportedFlow]); [writeString] marks it unconfirmed. */ - override suspend fun setBufferingQualityMode(value: BufferingQualityMode) { - val key = PlaybackSettingsKeys.BufferingQualityMode - withScope { scope, store -> - store.edit { - it[stringPreferencesKey(scope.keyPrefix + key)] = value.wireValue - markDeviceOverride(it, scope, key) - it[unconfirmedKeysKey(scope)] = it[unconfirmedKeysKey(scope)].orEmpty() + key - } - serverSettingsFlusher.enqueue(scope.profileId, key, value.wireValue, scope.serverUrl, scope.authority) - } - } + override suspend fun setBufferingQualityMode(value: BufferingQualityMode) = + writeString(PlaybackSettingsKeys.BufferingQualityMode, value.wireValue) override suspend fun setAutoSkipCredits(value: Boolean) = writeBool(PlaybackSettingsKeys.AutoSkipCredits, value) @@ -677,6 +683,9 @@ class AndroidPlayerSettingsStore( override suspend fun setNextUpPromptSeconds(value: Int) = writeInt(PlaybackSettingsKeys.NextUpPromptSeconds, value.coerceIn(0, 120)) + override suspend fun setNextUpEnabled(value: Boolean) = + writeBool(PlaybackSettingsKeys.NextUpEnabled, value) + override suspend fun setResumeRewindSeconds(value: Int) = writeIntLocal(PlaybackSettingsKeys.ResumeRewindSeconds, value.coerceIn(0, 30)) @@ -1240,6 +1249,7 @@ class AndroidPlayerSettingsStore( store.edit { it[booleanPreferencesKey(scope.keyPrefix + key)] = value markDeviceOverride(it, scope, key) + markUnconfirmedIfManifestDetected(it, scope, key) } serverSettingsFlusher.enqueue(scope.profileId, key, value.toString(), scope.serverUrl, scope.authority) } @@ -1284,6 +1294,7 @@ class AndroidPlayerSettingsStore( store.edit { it[stringPreferencesKey(scope.keyPrefix + key)] = value markDeviceOverride(it, scope, key) + markUnconfirmedIfManifestDetected(it, scope, key) } serverSettingsFlusher.enqueue(scope.profileId, key, value, scope.serverUrl, scope.authority) } @@ -1330,6 +1341,22 @@ class AndroidPlayerSettingsStore( private fun deviceOverridesKey(scope: Scope): Preferences.Key> = stringSetPreferencesKey(scope.keyPrefix + DEVICE_OVERRIDE_KEYS) + /** + * A key the server may not store yet ([PlaybackSettingsKeys.ManifestDetectedKeys]) + * stays unconfirmed, like the cellular pair, so a write the flusher held while + * the manifest was unknown is sent again by the first refresh rather than + * replaced with the server's default. + */ + private fun markUnconfirmedIfManifestDetected( + prefs: androidx.datastore.preferences.core.MutablePreferences, + scope: Scope, + key: String, + ) { + if (key in PlaybackSettingsKeys.ManifestDetectedKeys) { + prefs[unconfirmedKeysKey(scope)] = prefs[unconfirmedKeysKey(scope)].orEmpty() + key + } + } + private fun unconfirmedKeysKey(scope: Scope): Preferences.Key> = stringSetPreferencesKey(scope.keyPrefix + UNCONFIRMED_GATED_KEYS) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt new file mode 100644 index 0000000000..f9b3ecc6a0 --- /dev/null +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt @@ -0,0 +1,44 @@ +package org.siloserver.silo.common.settings + +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import org.siloserver.silo.common.R + +/** + * The Show Next Up picker: one control over `playback.next_up_enabled` and + * `playback.next_up_prompt_seconds`. A choice is the seconds before the end + * (0 = at end), or null for Off. + */ +object NextUpChoice { + private val promptSeconds: List = listOf(0, 10, 30, 60, 120) + + /** + * Off comes first while the server stores the setting, and while this + * device's last choice is Off and the server's manifest is not read yet, + * so that choice stays visible and can be changed. + */ + fun options(offSupported: Boolean, enabled: Boolean): List = + if (offSupported || !enabled) listOf(null) + promptSeconds else promptSeconds + + fun selected(enabled: Boolean, seconds: Int): Int? = if (enabled) seconds.coerceAtLeast(0) else null + + /** Off leaves the seconds alone; a time turns Next Up back on if it was off. */ + suspend fun apply(store: PlayerSettingsStore, choice: Int?, currentlyEnabled: Boolean) { + if (choice == null) { + store.setNextUpEnabled(false) + return + } + if (!currentlyEnabled) store.setNextUpEnabled(true) + store.setNextUpPromptSeconds(choice) + } +} + +/** The phone and TV label for a [NextUpChoice] choice. */ +@Composable +fun nextUpChoiceLabel(choice: Int?): String = when { + choice == null -> stringResource(R.string.settings_off) + choice <= 0 -> stringResource(R.string.settings_nextUp_atEnd) + choice < 60 -> pluralStringResource(R.plurals.settings_nextUp_secondsBeforeEnd, choice, choice) + else -> (choice / 60).let { pluralStringResource(R.plurals.settings_nextUp_minutesBeforeEnd, it, it) } +} diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/PlayerSettingsStore.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/PlayerSettingsStore.kt index 0385f09dbf..89f06c96f1 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/PlayerSettingsStore.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/PlayerSettingsStore.kt @@ -59,6 +59,20 @@ interface PlayerSettingsStore { val bufferingQualityModeSupportedFlow: Flow get() = flowOf(true) + /** + * `playback.next_up_enabled`: false turns Next Up off. True against a + * server whose manifest lacks the setting. + */ + val nextUpEnabledFlow: Flow + get() = flowOf(true) + + /** + * True once the active server's manifest is known to define + * `playback.next_up_enabled`: the Show Next Up picker offers Off only then. + */ + val nextUpEnabledSupportedFlow: Flow + get() = flowOf(true) + // Booleans /** * The deprecated boolean, projected from [introSkipModeFlow] rather than @@ -228,6 +242,9 @@ interface PlayerSettingsStore { suspend fun setAudioSyncMs(value: Int) suspend fun setSubtitleSyncMs(value: Int) suspend fun setNextUpPromptSeconds(value: Int) + + /** Writes `playback.next_up_enabled`; offered only while [nextUpEnabledSupportedFlow]. */ + suspend fun setNextUpEnabled(value: Boolean) = Unit suspend fun setSleepTimerDefaultMinutes(value: Int) /** Set resume skip-back seconds (clamped 0..30; 0 = off). */ suspend fun setResumeRewindSeconds(value: Int) 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 64265c9cad..56c13c23f8 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 @@ -1574,6 +1574,43 @@ class AndroidPlayerSettingsStoreTest { assertTrue(store.bufferingQualityModeSupportedFlow.first()) } + @Test + fun `Next Up stays on against a server whose manifest lacks the Off setting`() = runTest { + var keys: Set = setOf(PlaybackSettingsKeys.PreferredQuality) + var contract = capabilitiesAt(30) + val api = FakeSettingsApi( + effective = mapOf(stored(PlaybackSettingsKeys.NextUpEnabled, JsonPrimitive(false))), + ) + val store = AndroidPlayerSettingsStore( + context = mockContextStub(), + legacyCache = fakeLegacyCache, + getActiveProfileId = { activeProfileId }, + getServerUrl = { serverUrl }, + serverSettingsFlusher = fakeFlusher, + settingsRepository = SettingsRepository(api), + getDeviceId = { null }, + contractRevision = SettingsContractRevision({ contract }, { serverUrl }, { ApiResult.Success(keys) }), + dataStoreFactory = { _, id -> + PreferenceDataStoreFactory.create(produceFile = { File(tempFolder.root, "ds_nu_$id.preferences_pb") }) + }, + ) + store.setNextUpEnabled(false) + assertFalse(store.nextUpEnabledFlow.first(), "the last choice seen, until the manifest is read") + + // A server without the setting: Off hides and Next Up shows as before. + store.refreshFromServer() + assertFalse(PlaybackSettingsKeys.NextUpEnabled in api.requestedKeys) + assertFalse(store.nextUpEnabledSupportedFlow.first()) + assertTrue(store.nextUpEnabledFlow.first()) + + // The server upgrades to a contract with the setting. + keys = keys + PlaybackSettingsKeys.NextUpEnabled + contract = capabilitiesAt(31) + store.refreshFromServer() + assertTrue(store.nextUpEnabledSupportedFlow.first()) + assertFalse(store.nextUpEnabledFlow.first()) + } + @Test fun `cellular quality is left out of the batch while the server revision is unknown`() = runTest { val contractRevision = SettingsContractRevision( diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt new file mode 100644 index 0000000000..403ae637c8 --- /dev/null +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt @@ -0,0 +1,16 @@ +package org.siloserver.silo.common.settings + +import kotlin.test.Test +import kotlin.test.assertEquals + +class NextUpChoiceTest { + @Test + fun offIsOfferedWhereTheServerStoresItAndWhileASavedOffAwaitsTheManifest() { + val times = listOf(0, 10, 30, 60, 120) + assertEquals(listOf(null) + times, NextUpChoice.options(offSupported = true, enabled = true)) + assertEquals(times, NextUpChoice.options(offSupported = false, enabled = true)) + // A saved Off before the manifest is read stays visible and selected. + assertEquals(listOf(null) + times, NextUpChoice.options(offSupported = false, enabled = false)) + assertEquals(null, NextUpChoice.selected(enabled = false, seconds = 30)) + } +} diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt index 41ddd1255e..58b8adbf05 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt @@ -673,6 +673,11 @@ fun PlayerScreen( } } + // With Next Up off, the end of playback leaves the player like Back. + LaunchedEffect(Unit) { + viewModel.closeAtEndRequests.collect { exitPlayer() } + } + // Surface transient Watch Party server rejections as a brief Toast. These // flow on the repository's errors stream and never eject the user. Only // collected while bound to a room. diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt index ccff3c7b9a..48f90921f7 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt @@ -1040,6 +1040,17 @@ class PlayerViewModel( // Seconds before the end of the file to surface Up Next (0 = only at end). private val nextUpPromptSeconds: StateFlow = playerSettingsStore.nextUpPromptSecondsFlow .stateIn(viewModelScope, SharingStarted.Eagerly, 30) + // Show Next Up: Off means no card, and the player closes at the end. + private val nextUpEnabled: StateFlow = playerSettingsStore.nextUpEnabledFlow + .stateIn(viewModelScope, SharingStarted.Eagerly, true) + + private val _closeAtEndRequests = MutableSharedFlow( + replay = 0, + extraBufferCapacity = 1, + onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST, + ) + /** PlayerScreen leaves the player the way Back does: playback ended with Next Up off. */ + val closeAtEndRequests: kotlinx.coroutines.flow.SharedFlow = _closeAtEndRequests.asSharedFlow() /** * Video relative-seek intervals every phone surface uses (buttons, @@ -6193,6 +6204,11 @@ class PlayerViewModel( shuffleRefreshedForPostRoll = true refreshShuffleNext() } + } else if (!nextUpEnabled.value) { + // Next Up off: nothing before the end, and the player closes at the + // end. A shuffle still moves on; the viewer asked for one. + if (videoEnded) _closeAtEndRequests.tryEmit(Unit) + return } if (autoAdvanceHandled) { if (videoEnded) { diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/PlaybackSettings.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/PlaybackSettings.kt index bf19c6e04a..0d02bcb9a1 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/PlaybackSettings.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/PlaybackSettings.kt @@ -1,5 +1,7 @@ package org.siloserver.silo.android.ui.screens.settings +import org.siloserver.silo.common.settings.NextUpChoice +import org.siloserver.silo.common.settings.nextUpChoiceLabel import org.siloserver.silo.common.i18n.text import androidx.annotation.StringRes import androidx.compose.material3.Text @@ -11,7 +13,6 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics @@ -40,8 +41,6 @@ import org.siloserver.silo.network.apiv2.PlaybackLearnedLimitV2 // position in these lists back to the value. private val resumeRewindOptions = listOf(0, 3, 5, 7, 10, 15, 20, 30) private val passOutThresholdOptions = listOf(0, 2, 3, 4, 5) -// Up-Next prompt timing (seconds before end; 0 = at end). Mirrors TV/tvOS. -private val nextUpPromptOptions = listOf(0, 10, 30, 60, 120) @Composable private fun resumeRewindLabel(seconds: Int) = @@ -50,13 +49,6 @@ private fun resumeRewindLabel(seconds: Int) = @Composable private fun passOutThresholdLabel(count: Int) = if (count <= 0) stringResource(CommonR.string.settings_off) else LocaleFormat.integer(count, currentNumberLocale()) -@Composable -private fun nextUpPromptLabel(seconds: Int): String = when { - seconds <= 0 -> stringResource(CommonR.string.settings_nextUp_atEnd) - seconds < 60 -> pluralStringResource(CommonR.plurals.settings_nextUp_secondsBeforeEnd, seconds, seconds) - else -> pluralStringResource(CommonR.plurals.settings_nextUp_minutesBeforeEnd, seconds / 60, seconds / 60) -} - /** * The menu for a profile-layered picker: "Use profile setting" first, then * [options]. Routes that first option to [onUseProfileSetting] and checks it @@ -298,6 +290,8 @@ fun PlaybackCellularSection( fun PlaybackEpisodesSection( autoPlayNext: Boolean, nextUpPromptSeconds: Int, + nextUpEnabled: Boolean, + nextUpOffSupported: Boolean, introSkipMode: IntroSkipMode, autoSkipCredits: Boolean, resumeRewindSeconds: Int, @@ -305,7 +299,8 @@ fun PlaybackEpisodesSection( /** Keys this device holds its own value for. */ deviceOverrides: Set, onAutoPlayNextChanged: (Boolean) -> Unit, - onNextUpPromptSecondsChanged: (Int) -> Unit, + /** Seconds before the end, or null for Off. */ + onNextUpChoice: (Int?) -> Unit, onIntroSkipModeChanged: (IntroSkipMode) -> Unit, onAutoSkipCreditsChanged: (Boolean) -> Unit, onResumeRewindSecondsChanged: (Int) -> Unit, @@ -329,13 +324,15 @@ fun PlaybackEpisodesSection( onUseProfileSetting = { onUseProfileSetting(PlaybackSettingsKeys.AutoPlayNext) }, ) + val nextUpOptions = NextUpChoice.options(nextUpOffSupported, nextUpEnabled) + val nextUpSelected = NextUpChoice.selected(nextUpEnabled, nextUpPromptSeconds) ProfileLayeredDropdownRow( label = stringResource(CommonR.string.settings_nextUp_title), - value = nextUpPromptLabel(nextUpPromptSeconds), - options = nextUpPromptOptions.map { nextUpPromptLabel(it) }, - selectedIndex = nextUpPromptOptions.indexOf(nextUpPromptSeconds.coerceAtLeast(0)), + value = nextUpChoiceLabel(nextUpSelected), + options = nextUpOptions.map { nextUpChoiceLabel(it) }, + selectedIndex = nextUpOptions.indexOf(nextUpSelected), overridden = overridden(PlaybackSettingsKeys.NextUpPromptSeconds), - onIndexSelected = { onNextUpPromptSecondsChanged(nextUpPromptOptions[it]) }, + onIndexSelected = { onNextUpChoice(nextUpOptions[it]) }, onUseProfileSetting = { onUseProfileSetting(PlaybackSettingsKeys.NextUpPromptSeconds) }, ) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt index f4d732ed11..00bd992faa 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt @@ -202,13 +202,15 @@ fun SettingsPlaybackScreen(viewModel: SettingsViewModel, onBackClick: () -> Unit PlaybackEpisodesSection( autoPlayNext = state.autoPlayNext, nextUpPromptSeconds = state.nextUpPromptSeconds, + nextUpEnabled = state.nextUpEnabled, + nextUpOffSupported = state.nextUpOffSupported, introSkipMode = state.introSkipMode, autoSkipCredits = state.autoSkipCredits, resumeRewindSeconds = state.resumeRewindSeconds, passOutThreshold = state.passOutThreshold, deviceOverrides = state.deviceOverrides, onAutoPlayNextChanged = viewModel::setAutoPlayNext, - onNextUpPromptSecondsChanged = viewModel::setNextUpPromptSeconds, + onNextUpChoice = viewModel::setNextUpChoice, onIntroSkipModeChanged = viewModel::setIntroSkipMode, onAutoSkipCreditsChanged = viewModel::setAutoSkipCredits, onResumeRewindSecondsChanged = viewModel::setResumeRewindSeconds, 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 4b5e70b784..c199dc78f5 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 @@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import org.siloserver.silo.model.profile.ActiveProfileStore import org.siloserver.silo.android.auth.SignOutTeardown +import org.siloserver.silo.common.settings.NextUpChoice import org.siloserver.silo.common.settings.CardPresentationSource import org.siloserver.silo.common.settings.CardPresentationStore import org.siloserver.silo.common.settings.CardPresentationUiState @@ -130,6 +131,9 @@ data class SettingsUiState( // many seconds before the end to surface the card (0 = only at end). val autoPlayNext: Boolean = true, val nextUpPromptSeconds: Int = 30, + // Show Next Up Off (`playback.next_up_enabled`), offered while the server stores it. + val nextUpEnabled: Boolean = true, + val nextUpOffSupported: Boolean = false, /** * Keys this device holds its own value for. A profile-layered control * whose key is absent shows "Use profile setting" as its choice. @@ -338,6 +342,12 @@ class SettingsViewModel( playerSettingsStore.bufferingQualityModeSupportedFlow.onEach { supported -> _uiState.update { it.copy(bufferingQualityModeSupported = supported) } }.launchIn(viewModelScope) + combine( + playerSettingsStore.nextUpEnabledFlow, + playerSettingsStore.nextUpEnabledSupportedFlow, + ) { enabled, supported -> + _uiState.update { it.copy(nextUpEnabled = enabled, nextUpOffSupported = supported) } + }.launchIn(viewModelScope) combine( playerSettingsStore.cellularPreferredQualityFlow, playerSettingsStore.cellularMaxBitrateKbpsFlow, @@ -439,8 +449,10 @@ class SettingsViewModel( viewModelScope.launch { playerSettingsStore.setAutoPlayNext(value) } } - fun setNextUpPromptSeconds(value: Int) { - viewModelScope.launch { playerSettingsStore.setNextUpPromptSeconds(value) } + /** A Show Next Up choice: seconds before the end, or null for Off. */ + fun setNextUpChoice(choice: Int?) { + val enabled = _uiState.value.nextUpEnabled + viewModelScope.launch { NextUpChoice.apply(playerSettingsStore, choice, enabled) } } fun setPassOutThreshold(value: Int) { diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt index f733fadb67..2a7009b954 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModelLoadOwnershipIntegrationTest.kt @@ -35,6 +35,7 @@ import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.launch import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -486,6 +487,37 @@ class PlayerViewModelLoadOwnershipIntegrationTest { } } + @Test + fun nextUpOffShowsNoCardAndClosesThePlayerAtTheEnd() = runTest(dispatcher) { + val starter = DeferredNonCooperativeStarter() + val fixture = playerViewModel(starter, backgroundScope, nextUpEnabled = false) + val store = ViewModelStore().also { it.put("player", fixture.viewModel) } + try { + val viewModel = fixture.viewModel + val closes = mutableListOf() + backgroundScope.launch { viewModel.closeAtEndRequests.collect { closes += it } } + viewModel.loadContent("episode-a", preferredFileId = 1) + starter.awaitRequestCount(1) + starter.complete(0, ready(starter.request(0), "session-a")) + viewModel.awaitState { it.sessionId == "session-a" && !it.isLoading } + viewModel.onMediaMountApplied(viewModel.uiState.value.mediaMountGeneration) + viewModel.offerNextEpisode() + + viewModel.onPositionChanged(1_169_500L, 1_200_000L) + viewModel.onPositionChanged(1_170_500L, 1_200_000L) + assertFalse(viewModel.uiState.value.showUpNext) + assertTrue(closes.isEmpty()) + + viewModel.onApproachingEnd(videoEnded = true) + runCurrent() + assertFalse(viewModel.uiState.value.showUpNext) + assertEquals(1, closes.size) + assertEquals(1, starter.startedRequestCount) + } finally { + store.clear() + } + } + @Test fun keepWatchingSuppressesCreditsPromptButReopensNextUpAtPlaybackEnd() = runTest(dispatcher) { val starter = DeferredNonCooperativeStarter() @@ -895,6 +927,7 @@ class PlayerViewModelLoadOwnershipIntegrationTest { network: PlaybackNetworkEvidenceProvider = PlaybackNetworkEvidenceProvider.None, /** The reachability probe answers; otherwise it has no server to probe. */ serverReachable: Boolean = false, + nextUpEnabled: Boolean = true, ): PlayerFixture { val client = noOpClient() val tokenManager = FakeTokenManager() @@ -930,7 +963,7 @@ class PlayerViewModelLoadOwnershipIntegrationTest { } else { ServerReachabilityMonitor(org.siloserver.silo.network.apiv2.ApiV2Probe(client)::probeFresh, scope, { null }) }, - playerSettingsStore = FakePlayerSettingsStore(), + playerSettingsStore = FakePlayerSettingsStore(nextUpEnabled = nextUpEnabled), introAutoSkipController = IntroAutoSkipController(scope), sessionLifecycle = lifecycle, sleepTimer = SleepTimerController(scope), @@ -2038,7 +2071,9 @@ private class FakeServerRegistry : ServerRegistry { private class FakePlayerSettingsStore( private val audioLanguage: String = "", + nextUpEnabled: Boolean = true, ) : PlayerSettingsStore { + override val nextUpEnabledFlow: Flow = flowOf(nextUpEnabled) override val introSkipModeFlow: Flow = flowOf(IntroSkipMode.ASK) override val bufferingQualityModeFlow: Flow = flowOf(BufferingQualityMode.Default) override val autoSkipCreditsFlow: Flow = flowOf(false) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt index 089fb0ba09..9f99452bb6 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt @@ -634,6 +634,10 @@ fun TvPlayerScreen( stopPlaybackAndExit() } } + // With Next Up off, the end of playback leaves the player like Back. + LaunchedEffect(Unit) { + viewModel.closeAtEndRequests.collect { stopPlaybackAndExit() } + } val latestOnReturnToWatchPartyLobby by rememberUpdatedState(onReturnToWatchPartyLobby) val latestOnWatchPartyEnded by rememberUpdatedState(onWatchPartyEnded) if (watchParty != null && roomId != null) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt index 8077933766..4892c6daf5 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt @@ -1850,6 +1850,10 @@ class TvPlayerViewModel( */ val roomAudioTrackChanges: SharedFlow = _roomAudioTrackChanges + private val _closeAtEndRequests = MutableSharedFlow(extraBufferCapacity = 1) + /** Screen leaves the player the way Back does: playback ended with Next Up off. */ + val closeAtEndRequests: SharedFlow = _closeAtEndRequests + private val _remoteStopRequests = MutableSharedFlow(extraBufferCapacity = 1) /** Screen collects this and runs its teardown/exit, showing the notice when there is one. */ val remoteStopRequests: SharedFlow = _remoteStopRequests @@ -2012,6 +2016,9 @@ class TvPlayerViewModel( // Seconds before the end of the file to surface Up Next (0 = only at end). private val nextUpPromptSeconds: StateFlow = playerSettingsStore.nextUpPromptSecondsFlow .stateIn(viewModelScope, SharingStarted.Eagerly, 30) + // Show Next Up: Off means no overlay, and the player closes at the end. + private val nextUpEnabled: StateFlow = playerSettingsStore.nextUpEnabledFlow + .stateIn(viewModelScope, SharingStarted.Eagerly, true) val hdrEnabled: StateFlow = playerSettingsStore.hdrEnabledFlow .stateIn(viewModelScope, SharingStarted.Eagerly, true) val dolbyVisionEnabled: StateFlow = playerSettingsStore.dolbyVisionEnabledFlow @@ -5408,6 +5415,18 @@ class TvPlayerViewModel( shuffleRefreshedForPostRoll = true refreshShuffleNext() } + } else if (!nextUpEnabled.value) { + // Next Up off: nothing before the end, and the player closes at the + // end. A shuffle still moves on; the viewer asked for one. An + // overlay the viewer opened stays up, without a countdown. + if (videoEnded) { + if (_uiState.value.showNextUp) { + _uiState.update { it.copy(nextUpVideoEnded = true) } + } else { + _closeAtEndRequests.tryEmit(Unit) + } + } + return } // Playback end reopens a dismissed card without restarting its timer. // A card still showing keeps its existing countdown. diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt index a60c48a9f0..a844d183ed 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt @@ -61,6 +61,8 @@ import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import org.siloserver.silo.common.settings.NextUpChoice +import org.siloserver.silo.common.settings.nextUpChoiceLabel import org.siloserver.silo.common.i18n.AppLanguageStore import org.siloserver.silo.common.i18n.appLanguageOptions import org.siloserver.silo.common.i18n.displayUppercase @@ -93,7 +95,6 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight @@ -325,7 +326,7 @@ fun TvSettingsScreen( onTrueBlackBarsChanged = viewModel::onTrueBlackBarsChanged, onResumeRewindSecondsChanged = viewModel::onResumeRewindSecondsChanged, onPassOutThresholdChanged = viewModel::onPassOutThresholdChanged, - onNextUpPromptSecondsChanged = viewModel::onNextUpPromptSecondsChanged, + onNextUpChoice = viewModel::onNextUpChoice, onResetPlaybackOverrides = viewModel::resetPlaybackOverrides, onUseProfileSetting = viewModel::onUseProfileSetting, seekIntervals = viewModel.seekIntervals, @@ -480,7 +481,7 @@ private fun SettingsSplitLayout( onTrueBlackBarsChanged: (Boolean) -> Unit, onResumeRewindSecondsChanged: (Int) -> Unit, onPassOutThresholdChanged: (Int) -> Unit, - onNextUpPromptSecondsChanged: (Int) -> Unit, + onNextUpChoice: (Int?) -> Unit, onResetPlaybackOverrides: () -> Unit, onUseProfileSetting: (String) -> Unit, seekIntervals: SeekIntervalSettingsModel? = null, @@ -568,7 +569,7 @@ private fun SettingsSplitLayout( onTrueBlackBarsChanged = onTrueBlackBarsChanged, onResumeRewindSecondsChanged = onResumeRewindSecondsChanged, onPassOutThresholdChanged = onPassOutThresholdChanged, - onNextUpPromptSecondsChanged = onNextUpPromptSecondsChanged, + onNextUpChoice = onNextUpChoice, onResetPlaybackOverrides = onResetPlaybackOverrides, onUseProfileSetting = onUseProfileSetting, seekIntervals = seekIntervals, @@ -859,7 +860,7 @@ private fun SettingsDetailPane( onTrueBlackBarsChanged: (Boolean) -> Unit, onResumeRewindSecondsChanged: (Int) -> Unit, onPassOutThresholdChanged: (Int) -> Unit, - onNextUpPromptSecondsChanged: (Int) -> Unit, + onNextUpChoice: (Int?) -> Unit, onResetPlaybackOverrides: () -> Unit, onUseProfileSetting: (String) -> Unit, seekIntervals: SeekIntervalSettingsModel? = null, @@ -922,7 +923,7 @@ private fun SettingsDetailPane( onTrueBlackBarsChanged = onTrueBlackBarsChanged, onResumeRewindSecondsChanged = onResumeRewindSecondsChanged, onPassOutThresholdChanged = onPassOutThresholdChanged, - onNextUpPromptSecondsChanged = onNextUpPromptSecondsChanged, + onNextUpChoice = onNextUpChoice, onResetPlaybackOverrides = onResetPlaybackOverrides, onUseProfileSetting = onUseProfileSetting, seekIntervals = seekIntervals, @@ -1226,7 +1227,7 @@ private fun TvPlaybackSettingsPane( onTrueBlackBarsChanged: (Boolean) -> Unit, onResumeRewindSecondsChanged: (Int) -> Unit, onPassOutThresholdChanged: (Int) -> Unit, - onNextUpPromptSecondsChanged: (Int) -> Unit, + onNextUpChoice: (Int?) -> Unit, onResetPlaybackOverrides: () -> Unit, /** Receives the key of the control going back to the profile's value. */ onUseProfileSetting: (String) -> Unit, @@ -1393,7 +1394,7 @@ private fun TvPlaybackSettingsPane( } SettingsValueRow( label = stringResource(CommonR.string.settings_nextUp_title), - value = nextUpPromptLabel(state.nextUpPromptSeconds), + value = nextUpChoiceLabel(NextUpChoice.selected(state.nextUpEnabled, state.nextUpPromptSeconds)), onClick = { activePicker = PlaybackPicker.NextUpPrompt }, ) // Three-way, not a switch: the schema's recommended control @@ -1563,8 +1564,10 @@ private fun TvPlaybackSettingsPane( PlaybackPicker.NextUpPrompt -> { val (options, selectedId) = profileLayered( PlaybackSettingsKeys.NextUpPromptSeconds, - NextUpPromptOptions.map { PickerOption(it.toString(), nextUpPromptLabel(it)) }, - state.nextUpPromptSeconds.toString(), + NextUpChoice.options(state.nextUpOffSupported, state.nextUpEnabled).map { + PickerOption(it?.toString() ?: NextUpOffId, nextUpChoiceLabel(it)) + }, + NextUpChoice.selected(state.nextUpEnabled, state.nextUpPromptSeconds)?.toString() ?: NextUpOffId, ) TvSettingsPickerSheet( title = stringResource(CommonR.string.settings_nextUp_title), @@ -1574,7 +1577,7 @@ private fun TvPlaybackSettingsPane( if (id == UseProfileSettingId) { onUseProfileSetting(PlaybackSettingsKeys.NextUpPromptSeconds) } else { - id.toIntOrNull()?.let(onNextUpPromptSecondsChanged) + if (id == NextUpOffId) onNextUpChoice(null) else id.toIntOrNull()?.let(onNextUpChoice) } activePicker = null }, @@ -3070,8 +3073,8 @@ private fun invertedRowBorder() = ClickableSurfaceDefaults.border( private val ResumeRewindOptions = listOf(0, 3, 5, 7, 10, 15, 20, 30) private val PassOutThresholdOptions = listOf(0, 2, 3, 4, 5) -// Up-Next prompt timing (seconds before end; 0 = at end). Mirrors tvOS. -private val NextUpPromptOptions = listOf(0, 10, 30, 60, 120) +/** The Show Next Up picker's id for Off; the other choices use their seconds. */ +private const val NextUpOffId = "off" @Composable private fun resumeRewindLabel(seconds: Int): String = @@ -3081,13 +3084,6 @@ private fun resumeRewindLabel(seconds: Int): String = private fun passOutThresholdLabel(count: Int): String = if (count <= 0) stringResource(CommonR.string.settings_off) else "$count" -@Composable -private fun nextUpPromptLabel(seconds: Int): String = when { - seconds <= 0 -> stringResource(CommonR.string.settings_nextUp_atEnd) - seconds < 60 -> pluralStringResource(CommonR.plurals.settings_nextUp_secondsBeforeEnd, seconds, seconds) - else -> (seconds / 60).let { pluralStringResource(CommonR.plurals.settings_nextUp_minutesBeforeEnd, it, it) } -} - /** * "Theme Music" and "Loop Theme Music", as the web app's device settings offer * them. Each switch writes this TV's value; one set for the profile elsewhere 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 7989b93d9b..951a092b44 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 @@ -1,5 +1,6 @@ package org.siloserver.silo.tv.ui.screens.settings +import org.siloserver.silo.common.settings.NextUpChoice import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import org.siloserver.silo.common.settings.CardPresentationSource @@ -169,6 +170,9 @@ class TvSettingsViewModel( // Seconds before the end of an episode to surface the Up-Next prompt // (0 = at the very end). Mirrors tvOS `nextUpPromptSeconds`. val nextUpPromptSeconds: Int = 30, + // Show Next Up Off (`playback.next_up_enabled`), offered while the server stores it. + val nextUpEnabled: Boolean = true, + val nextUpOffSupported: Boolean = false, /** * Keys this device holds its own value for. A profile-layered control * whose key is absent shows "Use profile setting" as its choice. @@ -445,6 +449,14 @@ class TvSettingsViewModel( _uiState.update { it.copy(nextUpPromptSeconds = seconds) } } } + viewModelScope.launch { + combine( + playerSettingsStore.nextUpEnabledFlow, + playerSettingsStore.nextUpEnabledSupportedFlow, + ) { enabled, supported -> enabled to supported }.collect { (enabled, supported) -> + _uiState.update { it.copy(nextUpEnabled = enabled, nextUpOffSupported = supported) } + } + } viewModelScope.launch { playerSettingsStore.bufferingQualityModeFlow.collect { mode -> _uiState.update { it.copy(bufferingQualityMode = mode) } @@ -850,8 +862,10 @@ class TvSettingsViewModel( viewModelScope.launch { playerSettingsStore.setPassOutThreshold(value) } } - fun onNextUpPromptSecondsChanged(value: Int) { - viewModelScope.launch { playerSettingsStore.setNextUpPromptSeconds(value) } + /** A Show Next Up choice: seconds before the end, or null for Off. */ + fun onNextUpChoice(choice: Int?) { + val enabled = _uiState.value.nextUpEnabled + viewModelScope.launch { NextUpChoice.apply(playerSettingsStore, choice, enabled) } } /** diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSettingsKeys.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSettingsKeys.kt index 77964aa3bc..fa1782f00a 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSettingsKeys.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/PlaybackSettingsKeys.kt @@ -51,7 +51,7 @@ object PlaybackSettingsKeys { * Keys some supported servers lack, detected by their presence in the * server's settings manifest rather than by its revision number. */ - val ManifestDetectedKeys: Set = setOf(BufferingQualityMode) + val ManifestDetectedKeys: Set = setOf(BufferingQualityMode, NextUpEnabled) const val AutoSkipCredits = "playback.auto_skip_credits" const val AutoPlayNext = "playback.auto_play_next" // Renamed at the settings cutover: every other key carries a domain prefix @@ -79,6 +79,14 @@ object PlaybackSettingsKeys { // could read the other's. The contract settles on playback.*, and // [RenamedLocalKeys] carries the already-written local value across. const val NextUpPromptSeconds = "playback.next_up_prompt_seconds" + + /** + * False turns Next Up off: no card, no countdown, no automatic next + * episode; the player closes at the end. One picker writes it with + * [NextUpPromptSeconds] ([deviceOverrideGroup]). An older server neither + * stores nor answers it ([ManifestDetectedKeys]). + */ + const val NextUpEnabled = "playback.next_up_enabled" const val DvProfile7HDR10Fallback = "player.dv_profile7_hdr10_fallback" const val DolbyVisionEnabled = "player.dolby_vision_enabled" const val MatchContentFrameRate = "player.match_frame_rate" @@ -225,6 +233,7 @@ object PlaybackSettingsKeys { VideoGravity, OrientationMode, NextUpPromptSeconds, + NextUpEnabled, DvProfile7HDR10Fallback, DolbyVisionEnabled, MatchContentFrameRate, @@ -262,6 +271,7 @@ object PlaybackSettingsKeys { AutoSkipCredits, AutoPlayNext, NextUpPromptSeconds, + NextUpEnabled, SubtitleAppearance, ThemeMusicEnabled, ThemeMusicLoop, @@ -280,6 +290,7 @@ object PlaybackSettingsKeys { fun deviceOverrideGroup(key: String): List = when (key) { CellularPreferredQuality, CellularMaxBitrateKbps -> listOf(CellularPreferredQuality, CellularMaxBitrateKbps) IntroSkipMode, AutoSkipIntro -> listOf(IntroSkipMode, AutoSkipIntro) + NextUpEnabled, NextUpPromptSeconds -> listOf(NextUpEnabled, NextUpPromptSeconds) else -> listOf(key) } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/SettingKeys.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/SettingKeys.kt index d1a7aca23c..9c7367a0a1 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/SettingKeys.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/model/settings/SettingKeys.kt @@ -24,7 +24,7 @@ data class SettingPresentation( ) object SettingKeys { - const val REVISION = 28 + const val REVISION = 30 /** Blur unwatched episode images */ const val CATALOG_HIDE_UNWATCHED_EPISODE_IMAGES = "catalog.hide_unwatched_episode_images" @@ -72,6 +72,8 @@ object SettingKeys { const val PLAYBACK_INTRO_SKIP_MODE = "playback.intro_skip_mode" /** Maximum bitrate */ const val PLAYBACK_MAX_BITRATE_KBPS = "playback.max_bitrate_kbps" + /** Show Next Up */ + const val PLAYBACK_NEXT_UP_ENABLED = "playback.next_up_enabled" /** Next up prompt */ const val PLAYBACK_NEXT_UP_PROMPT_SECONDS = "playback.next_up_prompt_seconds" /** Preferred quality */ @@ -202,6 +204,7 @@ object SettingKeys { PLAYBACK_CELLULAR_PREFERRED_QUALITY, PLAYBACK_INTRO_SKIP_MODE, PLAYBACK_MAX_BITRATE_KBPS, + PLAYBACK_NEXT_UP_ENABLED, PLAYBACK_NEXT_UP_PROMPT_SECONDS, PLAYBACK_PREFERRED_QUALITY, PLAYBACK_SHOW_FORCED_SUBTITLES, @@ -286,6 +289,7 @@ object SettingKeys { PLAYBACK_AUTO_SKIP_CREDITS, PLAYBACK_AUTO_SKIP_INTRO, PLAYBACK_AUTO_SKIP_RECAP, + PLAYBACK_NEXT_UP_ENABLED, PLAYBACK_SHOW_FORCED_SUBTITLES, PLAYBACK_SHOW_MARKER_CONFIDENCE, PLAYBACK_SHOW_MARKER_SOURCE, diff --git a/shared/src/commonTest/resources/settings/v1/SOURCE b/shared/src/commonTest/resources/settings/v1/SOURCE index 6ae2713c56..fbe4a1e0c6 100644 --- a/shared/src/commonTest/resources/settings/v1/SOURCE +++ b/shared/src/commonTest/resources/settings/v1/SOURCE @@ -1,6 +1,6 @@ repository=https://github.com/Silo-Server/silo-server path=contracts/settings/v1 -manifest_revision=28 +manifest_revision=30 fixture_version=1 Both files are byte-identical copies of the server's canonical contract; do not @@ -10,9 +10,9 @@ the fixture's manifest_revision, the vendored manifest's revision, and the generated SettingKeys.REVISION stop agreeing, which is the whole point of carrying the pair rather than the fixture alone. -conformance.json commit=f5d61bb2b0dc33fedd2e1b6752a9827b838ecae8 -manifest.json commit=f5d61bb2b0dc33fedd2e1b6752a9827b838ecae8 -copied from commit=f5d61bb2b0dc33fedd2e1b6752a9827b838ecae8 (Silo-Server/silo-server#3723, branch feat/issue-3188-app-language) +conformance.json commit=fd61354caa99d7c35b99288d85416bc098236808 +manifest.json commit=fd61354caa99d7c35b99288d85416bc098236808 +copied from commit=fd61354caa99d7c35b99288d85416bc098236808 (branch feat/settings-next-up-enabled, unmerged) manifest.json is vendored whole, including the maintainer `notes` the server strips before serving /api/v1/settings/contract. Keeping it byte-identical is diff --git a/shared/src/commonTest/resources/settings/v1/conformance.json b/shared/src/commonTest/resources/settings/v1/conformance.json index 76a53a0dbf..2186cb3145 100644 --- a/shared/src/commonTest/resources/settings/v1/conformance.json +++ b/shared/src/commonTest/resources/settings/v1/conformance.json @@ -1,6 +1,6 @@ { "fixture_version": 1, - "manifest_revision": 28, + "manifest_revision": 30, "description": "Cross-platform conformance cases for settings resolution. Every case runs against the shipped manifest in this directory: definitions are referenced by key, never restated, so an expectation can only be satisfied by resolving the real contract. Each platform's resolver (Go in internal/settingsresolve, TypeScript in web/src/lib/settingsResolve.ts, Kotlin and Swift in the client repos) runs every case through a hand-written runner; a runner must fail on any fixture field it does not know, because schema drift in the fixture itself is drift. A case's constraint_bindings attach a constraint to a copy of a real definition so constraint semantics stay testable even while no shipped definition carries that constraint kind. In expected entries, constrained:true requires stored_value and constraint_kind to be present, and stored_value may be null to mean the authored value was JSON null.", "cases": [ { @@ -383,6 +383,7 @@ "playback.subtitle_mode", "playback.show_forced_subtitles", "playback.next_up_prompt_seconds", + "playback.next_up_enabled", "playback.audio_language", "ui.app_language" ], @@ -391,6 +392,7 @@ { "key": "playback.subtitle_mode", "value": "auto", "source": "default" }, { "key": "playback.show_forced_subtitles", "value": true, "source": "default" }, { "key": "playback.next_up_prompt_seconds", "value": 30, "source": "default" }, + { "key": "playback.next_up_enabled", "value": true, "source": "default" }, { "key": "playback.audio_language", "value": null, "source": "default" }, { "key": "ui.app_language", "value": null, "source": "default" } ] diff --git a/shared/src/commonTest/resources/settings/v1/manifest.json b/shared/src/commonTest/resources/settings/v1/manifest.json index a44168b91c..2d1f4b12a5 100644 --- a/shared/src/commonTest/resources/settings/v1/manifest.json +++ b/shared/src/commonTest/resources/settings/v1/manifest.json @@ -1,6 +1,6 @@ { "api_version": 1, - "revision": 28, + "revision": 30, "option_sets": { "playback_audio_languages": { "type": "language_tag", @@ -742,6 +742,20 @@ "recommended_control": "slider", "notes": "Android currently writes player.next_up_prompt_seconds. That alias is migrated to this key and removed from production writes." }, + { + "key": "playback.next_up_enabled", + "introduced_in": 30, + "persistence": "remote", + "allowed_scopes": ["profile", "profile_device"], + "resolution_order": ["profile_device", "profile", "default"], + "value_schema": { "type": "boolean" }, + "default_value": true, + "category": "playback", + "label": "Show Next Up", + "description": "Show the Next Up card near the end of an episode.", + "recommended_control": "switch", + "notes": "false turns Next Up off: no card before or at the end of an episode, no countdown and no automatic next episode, whatever playback.auto_play_next says. The episode plays to its end and the player closes as its Close action does. playback.next_up_prompt_seconds only applies while this is true. Clients may show the two as one picker with an Off choice. A client that predates this key keeps showing Next Up." + }, { "key": "catalog.metadata_language", "introduced_in": 1, @@ -1254,7 +1268,7 @@ "category": "appearance", "label": "Poster badges", "description": "Which badges appear on poster cards, and where.", - "notes": "Registered from the legacy unprefixed key card_overlays, which reached the server only through the unknown-key extension bag — stored as an arbitrary string with no validation. null means the user has expressed no preference, which is what lets the server-wide admin default in the overlay-config endpoint apply; writing a resolved-but-unchosen value would silently pin them. The server-wide default configuration stays in server_settings and is not a user setting. This key describes which badges to show, not whether to show them — that is ui.card_overlays_enabled. Revision 13 adds the advisory_age overlay id; a server below revision 13 rejects a value that contains it, so a client offers that badge only when manifest_revision is at least 13. Revision 15 adds the request_status overlay id (a watchlist title's request status on its poster) under the same rule: a client offers it only when manifest_revision is at least 15. Revision 25 reserves the top-right corner for the watch-status indicator, which every client always draws and no setting controls, and adds the left-edge and right-edge positions, the plate and band presets, style, and the per-badge image and valueImages references to uploaded images; a server below revision 25 rejects a value that uses any of them, so a client writes them only when manifest_revision is at least 25. top-right stays valid so stored values keep validating, but from revision 25 a client draws a badge stored there on the right edge and writes right-edge instead. Revision 26 adds the resolution_hdr_audio overlay id (one badge combining resolution, dynamic range and audio codec); a server below revision 26 rejects a value that contains it, so a client offers that badge only when manifest_revision is at least 26." + "notes": "Registered from the legacy unprefixed key card_overlays, which reached the server only through the unknown-key extension bag — stored as an arbitrary string with no validation. null means the user has expressed no preference, which is what lets the server-wide admin default in the overlay-config endpoint apply; writing a resolved-but-unchosen value would silently pin them. The server-wide default configuration stays in server_settings and is not a user setting. This key describes which badges to show, not whether to show them — that is ui.card_overlays_enabled. Revision 13 adds the advisory_age overlay id; a server below revision 13 rejects a value that contains it, so a client offers that badge only when manifest_revision is at least 13. Revision 15 adds the request_status overlay id (a watchlist title's request status on its poster) under the same rule: a client offers it only when manifest_revision is at least 15. Revision 25 reserves the top-right corner for the watch-status indicator, which every client always draws and no setting controls, and adds the left-edge and right-edge positions, the plate and band presets, style, and the per-badge image and valueImages references to uploaded images; a server below revision 25 rejects a value that uses any of them, so a client writes them only when manifest_revision is at least 25. top-right stays valid so stored values keep validating, but from revision 25 a client draws a badge stored there on the right edge and writes right-edge instead. Revision 26 adds the resolution_hdr_audio overlay id (one badge combining resolution, dynamic range and audio codec); a server below revision 26 rejects a value that contains it, so a client offers that badge only when manifest_revision is at least 26. Revision 29 adds the availability overlay id (complete seasons on a series poster, episodes in the library on a season poster) under the same rule: a client offers it only when manifest_revision is at least 29." }, { "key": "ui.card_overlays_enabled", From fa22e02ccb698d317ed8cfa9f66c1c34078d84a1 Mon Sep 17 00:00:00 2001 From: Rhainland Date: Wed, 18 Nov 2026 18:34:41 +0100 Subject: [PATCH 4/4] fix(settings): make a Show Next Up time this device's whole choice Choosing a time wrote only the seconds while Next Up was already on, so next_up_enabled stayed inherited from the profile. Turning Next Up off for the profile elsewhere then turned it off on this device too, although its picker showed a choice of its own. Where the server stores Off, a time now writes both keys. --- .../silo/common/settings/NextUpChoice.kt | 11 +++++-- .../silo/common/settings/NextUpChoiceTest.kt | 29 +++++++++++++++++++ .../ui/screens/settings/SettingsViewModel.kt | 6 ++-- .../screens/settings/TvSettingsViewModel.kt | 6 ++-- 4 files changed, 45 insertions(+), 7 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt index f9b3ecc6a0..4de71075e1 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/NextUpChoice.kt @@ -23,13 +23,18 @@ object NextUpChoice { fun selected(enabled: Boolean, seconds: Int): Int? = if (enabled) seconds.coerceAtLeast(0) else null - /** Off leaves the seconds alone; a time turns Next Up back on if it was off. */ - suspend fun apply(store: PlayerSettingsStore, choice: Int?, currentlyEnabled: Boolean) { + /** + * Off leaves the seconds alone. A time writes both keys where the server + * stores Off, so the picker's choice is this device's whole choice: one + * inherited half would follow a later profile change to Off. Where the + * server lacks the key, only a saved Off is turned back on. + */ + suspend fun apply(store: PlayerSettingsStore, choice: Int?, currentlyEnabled: Boolean, offSupported: Boolean) { if (choice == null) { store.setNextUpEnabled(false) return } - if (!currentlyEnabled) store.setNextUpEnabled(true) + if (offSupported || !currentlyEnabled) store.setNextUpEnabled(true) store.setNextUpPromptSeconds(choice) } } diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt index 403ae637c8..2c453311d9 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/settings/NextUpChoiceTest.kt @@ -1,5 +1,7 @@ package org.siloserver.silo.common.settings +import java.lang.reflect.Proxy +import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals @@ -13,4 +15,31 @@ class NextUpChoiceTest { assertEquals(listOf(null) + times, NextUpChoice.options(offSupported = false, enabled = false)) assertEquals(null, NextUpChoice.selected(enabled = false, seconds = 30)) } + + @Test + fun aTimeIsAChoiceOfBothKeysWhereverTheServerStoresOff() = runTest { + // On already (inherited from the profile): the time still writes On, so + // this device's choice survives the profile turning Next Up off later. + assertEquals(listOf("enabled=true", "seconds=10"), writes(10, currentlyEnabled = true, offSupported = true)) + assertEquals(listOf("enabled=true", "seconds=30"), writes(30, currentlyEnabled = false, offSupported = true)) + assertEquals(listOf("enabled=false"), writes(null, currentlyEnabled = true, offSupported = true)) + // A server without the key is never sent it while Next Up is on. + assertEquals(listOf("seconds=60"), writes(60, currentlyEnabled = true, offSupported = false)) + // A saved Off made before the manifest was read is turned back on. + assertEquals(listOf("enabled=true", "seconds=0"), writes(0, currentlyEnabled = false, offSupported = false)) + } + + private suspend fun writes(choice: Int?, currentlyEnabled: Boolean, offSupported: Boolean): List { + val calls = mutableListOf() + val unused = Proxy.newProxyInstance( + PlayerSettingsStore::class.java.classLoader, + arrayOf(PlayerSettingsStore::class.java), + ) { _, method, _ -> throw UnsupportedOperationException(method.name) } as PlayerSettingsStore + val store = object : PlayerSettingsStore by unused { + override suspend fun setNextUpEnabled(value: Boolean) { calls += "enabled=$value" } + override suspend fun setNextUpPromptSeconds(value: Int) { calls += "seconds=$value" } + } + NextUpChoice.apply(store, choice, currentlyEnabled, offSupported) + return calls + } } 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 c199dc78f5..92a40a1ed4 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 @@ -451,8 +451,10 @@ class SettingsViewModel( /** A Show Next Up choice: seconds before the end, or null for Off. */ fun setNextUpChoice(choice: Int?) { - val enabled = _uiState.value.nextUpEnabled - viewModelScope.launch { NextUpChoice.apply(playerSettingsStore, choice, enabled) } + val state = _uiState.value + viewModelScope.launch { + NextUpChoice.apply(playerSettingsStore, choice, state.nextUpEnabled, state.nextUpOffSupported) + } } fun setPassOutThreshold(value: Int) { 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 951a092b44..e8d3062a5e 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 @@ -864,8 +864,10 @@ class TvSettingsViewModel( /** A Show Next Up choice: seconds before the end, or null for Off. */ fun onNextUpChoice(choice: Int?) { - val enabled = _uiState.value.nextUpEnabled - viewModelScope.launch { NextUpChoice.apply(playerSettingsStore, choice, enabled) } + val state = _uiState.value + viewModelScope.launch { + NextUpChoice.apply(playerSettingsStore, choice, state.nextUpEnabled, state.nextUpOffSupported) + } } /**