Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -701,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)
}
Expand Down Expand Up @@ -1036,8 +1037,7 @@ class PlayerViewModel(
.stateIn(viewModelScope, SharingStarted.Eagerly, IntroSkipMode.Default)
val autoPlayNextEnabled: StateFlow<Boolean> = 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<Int> = playerSettingsStore.nextUpPromptSecondsFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, 30)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -4828,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.
*/
Expand Down Expand Up @@ -6162,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) {
Expand All @@ -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
Expand All @@ -6202,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) }
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -6308,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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1861,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
Expand Down Expand Up @@ -2008,6 +2009,9 @@ class TvPlayerViewModel(
// Per-profile "Still watching?" threshold (default 3; 0 = off).
val passOutThreshold: StateFlow<Int> = 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<Int> = playerSettingsStore.nextUpPromptSecondsFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, 30)
val hdrEnabled: StateFlow<Boolean> = playerSettingsStore.hdrEnabledFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
val dolbyVisionEnabled: StateFlow<Boolean> = playerSettingsStore.dolbyVisionEnabledFlow
Expand Down Expand Up @@ -3880,13 +3884,22 @@ 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()
}
// 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.
Expand Down Expand Up @@ -5234,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.
*/
Expand Down Expand Up @@ -5358,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.
Expand All @@ -5367,12 +5380,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
Expand All @@ -5381,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 ->
Expand Down Expand Up @@ -5451,7 +5466,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 —
Expand Down Expand Up @@ -5509,7 +5524,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
Expand Down Expand Up @@ -6614,7 +6629,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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ class MarkerTimeline private constructor(private val regions: List<Pair<MarkerKi
}

/**
* Where Up Next appears: the start of the last credits range, extended
* back over credits ranges that run into it, so a scene between two
* credits ranges still plays.
* Where the closing credits begin: the start of the last credits range,
* extended back over credits ranges that run into it, so a scene between
* two credits ranges still counts as part of the episode.
*/
fun upNextCreditsStart(): Double? {
fun finalCreditsStart(): Double? {
val credits = ranges(MarkerKind.Credits)
var start = credits.lastOrNull()?.start ?: return null
for (range in credits.asReversed()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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, as on iOS/tvOS (`PlayerNextUpCompletionPolicy`). Credits
* markers drive Skip Credits; 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
Comment on lines +22 to +23

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug medium

Short episodes never cross the configured Up Next prompt point

Episodes at or below the configured offset end without showing Up Next because promptStart is nonpositive and playback starts at zero. Handle this boundary explicitly so the prompt can appear during playback.

Prompt for LLM
File shared/src/commonMain/kotlin/org/siloserver/silo/domain/player/NextUpPrompt.kt, lines 22-23:

Short episodes never cross the configured Up Next prompt point

A file whose duration is less than or equal to the configured offset never shows Up Next before ending because its prompt point is nonpositive and playback positions start at zero. Handle this boundary explicitly so short episodes can surface the prompt during playback.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as main. The phone already computed the point as duration minus the lead time and needed a forward crossing, so a file no longer than the lead never opened the card early; the TV never used the setting at all. Such a file still gets Up Next when the stream ends (onApproachingEnd(videoEnded = true)). The longest lead is 2 minutes, so this only affects clips, not episodes.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That context changes the assessment: short files still get Up Next when playback ends, so the suggestion overstates the impact. The phone’s behavior is also unchanged from main; the TV’s prior behavior was different because it did not use the setting.

There is still a boundary case: for a file no longer than the configured lead time, the prompt cannot open early under the crossing logic. Whether to change that is a product decision rather than necessarily a regression in this PR. I would not treat it as blocking #994.

}
}
Loading
Loading