Skip to content

Player: DV Profile 7 direct play, mpv Atmos passthrough fix, mobile error recovery - #34

Closed
Quick104 wants to merge 1 commit into
mainfrom
player/dv-p7-passthrough-recovery
Closed

Quick104 wants to merge 1 commit into
mainfrom
player/dv-p7-passthrough-recovery

Conversation

@Quick104

@Quick104 Quick104 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to a code-level survey of seven open-source Android video players (jellyfin-androidtv, Findroid, jellyfin-android, Streamyfin, NextPlayer, Just Player, mpv-android — shallow-cloned and read end-to-end). The survey's conclusion: our player architecture already exceeds every surveyed app on engine routing, capability probing, and fallback planning — so no rewrite, but five concrete gaps were found and are fixed here. The full comparison lives in docs/media3/10-reference-player-comparison.md.

Fixes

  1. Mobile player-error recovery (parity with TV) — the phone player had no onPlayerError wiring and forced a FULL transcode on any preflight failure. It now runs the TV ladder: bounded transient-network same-route retry → PlaybackRecoveryPlanner → alternate direct engine (attemptedEngines ping-pong guard, route-event telemetry) → server remux → transcode, single-flighted. (PlayerViewModel.kt, PlayerScreen.kt)
  2. Dolby Vision Profile 7 direct play — policy no longer hard-refuses P7:
    • Native: allowed when the decoder claims dual-layer DV and multi-instance HEVC (MediaCodecCapabilitiesProbe's existing gate — the same model jellyfin-androidtv ships). DisplayHdrProbe no longer fabricates a [5, 8] panel profile list that silently vetoed legitimate P7 decoder claims.
    • Fallback: UnsupportedDvProfile now prefers an alternate direct engine (mpv renders the P7/P8 HDR10 base layer, tone-maps P5) and excludes remux (it re-sends the exact stream the decoder rejected) before conceding a transcode — Just Player's mapDV7ToHevc outcome without maintaining a Media3 fork.
  3. mpv Atmos/TrueHD passthrough actually bitstreams — default ao was aaudio, whose mpv AO cannot open IEC61937 (compressed) streams, so the existing audio-spdif config silently decoded to PCM. Now audiotrack,aaudio.
  4. mpv hwdec direct-first — mediacodec,mediacodec-copy instead of forced copy-back (double memory bandwidth on 4K); mpv falls back per-codec automatically.
  5. TS extractor hardening — FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS (DTS in Blu-ray-sourced M2TS) + 1500-packet timestamp search window. (SiloPlayerFactory.kt)

Server follow-up (separate repo)

The resolver still emits the dolby_vision_profile_7_not_launch_claimed blocker, which preempts the new client ladder with an immediate FULL transcode. To realize the P7 benefit it should stop blocking P7 (or list MPV_DIRECT as a fallback) now that clients claim and handle it honestly.

Test plan

  • :android-shared:testDebugUnitTest — passes, including new tests: P7 policy (native-gated, P5 unchanged, P8 unchanged) and planner behavior (UnsupportedDvProfile → alternate engine, never remux)
  • :androidApp:testDebugUnitTest, :shared:testDebugUnitTest — pass
  • :androidApp:assembleDebug, :androidTvApp:assembleDebug — build
  • :androidTvApp:testDebugUnitTest — passes; note TvAuthSingleFlightTest is load-flaky on main too (Ktor MockEngine real-dispatcher work racing a virtual-time withTimeout) — unrelated to this diff, worth a separate fix
  • On-device: DV P7 MKV on a non-DV HDR10 device (expect mpv base-layer HDR10 playback, not transcode) — blocked on the server-side blocker change
  • On-device: TrueHD/Atmos MKV over HDMI on the mpv route (expect bitstream passthrough on the AVR display)

🤖 Generated with Claude Code

https://claude.ai/code/session_01AaKRXz1mtnsDm6pn1LDkmz

Summary by CodeRabbit

  • New Features

    • Improved Dolby Vision playback handling, including broader support for Profile 7 and smarter fallback to alternate playback paths.
    • Updated playback defaults to better prioritize audio output and hardware decoding options.
  • Bug Fixes

    • Improved recovery from playback errors and transient network issues to reduce failed or interrupted playback.
    • Enhanced support for certain transport stream files and audio tracks.
  • Documentation

    • Added updated player-comparison guidance and revised Dolby Vision Profile 7 playback recommendations.

… recovery

Findings from a code survey of seven open-source Android players
(jellyfin-androidtv, Findroid, jellyfin-android, Streamyfin, NextPlayer,
Just Player, mpv-android), written up in docs/media3/10.

- Mobile player-error recovery (parity with TV): wire onPlayerError and
  PlaybackRecoveryPlanner into PlayerViewModel — bounded transient-network
  same-route retry, alternate direct engine with attemptedEngines guard and
  route-event telemetry, then server remux/transcode, single-flighted.
  Previously decoder/IO failures were dropped and every preflight issue
  forced a FULL transcode.
- Dolby Vision Profile 7: allow native direct play when the decoder claims
  dual-layer DV with multi-instance HEVC (the probe's existing gate);
  DisplayHdrProbe no longer strips P7 from the panel intersection (Android
  panels can't report per-profile DV support). Non-native P7 now prefers an
  alternate direct engine (mpv renders the HDR10 base layer) over transcode,
  and never remuxes (a remux re-sends the same rejected stream).
- mpv audio passthrough: default ao is now audiotrack,aaudio — mpv's AAudio
  AO cannot open IEC61937 streams, so audio-spdif passthrough silently
  decoded Atmos/TrueHD to PCM under aaudio.
- mpv hwdec: direct-first (mediacodec,mediacodec-copy) instead of forced
  copy-back, halving decode memory bandwidth on 4K.
- TS extractor hardening: FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS and a
  1500-packet timestamp search window for Blu-ray-sourced M2TS and
  high-bitrate transport streams.

Server follow-up: the resolver still emits
dolby_vision_profile_7_not_launch_claimed, which preempts the new client
ladder; it should stop blocking P7 (or offer MPV_DIRECT as a fallback) now
that clients claim and handle it honestly.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AaKRXz1mtnsDm6pn1LDkmz
@cursor

cursor Bot commented Jul 4, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR revises Dolby Vision profile 7 handling across HDR probing, direct-play eligibility, and recovery planning, adds a bounded playback error-recovery ladder to PlayerViewModel with alternate-engine and server-transcode fallback, updates mpv/TS extractor defaults, and documents the changes.

Changes

Dolby Vision profile 7 policy and playback recovery

Layer / File(s) Summary
HDR probe and direct-play eligibility
DisplayHdrProbe.kt, PlaybackCapabilityDetector.kt
DV profile list now includes 7 alongside 5 and 8; profile 7 direct-play falls back to a general capability check instead of a hard-coded block.
Recovery planner fallback logic
PlaybackRecoveryPlanner.kt
UnsupportedDvProfile now delegates to serverFallbackFromPlan with remux disallowed, preferring an alternate direct engine before server transcode.
Detector and planner tests
PlaybackCapabilityDetectorDolbyVisionTest.kt, PlaybackRecoveryPlannerTest.kt
Tests validate profile 7/5 direct-play eligibility and planner selection between AlternateDirectEngine and ServerTranscode.
PlayerViewModel recovery ladder
PlayerScreen.kt, PlayerViewModel.kt
New onPlayerError handles transient network retries, alternate-direct-engine fallback, single-flight server recovery, and updates onEngineSwitchFailed/onPositionChanged.
mpv and TS extractor defaults
MpvPlayer.kt, SiloPlayerFactory.kt
mpv audio output/hwdec defaults updated to preference lists; TS extractor gains HDMV DTS support and larger timestamp search window.
Documentation updates
docs/media3/10-reference-player-comparison.md, docs/media3/README.md
Adds a player comparison survey and updates README's TOC and DV Profile 7 guidance.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PlayerScreen
  participant PlayerViewModel
  participant PlaybackRecoveryPlanner
  participant PlaybackSessionManager

  PlayerScreen->>PlayerViewModel: onPlayerError(error)
  alt transient IO network error
    PlayerViewModel->>PlayerViewModel: retry same route (bounded)
  else other error
    PlayerViewModel->>PlaybackRecoveryPlanner: planForPlayability(...)
    PlaybackRecoveryPlanner-->>PlayerViewModel: PlaybackRecoveryAction
    alt AlternateDirectEngine
      PlayerViewModel->>PlaybackSessionManager: report PlaybackRouteEventRequest
    else
      PlayerViewModel->>PlayerViewModel: startServerRecoveryFallback (single-flight)
    end
  end
Loading

Possibly related PRs

  • Silo-Server/silo-android#11: Both PRs modify Dolby Vision direct-play logic in PlaybackCapabilityDetector and recovery branches in PlaybackRecoveryPlanner.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: DV Profile 7 direct play, mpv passthrough updates, and mobile error recovery.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch player/dv-p7-passthrough-recovery

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47292802e9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +865 to +867
if (positionSec > 0 && transientNetworkRetries > 0) {
transientNetworkRetries = 0
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep retry budget until playback actually advances

When a transient network error happens after the playhead is already >0, the remount enters STATE_BUFFERING; PlayerScreen still calls onPositionChanged while buffering with the same currentPosition. This resets transientNetworkRetries before any playback has advanced, so a persistent outage after the first retry can keep getting another “one” retry instead of falling through to the recovery ladder. Compare against the previous position, or reset from an actual playing/progress signal, so the budget is restored only after forward progress.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/media3/README.md (1)

66-69: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale quick-answer contradicts the new P7 policy just added below.

Line 68 still states "Profile 7 is not a launch-safe Android TV DV direct-play claim and needs the fallback policy in 09", but the newly-added entry at lines 82-87 says P7 direct-plays when the decoder reports dual-layer DV with multi-instance HEVC support. These two quick-answers now disagree on whether P7 can ever direct-play, which will confuse readers.

📝 Suggested fix
 - **"Why doesn't Dolby Vision work on my TV?"** Check the profile and selected
   route. DV Profile 5 needs a decoder **and** a DV-capable HDMI link; Profile 7
-  is not a launch-safe Android TV DV direct-play claim and needs the fallback
-  policy in **09**.
+  direct-plays only when the decoder reports dual-layer DV with multi-instance
+  HEVC support; otherwise it falls back per the policy in **09** and **10 §4**.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/media3/README.md` around lines 66 - 69, The Dolby Vision quick-answer in
the README is stale and conflicts with the newer Profile 7 policy entry. Update
the existing FAQ text near the “Why doesn’t Dolby Vision work on my TV?” item so
it matches the current P7 behavior described by the newer Dolby Vision policy
section, and make sure the wording in the README is consistent with the logic in
the Dolby Vision decoder/direct-play guidance.
🧹 Nitpick comments (1)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/mpv/MpvPlayer.kt (1)

65-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

mpv AO/hwdec priority-list defaults look correct.

The comma-separated fallback ordering for audioOutput/hwDec matches documented mpv behavior for these options, and the rationale comments are clear and accurate.

One minor note: these default string literals ("audiotrack,aaudio", "mediacodec,mediacodec-copy") are now duplicated between the class constructor defaults (Lines 71, 77) and the Builder defaults (Lines 135, 138). Pre-existing pattern, but consider hoisting them into companion object constants to prevent the two copies drifting apart on a future tuning change.

♻️ Optional: single source of truth for defaults
     companion object {
         private const val TAG = "SiloMpvPlayer"
         private const val AUDIO_FOCUS_DUCKING = 0.5f
+        private const val DEFAULT_AUDIO_OUTPUT = "audiotrack,aaudio"
+        private const val DEFAULT_HWDEC = "mediacodec,mediacodec-copy"

Then reference MpvPlayer.DEFAULT_AUDIO_OUTPUT / MpvPlayer.DEFAULT_HWDEC from both the class constructor default and Builder.

Also applies to: 135-138

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/mpv/MpvPlayer.kt`
around lines 65 - 77, The mpv fallback defaults are correct, but the
`audioOutput` and `hwDec` string literals are duplicated between `MpvPlayer`
constructor defaults and `Builder` defaults, which risks them drifting over
time. Hoist these defaults into shared `companion object` constants on
`MpvPlayer` (for example, `DEFAULT_AUDIO_OUTPUT` and `DEFAULT_HWDEC`) and update
both the primary constructor and `Builder` to reference those symbols so there
is a single source of truth.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt`:
- Around line 76-84: The TS extractor overrides in SiloPlayerFactory are only
being applied through the shared ExtractorsFactory, which does not affect HLS
playback. Update the HLS setup in this class so the same TS/M2TS settings are
applied separately to the HLS extractor factory as well, ensuring the
FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS and timestamp search bytes overrides are used
for .m3u8 streams too.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt`:
- Around line 284-293: The new recoveryJob in PlayerViewModel can outlive
content/version/exit changes and later overwrite _uiState with stale session
data. Cancel and null recoveryJob anywhere playback context changes or ends
(loadContent, onSelectVersion, onExit, onCleared), and reset attemptedEngines
plus transientNetworkRetries when switching versions like the existing
engineSwitchFallbackAttempted reset. Also add a staleness guard in the recovery
completion path, following resolveNextEpisode’s forContentId check, so any late
recovery result is ignored if the active content/session has changed.

---

Outside diff comments:
In `@docs/media3/README.md`:
- Around line 66-69: The Dolby Vision quick-answer in the README is stale and
conflicts with the newer Profile 7 policy entry. Update the existing FAQ text
near the “Why doesn’t Dolby Vision work on my TV?” item so it matches the
current P7 behavior described by the newer Dolby Vision policy section, and make
sure the wording in the README is consistent with the logic in the Dolby Vision
decoder/direct-play guidance.

---

Nitpick comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/mpv/MpvPlayer.kt`:
- Around line 65-77: The mpv fallback defaults are correct, but the
`audioOutput` and `hwDec` string literals are duplicated between `MpvPlayer`
constructor defaults and `Builder` defaults, which risks them drifting over
time. Hoist these defaults into shared `companion object` constants on
`MpvPlayer` (for example, `DEFAULT_AUDIO_OUTPUT` and `DEFAULT_HWDEC`) and update
both the primary constructor and `Builder` to reference those symbols so there
is a single source of truth.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 49760559-d1cf-454a-906e-723787f43e37

📥 Commits

Reviewing files that changed from the base of the PR and between 95eb42d and 4729280.

📒 Files selected for processing (11)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/DisplayHdrProbe.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackCapabilityDetector.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackRecoveryPlanner.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/mpv/MpvPlayer.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackCapabilityDetectorDolbyVisionTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackRecoveryPlannerTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt
  • docs/media3/10-reference-player-comparison.md
  • docs/media3/README.md

Comment on lines +76 to +84
// HDMV DTS streams (Blu-ray-sourced M2TS) use a stream type the TS
// payload reader skips by default, so DTS tracks vanish from
// Blu-ray-remux transport streams without this flag.
.setTsExtractorFlags(DefaultTsPayloadReaderFactory.FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS)
// The default PCR search window is too small for high-bitrate 4K
// remux/transcode TS segments with sparse PTS — startup then fails
// with "timestamp not found" (androidx/media #8571-class failures).
// 1500 packets matches what battle-tested players ship.
.setTsExtractorTimestampSearchBytes(1500 * TsExtractor.TS_PACKET_SIZE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does DefaultMediaSourceFactory pass a custom ExtractorsFactory to HlsMediaSource in current androidx media3?

💡 Result:

No, DefaultMediaSourceFactory does not pass a custom ExtractorsFactory to HlsMediaSource [1][2]. The ExtractorsFactory provided to the DefaultMediaSourceFactory constructor is intended for and used by ProgressiveMediaSource (the fallback media source for regular media files) [1][2]. HlsMediaSource uses a different type of factory for its segments, called an HlsExtractorFactory [3][4]. HlsMediaSource.Factory uses DefaultHlsExtractorFactory by default [3][4]. If you need to customize extraction for HLS, you must use the HlsMediaSource.Factory.setExtractorFactory method directly, rather than providing an ExtractorsFactory to the DefaultMediaSourceFactory [3][4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant factory and surrounding wiring.
file="android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt"
sed -n '1,220p' "$file"

printf '\n\n--- grep for HLS/extractor wiring ---\n'
rg -n "DefaultMediaSourceFactory|HlsMediaSource|ExtractorsFactory|setExtractorFactory|setTsExtractorFlags|setTsExtractorTimestampSearchBytes" \
  android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt \
  android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player \
  || true

Repository: Silo-Server/silo-android

Length of output: 13692


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Probe Media3 API docs from the codebase? No network here, so just inspect local references if any.
rg -n "setExtractorFactory\\(|DefaultHlsExtractorFactory|HlsExtractorFactory" android-shared/src || true

Repository: Silo-Server/silo-android

Length of output: 162


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt"

# Show the relevant region with line numbers.
nl -ba "$file" | sed -n '1,220p'

printf '\n--- HLS / extractor references in the repo ---\n'
rg -n "DefaultMediaSourceFactory|HlsMediaSource|ExtractorsFactory|setExtractorFactory|DefaultHlsExtractorFactory|setTsExtractorFlags|setTsExtractorTimestampSearchBytes" android-shared/src || true

Repository: Silo-Server/silo-android

Length of output: 202


Apply the TS extractor overrides to HLS separately

DefaultMediaSourceFactory(context, extractorsFactory) only forwards this ExtractorsFactory to progressive playback; HLS builds its own extractor factory. If these TS/M2TS streams can be delivered as .m3u8, the DTS and timestamp-search settings won’t apply there, and the same playback failures can still surface on that path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt`
around lines 76 - 84, The TS extractor overrides in SiloPlayerFactory are only
being applied through the shared ExtractorsFactory, which does not affect HLS
playback. Update the HLS setup in this class so the same TS/M2TS settings are
applied separately to the HLS extractor factory as well, ensuring the
FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS and timestamp search bytes overrides are used
for .m3u8 streams too.

Comment on lines +284 to +293

// Recovery ladder state — mirrors TvPlayerViewModel. The planner picks the
// cheapest viable fallback (alternate direct engine → server remux →
// transcode); attemptedEngines prevents Media3↔mpv ping-pong; the
// transient-network budget lets a single blip retry the SAME route instead
// of demoting a healthy direct stream for the rest of playback.
private val recoveryPlanner = PlaybackRecoveryPlanner()
private val attemptedEngines = mutableSetOf<PlaybackEngineKind>()
private var transientNetworkRetries = 0
private var recoveryJob: Job? = null

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

recoveryJob isn't cancelled (or staleness-guarded) across content/version/exit transitions.

recoveryJob is new state, but none of loadContent, onSelectVersion, onExit, or onCleared cancel it — unlike resolveNextEpisodeJob, which loadContent already cancels for this exact class of race. If a server recovery fallback is in flight when the user advances episodes, switches version, or exits, its eventual completion unconditionally overwrites _uiState (sessionId, playbackPlan, streamUrl, startPosition, …) with data belonging to the old, already-stopped session — corrupting the new session's playback state. attemptedEngines/transientNetworkRetries have the same gap in onSelectVersion (only engineSwitchFallbackAttempted is reset there).

Cancelling the job is necessary but not sufficient on its own (cooperative cancellation can't preempt a coroutine already past its last suspension point). The existing resolveNextEpisode() guards exactly this hazard by capturing forContentId and checking it before applying the update — recommend the same pattern here.

🔧 Proposed fix
         autoAdvanceHandled = false
         engineSwitchFallbackAttempted = false
         attemptedEngines.clear()
         transientNetworkRetries = 0
+        recoveryJob?.cancel()
+        recoveryJob = null
         resolveNextEpisodeJob?.cancel()

Apply the same recoveryJob?.cancel(); recoveryJob = null (plus attemptedEngines.clear() / transientNetworkRetries = 0) in onSelectVersion() near engineSwitchFallbackAttempted = false, and in onExit() / onCleared() alongside the other job cancellations.

Additionally, guard the completion handler itself:

             when (val r = playbackSessionManager.startTranscodeFallbackRecoveringMissingSession(...)) {
                 is ApiResult.Success -> {
                     val fallback = r.data
+                    // Skip a stale completion that raced a subsequent
+                    // loadContent/onSelectVersion/onExit for a different session.
+                    if (_uiState.value.sessionId != sessionId) return@launch
                     sessionLifecycle.adoptActiveSession(...)

Also applies to: 398-399

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt`
around lines 284 - 293, The new recoveryJob in PlayerViewModel can outlive
content/version/exit changes and later overwrite _uiState with stale session
data. Cancel and null recoveryJob anywhere playback context changes or ends
(loadContent, onSelectVersion, onExit, onCleared), and reset attemptedEngines
plus transientNetworkRetries when switching versions like the existing
engineSwitchFallbackAttempted reset. Also add a staleness guard in the recovery
completion path, following resolveNextEpisode’s forContentId check, so any late
recovery result is ignored if the active content/session has changed.

@RXWatcher

Copy link
Copy Markdown
Contributor

Closing this in favor of a consolidated parity/open-issues PR from fix/open-issues-upstream-main. The current branch already contains this work plus later followups and review-comment fixes will land in the consolidated PR.

@RXWatcher RXWatcher closed this Jul 6, 2026
@RXWatcher
RXWatcher deleted the player/dv-p7-passthrough-recovery branch July 13, 2026 19:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants