Skip to content

ADR 0003: Use cases for playback and downloads

Status: Proposed (2026-11-25, in #970). Refines ADR 0001, decision 1, and ADR 0002, decision 3. The PRs are in “The order of the PRs” below. Corrected the same day after a second-opinion review on PR #1000, with the overseer’s decisions on the order, the rule numbers and Q4.

Progress: PR 1 is done (2026-12-01): every row of the download table has a test against today’s queue. The table below was brought up to date with the code at the same time: #1002 and #1003 were fixed after it was written (rows 5 to 10), and row 29’s order was wrong.

PR 2 is done (2026-12-01): the machine is in domain (dev.jdtech.jellyfin.domain.downloads.model and .rule, DownloadStage?.on), with no caller, tested row by row in DownloadTransitionTest. Where the table and the code differed, the machine follows the code; the cells were corrected and the list is under “What PR 2 found”.

PR 3 is done (2026-12-01): DownloadQueue sends every event to the machine and carries out its effects; Entry and EntryState are mapped from the stage (DownloadQueueStages.kt). The tests of PR 1 and the other queue tests pass unchanged. Rule R24 landed with it (architecture/size-ceilings.txt, SizeCeilingTest). Where this ADR and the code differed, the code won; the list is under “What PR 3 found”.

PR 4 is done (2026-12-01): DownloadQueue takes its wall clock, its monotonic clock, its dispatcher and its scope as constructor parameters, and DownloaderModule.provideDownloadQueue passes the real ones. The DownloadQueue*Test classes run under runTest in virtual time (QueueVirtualTime.kt), with no Thread.sleep; three tests were added for the backoff, the #912 guard and the server’s return. Only DownloadQueueMachineReviewTest still writes the queue’s list by reflection, for a failed and a queued entry of one item that no short run of events reaches. The queue grew by one line, and its R24 ceiling went down from 1163 to 1158. R26 did not land with it; why is under “What PR 4 found”. It landed with #1104.

PR 9 is done (2026-12-02): six player rules are in domain (dev.jdtech.jellyfin.domain.playback.rule), moved as renames with their tests: SegmentTracker, UpNextCountdown, StillWatchingTracker, SleepTimer, PlaybackStartGate and ReportedPause. matchSeriesTrack and seriesTrackChoice go to step 10. The Q4 test was corrected on the way; both are under “What PR 9 found”.

PR 5 is done (2026-12-02): Downloader is a port of application (dev.jdtech.jellyfin.application.downloads.port). A start returns a DownloadStart (Started with the download id, or Failed with a DownloadFailure of domain), and Progress.status is an EngineStatus. The queue makes the words for a failure (DownloadTexts.failureText in downloads), so DownloaderImpl no longer takes DownloadTexts. FakeDownloader in testing replaces the private fakes of eight queue tests. The R24 ceilings went down: DownloaderImpl from 1665 to 1639, DownloadQueue from 1158 to 1144. The list is under “What PR 5 found”.

PR 10 is done (2026-12-02), in three commits that share nothing. playbackStopReport is in dev.jdtech.jellyfin.domain.playback.rule and PlayingSnapshot in .model, with an unknown duration as null. resolveAutoPlayNext and autoPlayNextFollowsServer take an AutoPlayNextSetting that PlayerSettings returns, so they no longer read settings.domain.Constants. matchSeriesTrack, seriesTrackChoice and normalizeLanguage moved to domain; serverAudioTracks and audioStreamIndex stay in player/local, in ServerAudioTracks.kt. The two KDoc links to PlayerViewModel are plain text now. The rest is under “What PR 10 found”.

PR 11 is done (2026-12-02): the end of an item is a rule in steps, EndOfItemSteps in dev.jdtech.jellyfin.domain.playback.rule, with no caller. P7 has today’s order as a table of 43 rows, each a test in EndOfItemStepsTest. The Q4 test no longer lets a changed non-Kotlin rename under player/ through (#1112). What looks wrong in today’s order is under “What PR 11 found”.

PR 12 is done (2026-12-02, PR 1117): PlayerViewModel calls EndOfItemSteps at the end of an item, in the “Up next” update, the outro skip, the prompt’s confirmation and play after the sleep timer, and carries out what each step returns. The rule needed no change. A new PlayerInvariantsTest case fails when the view model reads the trackers’ decisions itself. Its R24 ceiling went down from 2534 to 2530; why so little is under “What PR 12 found”.

PR 13 is done (2026-12-02): PlaybackReporter is a service of application (dev.jdtech.jellyfin.application.playback.service). It takes each stream as a ReportedStream (the item, the version, the play session, transcoded or not, the start position), which the view model makes from the PlayerItem, and logs through AppLog (dev.jdtech.jellyfin.application.log.port), the one log port of application (Q5): the repository’s RepositoryLog renamed, with FallbackLog folded into it, and TimberAppLog in core. The start report’s Job left PlayingSnapshot: the service keeps it with the snapshot as a ReportedItem. PlaybackReporterModule in player/local still provides one per player. The 31 tests of PlaybackReporterTest moved to application unchanged but for the stream value, and PlayerInvariantsTest reads the service’s file there. The rest is under “What PR 13 found”.

PR 14 is done (2026-12-02, PR 1130): Cast’s stop takes its percentage from playbackStopReport, which has Cast’s clamp to 0..100 as an input (clampPercentage), and CastPlayerControllerImpl sends Cast’s three reports through PlaybackReporter (sendDecidedStart, sendDecidedProgress, sendDecidedStop). Cast keeps its own gate. R25 landed with it (ReportSenderTest), with no baseline. CastReportSendingTest pinned what the server gets for each Cast report before the move and passes unchanged after it. The R24 ceiling of CastPlayerControllerImpl went down from 1192 to 1190. The rest is under “What PR 14 found”.

PR 6 is done (2026-12-02): DownloadQueue is a service of application (dev.jdtech.jellyfin.application.downloads.service), moved as a rename with its published view, its speed sample and the service’s notice. What it needs from Android goes through four ports in dev.jdtech.jellyfin.application.downloads.port: DownloadPump, DownloadFailureNotice, DownloadQueueTexts and DownloadQueueLog. downloads implements them in DownloadQueueAndroid.kt (113 lines). What starts next is nextDownloads in domain. The queue tests moved with it and run on the JVM without Robolectric. The R24 ceiling of DownloadQueue went down from 1148 to 1100. The list is under “What PR 6 found”.

PR 7 is done (2026-12-02): the queue stores each download’s DownloadStage, and the screens read its view, DownloadStageView in dev.jdtech.jellyfin.domain.downloads.model (queued, waiting for the network, running, paused, finished, failed). EntryState, DownloadEntryState and both DownloadStatus types are gone; the engine speaks EngineStatus. What a screen shows of each stage is decided in its composable, as before, and the view models’ mapping is tested (DownloaderStateTest, ActiveDownloadMappingTest, EpisodeDownloadProgressTest, DownloadQueueStagesTest). The R24 ceilings went down: DownloaderImpl from 1647 to 1629, DownloadQueue from 1100 to 1065. The list is under “What PR 7 found”.

PR 8 is done (2026-12-02): the rules DownloaderImpl held are in domain (dev.jdtech.jellyfin.domain.downloads.rule): the orphan sweep, the paths and file names, which streams are kept as files of their own, the percentage of a transfer, the metered and roaming rule the engine calls, and the finalize of a video and of an external track as steps (FinalizeSteps.kt). DownloaderImpl keeps the files, the rows and the engine. Their tests are plain JVM tests in domain, with a table for the sweep and one for the finalize. The R24 ceiling of DownloaderImpl went down from 1629 to 1493. The list is under “What PR 8 found”.

PR 15 is done (2026-12-02, PR 1133): ResolvePlayback is a use case of application (dev.jdtech.jellyfin.application.playback.service) and gives a ResolvedStream (the source that plays and the cap it was asked with). It reads the settings through PlayerSettings, which gained the preferred audio language and the cap per network, and QualityNetwork moved to dev.jdtech.jellyfin.domain.playback.model. player/local provides it (ResolvePlaybackModule) and keeps building the PlayerItem from it. Its tests run on the JVM in application; what the queue asks for and carries was pinned first, in PlaylistManagerResolvedStreamTest. The rest is under “What PR 15 found”.

PR 16 is done (2026-12-02, PR 1136): which tracks play is decided in application (dev.jdtech.jellyfin.application.playback.service), by two classes. TrackPreferences holds the view model’s part: the choice of this session and of the series, read ahead, applied when the tracks change (the reset alone, or with the picks now or once the series’ row is read) and remembered after a pick by hand. TranscodeAudio holds PlaylistManager’s part: the audio index a transcode is asked for, and the second request that asks for it. Tracks are a TrackKind of our own instead of media3’s numbers; the rows keep the numbers they had. ResolvedStream’s constructor is internal. The order of apply, reset and read was pinned first, on a copy of the view model’s code in player/local, and the same tests now run in application over fakes of testing. The R24 ceiling of PlayerViewModel went down from 2530 to 2443. The rest is under “What PR 16 found”.

PR 17 is done (2026-12-03, PR 1139): the play queue is PlayQueue, a service of application (dev.jdtech.jellyfin.application.playback.service). It holds what PlaylistManager held: the queue of a movie, an episode, a season, a series from next up and a shuffle, the item that plays, previous and next with the next season, which items it handed out, and where the first item starts. PlaylistManager stays in player/local and only makes a PlayerItem of each item; the local player and Cast both use the queue through it. The rules no test held were pinned on PlaylistManager first, then moved with the queue’s tests. No R24 ceiling changed. The rest is under “What PR 17 found”.

PR 18 (2026-12-03) moves the stream switches: StreamSwitches and rebuildQueue are a service of application (dev.jdtech.jellyfin.application.playback.service), generic over the player’s item. The service also stores a quality pick for the network in use, through ResolvePlayback, and decides when an item asked for on the other network has the queue asked for again (itemPlays), which the view model did. The view model keeps the reload (swapInQueue), the PlayerItem and the failure text. Cast’s audio switch shares too little to join it. R27 landed with it (PlayerRulesMedia3Test): the media3 mappers of the player’s domain package moved to a mapping package, and its two rules that read media3 values take our own. The R24 ceiling of PlayerViewModel went down from 2443 to 2420. The rest is under “What PR 18 found”.

With PR 18 the 18 steps of this ADR are done. What they did not reach is under “Where the series ended”.

application is almost only interfaces. The rules of playback and downloads sit in four large classes, where they are hard to test and easy to break:

Class Lines on main (41de995ad) Unit tests of its own
PlayerViewModel (player/local/.../presentation/) 2583 none of its logic: PlayerErrorTest covers the error events, PlayerInvariantsTest reads its source with regular expressions
CastPlayerControllerImpl (player/cast/src/proprietary) 1097 none; only its pure helpers are tested
DownloaderImpl (downloads/.../utils/) 1529 Robolectric, with a real engine over OkHttp fakes
DownloadQueue (downloads/.../core/presentation/downloader/) 1004 Robolectric, runBlocking and Thread.sleep loops: no clock or dispatcher can be injected

Most regressions fixed between 2.8.0 and 2.9.0 were in this code. What each one broke, and where that rule lives now:

Issue The rule that was broken Where it lives now Pure test
#601 No start before the first ready state; no progress or stop before a start PlaybackStartGate, inside PlaybackReporter PlaybackStartGateTest
#674 A pause or resume is reported at once; a buffering stall is not ReportedPause; the trigger is onPlayWhenReadyChanged in the view model ReportedPauseTest; the trigger only by regex
#868 The start carries the player’s position when it is sent PlaybackReporter.sendPlaybackStart PlaybackReporterTest
#869 The item being left reports its last position, never the next file’s 0 MpvItemLeftPosition (the mpv engine) MpvItemLeftPositionTest
#870 Every new stream of the playing item gets one start, with or without a transition PlaybackReporter.onStreamReplaced; the call is in swapInQueue in the view model PlaybackReporterTest
#890 The previous item’s stop reaches the server before the next start; only the newest transition sends one PlaybackReporter (ItemTransition, stopsInFlight) PlaybackReporterTest
#909 Every report names the version that plays PlaySessions (domain) PlaySessionsTest
#726 Only the newest switch is applied; a failed switch undoes only its own change StreamSwitches StreamSwitchesTest
#848 A download is finished only when its finalize succeeded split over DownloadQueue (the outcome) and four places in DownloaderImpl Robolectric only
#850 A resume sends the stored validator as If-Range ResumeValidators and the engine ResumeValidatorsTest
#912 A download that failed for want of an answer goes on when the server is back DownloadQueue (retryWhenServerReturns, afterFailure) Robolectric only

Two things follow. First, the playback rules that broke were moved into small classes as they were fixed (#765, #766 started that), and those classes are tested; what is left in the view model is the wiring that decides when each rule runs, and several flows whose order lives only there (the end of an item, the track choice). Second, the download rules were fixed in place: the life of one download is spread over an in-memory EntryState, the engine’s DownloadStatus numbers, a second DownloadStatus enum for the screens, the file suffix and two Room tables, and none of it is tested without Robolectric.

The playback rules also exist a second time in Cast. CastPlaybackReporter is its own decider for start, progress and stop; Cast reloads at a position for an audio switch on its own; it reuses PlaylistManager and SegmentTracker from player/local. Only #909 was fixed on both sides.

The player’s domain package is not the domain layer: it is a package of player/local, an Android module, and PlaylistManager, PlaybackReporter, PlaybackStopReport and EndOfItem import media3 constants. A rule there cannot be used by application and is not covered by R5 or R19.

  1. A use case is a flow with rules or state of its own, nowhere else. ADR 0001 (decision 1) named four: resolving what to play, reporting playback, the play queue and the download queue. ADR 0002 (decision 3) kept “no use case per call”. This ADR keeps both and names the flows that qualify (the inventory below). A view model still calls MediaRepository or a port directly for a plain read or write (a chapter image, the segments of an item, a favourite mark). No class is written only to pass a call through.
  2. Two shapes. A rule is a pure function or value in domain: no coroutines, no clock, time as a parameter (as PlayState already is). A service is a class in application over ports, with the state of one flow, an injected scope, dispatcher and clock, tested with runTest. Details in “How a use case is shaped”.
  3. The view model keeps the screen; the engine keeps the engine. A view model holds the state the screen shows, maps the user’s actions to services, and maps media3’s events and track groups to our own types. An engine (ExoPlayer, mpv, the Cast receiver, the download engine) does I/O and reports what happened. Neither decides what a rule decides.
  4. The life of one download is a state machine in domain, with the engine as an adapter that only does I/O. Its table describes today’s behaviour completely and is pinned by tests against the current code before it replaces anything. DownloadState stays what the rows say (no schema change in this series; #1124, a fix outside it, added schema 23); the stage does not decide it.
  5. One rule set for both players. The local player and Cast call the same services and rules. Where Cast behaves differently today, the move keeps the difference as an explicit input, and a change of behaviour is a separate fix PR with its own issue.
  6. No change of behaviour in a move. Each PR moves one flow, keeps the existing tests green and adds pure tests. A bug found on the way is filed, not fixed in the move.
  7. New code goes in packages by layer, area and kind now, in the scheme #971 asks for (Q2): dev.jdtech.jellyfin.domain.<area>.model and .rule, dev.jdtech.jellyfin.application.<area>.port and .service, with playback and downloads as the areas, so #971 does not move it again.

Line numbers are those of main at 41de995ad. “VM” is PlayerViewModel.kt.

P1. Resolving what plays.

  • Where: ResolvePlayback (109 lines: sources, pick, the cap per network of #837, the preferred audio language); PlaylistManager.toPlayerItem and withChosenAudio (497 to 633), which may ask the server a second time for the chosen audio; VM initializePlayer (708 to 773) and toMediaItem (779 to 828). Cast: CastPlayerControllerImpl.playItem (754 to 827) resolves each item through the local PlaylistManager, with the local target and cap, and then asks again through MediaServer.playback for PlaybackTarget.CastReceiver (receiverSource, 640 to 660), keeping only the source id and the start position of the first answer.
  • Depends on: MediaRepository, AppPreferences, AppVariant, NetworkConnectivity; PlayerItem (Parcelable, Uri).
  • Needed by: the local player (phone, TV), Cast, the downloads’ quality choice (the cap).
  • Tests: ResolvePlaybackTest, PlaylistManagerAudioChoiceTest, PlaylistManagerUnfinishedDownloadTest. Bugs: #766, #837, #860 (the played version).
  • Decision: a use case in application, ResolvePlayback, one operation: an item id, a wanted source, a playback target, a cap and an audio stream in; a resolved stream out (the source, the URL, transcoded or not, the play session, the cap asked for, the audio streams), in our own types. The settings come through the player settings port of #969. Building a PlayerItem and a MediaItem from the result stays in player/local. Cast keeps its two requests in the move; asking once is a fix of its own.

P2. The queue and the next episode.

  • Where: PlaylistManager (672 lines: getInitialItem 105 to 272, loadQueue 273, getPreviousPlayerItem / getNextPlayerItem 294 to 379, the next season 380, jumpTo 440, shuffle); NeighbourLoader; VM playQueueItem, playEpisode, jumpToQueued (835 to 877) and the deferred neighbour work (1175 to 1216). Cast: manageQueue (833 to 863) over the same PlaylistManager, plus CastPlaylistOrder, because a PlaylistManager hands out each neighbour once.
  • Depends on: MediaRepository, P1, Timber, media3’s C and androidx.core.net.
  • Needed by: the local player, Cast, the TV player’s queue row.
  • Tests: PlaylistManagerQueueTest, PlaylistManagerNextUpTest, PlaylistManagerNextSeasonTest, PlaylistManagerShuffleTest, NeighbourLoaderTest, CastPlaylistOrderTest. Bugs: #657 (the neighbours of an item left early), an item found by index instead of id (the pitfall in the player guide).
  • Decision: a service in application, the play queue, with the list of items, the current one, previous and next, the next season and shuffle, over the catalog role and P1. It hands out items, not PlayerItems; the mapping stays in player/local. Inserting into the player’s playlist stays in the view model. The start position rule (the saved state, the item’s resume position, from the beginning: VM 755 to 760) moves with it.

P3. The reports to the server.

  • Where: PlaybackReporter (420 lines: onItemTransition 160, onTransitionHandled 182, onStreamReplaced 204, sendPlaybackStart 237, reportStopped 286, reportProgress 362), PlaybackStartGate, ReportedPause, playbackStopReport; in the VM releasePlayer (901 to 935), refreshPlayingSnapshot and its outro variant (946 to 967), reportProgress (998 to 1004), the transition (1086 to 1172), the ready state (1696 to 1700), swapInQueue (2107) and the background loop (2490 to 2498); the phone’s 5 s loop in PlayerActivity, TV’s TvProgressReports. Cast: CastPlaybackReporter (190 lines, pure, with a clock) and its sender in CastPlayerControllerImpl (462 to 544).
  • Depends on: MediaRepository (postPlaybackStart, postPlaybackProgress, postPlaybackStop, setPlaySession), PlaybackEvents, an application scope (a stop outlives the player), the IO dispatcher, media3’s C, PlayerItem, Timber.
  • Needed by: the local player (phone, TV), Cast.
  • Tests: PlaybackReporterTest, PlaybackStartGateTest, PlaybackStopReportTest, ReportedPauseTest, CastPlaybackReporterTest; the call sites only through PlayerInvariantsTest. Bugs: #601, #674, #868, #869, #870, #890, #909: seven of the eleven above.
  • Decision: a service in application, the playback reports (the reporter as it is, with a stream value of our own instead of PlayerItem, a missing duration as null instead of C.TIME_UNSET, logging through a port). The stop’s position and percentage (playbackStopReport) and the start gate become rules in domain. Hilt provides it unscoped in player/local/.../di/, as today. It stays a main-thread class: it reads the player before it launches, records each start’s job on the snapshot before it waits (the progress gate and the stop’s wait read it), sends in reportScope, and catches every exception there but cancellation (see “How a use case is shaped”). What stays in the view model: telling the service what happened, and reading the player’s position for it (ReportedPlayer). Cast shares the stop rule only: its position and percentage (Cast clamps to 0..100, the local player does not: an input). Cast’s gate is a different rule (the receiver plays the current item and no load is pending), decided from the receiver’s status updates and a clock, and stays Cast’s. Its other differences (no position on the start, no PlaybackEvents) stay until their own fix (Q6).

P4. Switching quality, audio and version (the reload at a position).

  • Where: StreamSwitches (204 lines: selectBitrate, followBitrate, playingAt, selectAudio), QueueRebuild; VM switchTranscodeAudio (2064 to 2084), swapInQueue (2092 to 2114), selectMaxBitrate and the network quality (2135 to 2172), the host (2178 to 2234). Cast: setAudioTrack (1007 to 1074) reloads the current item at its position with its own cancellation. A version is chosen only at the start, on both players.
  • Depends on: a scope, PlayerItem, UiText for the failure text, P1, P2, the stored cap.
  • Needed by: the local player; Cast for audio.
  • Tests: StreamSwitchesTest, QueueRebuildTest, MpvPlaylistLoadTest. Bugs: #723, #726, #580, #837, #870 and #890 (both triggered by a switch).
  • Decision: a service in application, the stream switches, over P1 and P2: the newest switch wins, a failure undoes its own change and comes back as a result with the ServerException; the view model turns it into a text. The reload itself (setMediaItems at the position, prepare, playWhenReady) stays in the view model, because it is the engine’s. Cast’s audio switch joins it after P3’s Cast step.

P5. Segments and skipping.

  • Where: SegmentTracker (167 lines, already pure), segmentTrackerFrom (reads AppPreferences); VM updateCurrentSegment (1013 to 1078), getSegments (2236 to 2249), skipSegment and skipTo (2323 to 2345), skipButtonText (2347 to 2359). Cast: CastSegmentSkipper wraps the same tracker with guards of its own for receiver positions.
  • Depends on: the settings (#969), the item’s duration and whether a next item exists.
  • Needed by: the local player, Cast.
  • Tests: SegmentTrackerTest, CastSegmentSkipperTest, CastViewModelSegmentTest. Bugs: #271, #298, #616, #681, #851.
  • Decision: already a rule; it moves to domain as it is. The decision about what an automatic outro skip does (the sleep timer, the up next card, autoplay off: VM 1042 to 1076) joins P7. The skip label stays in the view models (it is a string resource).

P6. Track choice and remembered preferences.

  • Where: SeriesTrackPreference.kt (matchSeriesTrack, seriesTrackChoice, audioStreamIndex, serverAudioTracks), TrackPicks.kt (SessionTrackPicks); in PlaylistManager withChosenAudio, preferredAudio, savedAudioChoice (596 to 662); VM rememberTrackChoice (1804 to 1850), onTracksChanged (1852 to 1913), seriesTrackPreferences (1967 to 1995), trackChoices and switchToTrack (2001 to 2057). Cast starts with the server’s default tracks and does not apply the remembered choice.
  • Depends on: MediaRepository (saveSeriesTrackPreference, getSeriesTrackPreferences, getUserId), the preferred audio language, media3’s track type numbers (TrackPick.trackType is a media3 C.TRACK_TYPE_* value).
  • Needed by: the local player; Cast (not today).
  • Tests: SeriesTrackPreferenceTest, SessionTrackPicksTest, PlaylistManagerAudioChoiceTest; the order of apply, reset and read in onTracksChanged has no test. Bugs: #296, #580, #596, #597.
  • Decision: a service in application, the track preferences: given an item (series or not) and the candidate tracks per kind, which one to select; given a pick, what to remember and where. Our own kind of track (audio, subtitle) instead of media3’s numbers. Matching media3’s track groups to candidates, and building TrackSelectionOverrides, stays in the view model.

P7. The end of an item: autoplay, up next, still watching, the sleep timer.

  • Where: the pieces are pure and tested: AutoPlayNext, EndOfItem (imports media3’s Player), UpNextCountdown, StillWatchingTracker, SleepTimer. Their order is only in the VM: onPlayWhenReadyChanged (1225 to 1282: the sleep timer, then a cancelled up next card, then autoplay off, then still watching), advanceOrAskStillWatching (1288 to 1307), updateUpNext (1314 to 1362), autoAdvanceToNextItem and endItemWithoutAdvancing (1392 to 1422), the prompt and the timer (1424 to 1535), the outro auto-skip branch (1042 to 1076) and onPositionDiscontinuity (2502 to 2523).

  • Depends on: the clock (System.currentTimeMillis, SystemClock.elapsedRealtime), the settings, the server’s autoplay setting.

  • Needed by: the local player (phone, TV). Cast ignores autoplay today.

  • Tests: each piece has one (AutoPlayNextTest, EndOfItemTest, UpNextCountdownTest, StillWatchingTrackerTest, SleepTimerTest); the order has none. Bugs: #272, #298, #477, #616, #677.

  • How the code runs today, which the rule must keep:

    • The autoplay value is a Deferred that may wait for the server. It is awaited only on the branch that needs it (VM 1260 to 1270: a next item exists, the sleep timer does not stop here, the up next card was not cancelled), and the item is checked again after the wait: the user may have moved on.
    • StillWatchingTracker.onAutoAdvance changes its counters (VM 1294). It runs only when an advance is reached, and decides there whether to ask.
    • There are two clocks: wall time for still watching (1294, 1331, 1443, 1534) and elapsedRealtime for the sleep timer and the prompt’s deadline (1426, 1461 to 1481).
  • Decision: a rule in domain, the end of an item, in steps. The first step takes what is known at once (a next item, the sleep timer at the end of the item, the up next card cancelled) and returns one of: stay paused for the timer, end without advancing, the last item (the normal path to STATE_ENDED), or “needs autoplay”. The view model awaits autoplay only then, checks the item again, and calls the second step with it. That step returns end without advancing, or advance. The view model then calls the still watching tracker as it does now, which decides between asking and advancing. So a slow server never holds up the sleep timer’s end, and an advance that is not reached is not counted. The outro auto-skip (VM 1042 to 1076) uses the same steps; times come in as parameters, one per clock. The view model carries each result out. This is the largest untested rule in the view model, and PR 11’s table tests exactly these steps.

  • Done in PR 11: EndOfItemSteps in dev.jdtech.jellyfin.domain.playback.rule, with no caller. It takes the view model’s SleepTimer, UpNextCountdown and StillWatchingTracker and the prompt’s timeout. The outro skip does not use the same steps as the end of an item, contrary to the decision above: today it fires the sleep timer without remembering the item, runs the up next update in between, checks no item after its waits and never asks the still watching tracker. So it has steps of its own. updateUpNext awaits autoplay on every tick, not only on the branch that needs it. The steps, and what the view model does with each result:

    • The end of an item: atEnd(item, hasNext) returns SleepTimerStops(item) (fire the timer, remember the item, report progress), EndWithoutAdvancing, LastItem (autoAdvanceToNextItem with no next item) or NeedsAutoPlay(item). After the wait, afterAutoPlay(ended, current, autoPlay) returns ItemLeft, EndWithoutAdvancing or GoOn. GoOn and the countdown’s Advance call advance(hasNext, wallNow, monotonicNow), which returns AskStillWatching(promptEndsAt) or Next.
    • The prompt confirmed: confirmStillWatching(hasNext, wallNow), true to advance.
    • The card: upNext(facts, autoPlay, wallNow), with autoplay awaited first, returns UpNextDecision.
    • The outro skip: atOutroSkip(target) returns Skip(target), SleepTimerStops or UpdateUpNextFirst. After the card, afterOutroUpNext(card, current) returns CountdownTakesOver, Skip(EndItem) or NeedsAutoPlay, and then outroTarget(autoPlay).
    • Play after the sleep timer stopped at the end: resumeAfterSleepTimer(ended, current, position, duration, hasNext), true to advance.

    Today’s order, one test per row in EndOfItemStepsTest (the row is the start of the test’s name). “Wait” is the autoplay Deferred; “wall” and “mono” are the two clocks.

    Row Where When Today
    E1 end of item sleep timer set to the end of the item, next item the timer fires, the item is remembered; no wait
    E2 end of item the timer fired earlier (holds autoplay), last item the same: the timer comes first, last item too
    E3 end of item timer and a cancelled card the timer
    E4 end of item card cancelled for this item, next item end without advancing; no wait
    E5 end of item card cancelled for another item wait
    E6 end of item card cancelled, last item the last item’s path
    E7 end of item last item the last item’s path; nothing counted, no wait
    E8 end of item next item wait, for the item that ended
    E9 after the wait same item, autoplay off end without advancing
    E10 after the wait same item, autoplay on advance
    E11 after the wait another item plays now (slow answer) nothing, whatever autoplay says
    E12 after the wait timer set to the end of the item during the wait advance anyway (looks wrong)
    E13 advance next item, below both thresholds next; one advance counted
    E14 advance next item, count threshold reached pause, stop report, prompt until mono + timeout
    E15 advance inactivity reached on wall (a slow answer) prompt; the deadline on mono
    E16 advance no next item any more next (a seek that does nothing); nothing counted
    C1 prompt confirmed next item the tracker starts again at wall; advance
    C2 prompt confirmed no next item nothing
    U1 card episode, next item, in the window, autoplay count down
    U2 card autoplay off shown, no countdown
    U3 card not an episode hidden
    U4 card no next item in the queue or in the player hidden
    U5 card player idle or ended hidden
    U6 card the sleep timer takes the end hidden
    U7 card the prompt on screen hidden
    U8 card autoplay, prompt due at the next advance (wall) hidden; nothing counted
    U9 card autoplay off, prompt due shown, no countdown
    U10 card duration unknown hidden
    U11 card countdown runs out in an outro advance once, through the prompt; hidden after
    O1 outro skip a skip to a position at once, whatever the timer
    O2 outro skip to the next item, the timer takes the end the timer fires; nothing remembered
    O3 outro skip to the next item the card first (with its wait)
    O4 outro skip the card counts down the countdown takes over
    O5 outro skip card without countdown, not cancelled wait; autoplay off: end the item
    O6 outro skip card cancelled end the item
    O7 outro skip card hidden because the prompt is due, autoplay on wait; skip to the next item, unasked (looks wrong)
    O8 outro skip the countdown ran out at this tick wait; skip again (looks wrong)
    O9 outro skip after the wait autoplay on: the next item; off: end the item
    S1 play after the timer same item, within 2 s of the end, next item advance; autoplay not read
    S2 play after the timer seeked back more than 2 s play on
    S3 play after the timer another item play on
    S4 play after the timer last item play on
    S5 play after the timer duration unknown play on

P8. Resume position rules.

  • Where: PlayState, PlayStop and ResumeThresholds in domain (#637), applied in MediaRepositoryImpl.postPlaybackStop; PlayingSnapshot’s unknown duration (#461); the start position (VM 755 to 760, PlaylistManager 253 to 255); the engine’s last position on mpv (#869).
  • Decision: already done for what is stored (ADR 0002, R14). The start position moves with P2. The engine’s position stays in the engine.

Not use cases, and why. The network wait during playback (NetworkRecovery is already a tested rule; the ConnectivityManager callback in VM 1583 to 1671 goes behind a port in #969 or #998). Trickplay, chapters, the subtitle sync sheet’s cues and the display refresh rate: screen or engine work, without a rule another flow needs. The media session and PlaybackService: Android.

D1. The life of one download.

  • Where: DownloadQueue.EntryState (86 to 96: Pending, Downloading, Paused, Completed, Failed) and the flags on Entry (98 to 145: retryCount, retryAt, waitingForNetwork, retryWhenServerReturns); the transitions in the pump (551 to 820), afterFailure (989 to 1002), retry (448 to 497), remove (399 to 445), restore (281 to 342); the engine’s DownloadStatus numbers on an in-memory task; a second DownloadStatus enum for the screens (DownloadProgress.kt); DownloadState from the row’s type and path; the finalize in DownloaderImpl (1182 to 1444).
  • Persisted today: a pending_downloads row (queued); a LOCAL source with the partial suffix and a downloadId (started, not finished); the final path and downloadedAt (finished). Room (version 21) cannot tell running, paused, failed and finalizing apart.
  • Depends on: System.currentTimeMillis, System.nanoTime, delay, a hard-coded Dispatchers.IO scope (DownloadQueue 158), Context (the pump service, notifications).
  • Tests: DownloadQueue*Test (cancel, finalize, HTTP error, network, retry transition, server return), DownloadFinalizeFailureTest, SubtitleFinalizeTest, all on Robolectric. Bugs: #383, #426, #530, #560, #573, #848, #912.
  • Decision: a state machine in domain (below), with the queue as the only caller and the engine and DownloaderImpl doing what its effects say.

D2. The queue.

  • Where: DownloadQueue: order (sort, 517 to 529), slots (maxConcurrentDownloads, a paused download keeps its slot, 785 to 790), the network (the queue checks only online, 783 and 858; the engine checks metered and roaming, shouldPauseTransfer), retry and backoff (three retries, 30 s, 2 min, 10 min, afterFailure), the server’s return (#912), the restore after process death, deduplication by item id (#718), the pump’s poll interval (DownloadSpeed).
  • Decision: a service in application, the download queue, over the store role of #967, the Downloader port (reshaped first, in PR 5: it lived in downloads and returned UiText from settings and the engine’s int status), DownloadSettings, NetworkConnectivity and ServerAvailability, with its scope, its dispatcher and its two clocks injected (wall time for addedAt and retryAt, which are compared with stored rows; a monotonic clock for the #912 guard). The choice of what starts next is a rule in domain. The pump service, the failure notification and the texts go behind small ports implemented in downloads. The metered and roaming rule becomes one function in domain that the engine calls, so there is one network rule; who applies it does not change.

D3. The engine. MediaDownloadEngine: OkHttp, Range and If-Range (#850), pausing on a network the settings forbid. Decision: stays an adapter, doing I/O only; it reports running, paused, progress, succeeded and failed (with the HTTP status), which become the machine’s events.

D4. DownloaderImpl. Pure rules inside an I/O class: the orphan sweep (76 to 147), the paths (1481 to 1510), which subtitles are downloaded (683 to 685, again 830 to 843), progress as a percentage (written twice, 594 to 652). Decision: the rules go to domain; the class stays the adapter that writes rows and files. The order of the finalize (rename, write the row, undo the rename when the write fails, the subtitles of #573) becomes the effects of the machine’s finalizing stage; the file operations stay here.

D5. Smart downloads. SmartDownloadPlanner is pure and tested (SmartDownloadPlannerTest). Already done; it moves to domain with the package pass.

The table below is today’s behaviour, read from DownloadQueue and DownloaderImpl on main at 41de995ad, including the paths that look odd. The machine reproduces it row by row. A row whose “Pinned by” cell says none has no test today: PR 1 adds a characterisation test for it against the current code, before the machine replaces anything. A change to a row is a fix PR with its own issue, never part of a move.

Stages (one sealed type in domain). Every stage carries the facts of the download itself: the item, the quality asked for, whether Smart Downloads queued it, addedAt, and retryCount, which goes along through Running, Paused and Failed so that an engine failure can count the retries (as Entry.retryCount does today).

  • Queued (retryAt, waitingForNetwork, starting): waits for a slot; starting while the downloader sets the download up. Today’s Pending.
  • Running (downloadId, progress, bytes, speed): the engine transfers. Today’s Downloading.
  • Paused (downloadId): the engine stopped for a network the settings forbid; keeps its slot.
  • Finalizing (downloadId): the engine finished and the downloader renames and writes the rows. It lasts from the poll that sees the engine succeed until that poll publishes, so no screen sees it today: it exists in the machine to name the finalize’s outcome.
  • Finished: finished in this process. Today’s Completed. A download finished in an earlier process is not in the queue at all (restoreAll loads active and pending downloads only).
  • Failed (reason, resumesWhenServerReturns): waits for the user, or for the server when flagged. The flag is decided as today, not derived from the reason (rows 10 and 21).

The reason carries everything the queue shows today, so the screens show the same after the move: not enough storage, with the size needed and the space free (DownloaderImpl 334 to 341); storage unavailable (319); no sources (461); a start error with its exception, which texts.startError turns into words (1027); the server refused, with the HTTP status (DownloadQueue.serverRefused); the generic downloading error (a finalize that failed, a downloadItem that threw); and no text at all (an engine failure without a status). The texts themselves stay outside domain.

What the stage does not decide: DownloadState. The item buttons read DownloadState from the rows, next to the queue’s entry for the same item. The two do not follow each other: a Queued download with only a pending row has no LOCAL source, so its DownloadState is NONE; so is a Failed one whose fresh start failed. A Queued download after an engine failure, or a Failed one after a failed resume or a failed finalize, has a partial row and is DOWNLOADING. A Finished one is FINISHED. The machine does not change DownloadState or the rows that make it.

# From Event To Effects Pinned by
1 (none) Enqueue (also enqueueAll) Queued (addedAt now; enqueueAll adds one per item, in order) save the pending row DownloadQueueCharacterisationTest
2 Failed or Finished Enqueue of the same item Queued, fresh (new quality, counters at 0) save the pending row DownloadQueueCharacterisationTest
3 Queued, Running, Paused or Finalizing, queued by Smart Downloads Enqueue by the user same stage, no longer Smart Downloads’ clearSmartQueued on the rows DownloadQueueCharacterisationTest
4 Queued, Running, Paused or Finalizing any other Enqueue unchanged none DownloadQueueCharacterisationTest
5 Queued, not starting, retryAt passed, online, a slot free (Running and Paused count) Start Queued (starting, with an attempt id of its own, #1003) call the downloader; the pending row stays until the start succeeds (#1002) partly: DownloadQueueNetworkTest, DownloadQueuePendingPersistenceTest
6 Queued (starting) Started (a download id) Running (startedAt now) delete the pending row (#1002) DownloadQueueFinalizeTest, DownloadQueueHttpErrorTest (as setup), DownloadQueuePendingPersistenceTest
7 (none: removed while starting) Started (a download id) (none) cancel that download: the engine task, and the source of that id DownloadQueueCharacterisationTest, DownloadQueueCancelTest
8 any stage but Queued with this attempt: Queued, not starting or with an attempt of its own (removed and queued again while the old start ran) Started of the old start unchanged: the start belongs to an attempt that is gone, and the new entry starts on its own (#1003, fixed in #1040) cancel the old start’s download, as row 7 DownloadQueueCancelTest, DownloadQueuePendingPersistenceTest
9 Queued (starting) StartFailed, offline now Queued (waitingForNetwork), retries not counted save the pending row again DownloadQueueNetworkTest
10 Queued (starting) StartFailed, online Failed (the downloader’s reason, or the downloading error when it threw), resumesWhenServerReturns set whatever the reason none from the queue. What the downloader left: the fresh branch deleted what it wrote (DownloaderImpl 413 to 436); a failed resume keeps its partial row and file (272 to 277); the early returns wrote nothing. The pending row stays (#1002, fixed in #1044), so a restart queues it again DownloadQueueNetworkTest, DownloadQueueServerReturnTest, DownloadQueuePendingPersistenceTest
11 Queued NetworkChanged Queued (waitingForNetwork follows) none DownloadQueueNetworkTest
12 Running EnginePaused Paused none DownloadQueueCharacterisationTest
13 Paused EngineRunning (or the engine’s pending) Running none DownloadQueueCharacterisationTest
14 Running or Paused EngineProgress same publish progress, bytes, speed (an estimated size for a transcode) DownloadSpeedTest, DownloadQueueCharacterisationTest
15 Running or Paused the engine has no task for the id as row 19 to 21, with no status as there DownloadQueueCharacterisationTest
16 Running or Paused EngineSucceeded Finalizing finalize DownloadQueueFinalizeTest
17 Finalizing Finalized Finished, progress 100 publish a data change (#251) DownloadQueueFinalizeTest
18 Finalizing FinalizeFailed (false, or it threw) Failed (the downloading error), no auto-retry, not resumed when the server returns the failure notice; the partial file and row stay (#848) DownloadQueueFinalizeTest, DownloadQueueCharacterisationTest
19 Running or Paused EngineFailed, not permanent, fewer than 3 retries Queued (retryCount + 1, retryAt now + 30 s, 2 min, 10 min), never published as Failed (#560) save the pending row; the partial file and row stay DownloadQueueRetryTransitionTest, DownloadQueueHttpErrorTest
20 Running or Paused EngineFailed, permanent (a 4xx but 408 and 429, #383) Failed (server refused, with the status), not flagged the failure notice DownloadQueueHttpErrorTest, DownloadQueueServerReturnTest
21 Running or Paused EngineFailed, retries used up Failed (server refused when it had a status, else no text); flagged only without a text the failure notice; no pending row is saved DownloadQueueRetryTransitionTest, DownloadQueueCharacterisationTest
22 Failed by row 21 in this poll, flagged the server was confirmed after the poll began Queued, as row 24 as row 24 DownloadQueueCharacterisationTest
23 Failed Retry Queued (counters at 0, addedAt now) save the pending row DownloadQueueHttpErrorTest, DownloadQueueFinalizeTest
24 Failed, flagged ServerConfirmed Queued (retry count at 0, original addedAt kept, #1124) save the pending row with the queue timestamp DownloadTransitionTest, DownloadQueueServerReturnTest, DownloadQueueCharacterisationTest
25 Failed, not flagged ServerConfirmed unchanged none DownloadQueueServerReturnTest
26 Queued, Running, Paused or Failed Remove (none) delete the pending row; for every unfinished download id (the entry’s, and those on its partial rows, #426) cancel the engine task and delete the source of that id DownloadQueueCancelTest, DownloadQueueHttpErrorTest, DownloadQueueServerReturnTest
27 Finalizing Remove (none) as row 26: the source of that id is deleted, partial or final. The finalize’s late result is dropped. A rename that lands between the two leaves a final file without a row, which the orphan sweep deletes after a day DownloadQueueCharacterisationTest
28 Finished Remove, or clearCompleted (none) a Remove deletes the pending row (there is none); otherwise none: the entry leaves the list, the files stay. Deleting a finished download is Downloader.deleteItem, called by the view models, outside the machine DownloadQueueCharacterisationTest
29 (process start) Restored from a partial row with no engine task, item found in Room Queued with an addedAt supplied by the queue to sort ahead of restored pending rows (#1098). The entry keeps its download id for the resume (#1109) none; its pending row, if any, is skipped DownloadTransitionTest, DownloadQueueCancelTest, DownloadQueuePendingPersistenceTest; the order: DownloadQueueCharacterisationTest
30 (process start) Restored from a pending row whose item resolves Queued (addedAt from the row) none DownloadQueueCharacterisationTest
31 (process start) a pending row whose item does not resolve not in the queue the row stays for 30 days from its last write; a kind other than movie or episode is dropped at once PendingDownloadRestoreTest
32 (process start) a partial row whose file was renamed before the stop (#848) not in the queue the downloader finishes the finalize inside the restore; when that fails the row stays for the next start and is never resumed (the partial file is gone) DownloadFinalizeFailureTest
33 (none), or Failed or Finished restore(item, downloadId) from a detail screen of an item still downloading Running with that id and no engine task; the next poll goes on by row 15 none DownloadQueueCharacterisationTest

Every other pair is not legal: the state stays as it is, there are no effects, and the queue logs it. Row 22 is not such a case: today it re-applies a confirmation that arrived while the poll was still deciding (DownloadQueue 760 to 768, lastServerConfirmedAt against polledAt, a monotonic clock). The machine keeps it as an event of its own, with the confirmation’s time.

What PR 2 found. The machine follows the code where it differs from the cells as first written; none of these is a change of behaviour:

  • Starting the pump is not an effect. The queue starts it after every enqueue, retry, remove and restore, not only in row 1, and the pump runs while a stage is work (DownloadStage.isWork).
  • A download that is finalizing is live for an enqueue (rows 3 and 4): today it is still Downloading while the poll finalizes it.
  • A start whose attempt is gone cancels its download at any stage (rows 7 and 8): the queue looks for the attempt, not for a stage.
  • Every remove deletes the pending row, also of a finished download and of an item the queue does not hold (row 28 and remove on no stage).
  • A restore of an item the queue already holds is skipped (rows 29 and 30), and restore(item, downloadId) of a live download is left alone (row 33): both legal, without effects.
  • An engine status the stage already has (running while Running, paused while Paused) is a progress report, row 14. A change of stage clears the speed, as the poll does today.
  • Row 5’s online and free slot are the queue’s choice before it sends Start; the machine checks the stage, the attempt and retryAt. Rows 31 and 32 send no event: the queue never sees them.
  • Row 29 initially kept the old order so PR 3 could preserve behaviour. The fix for #1098 gives partial downloads priority over restored pending rows. The queue uses one millisecond before the earlier of the restore time and the oldest pending timestamp, with a stable sort for ties.

What PR 3 found. The queue decides through the machine; none of these changes what it does:

  • The entries stay what the queue stores, and the stage is made from an entry before each event (Entry.toStage), then the entry from the new stage (toEntry). The stages cannot be the store yet: PR 1’s tests put an entry in the list directly (seed), and the screens read Entry until PR 7. PR 6 can make the stage the store.
  • A failed entry’s reason is not read back from its text. No event changes a Failed stage in place: it stays as it is (the entry and its text are kept) or leaves Failed.
  • The downloader still returns a text, not a reason, until PR 5. A start that fails (row 10) shows the downloader’s text, and its event carries the downloading error when downloadItem threw, else no reason.
  • A queued download keeps the byte counts it had, as today: the stage has none, so toEntry keeps them from the entry before, and takes a transfer’s numbers only from the engine’s report. The screens show bytes only while a download runs; after a start, the next poll replaces them.
  • restoreAll and enqueueAll decide each row or item against the queue as it was before the call, as the code did: two partial rows of one item both come back, as before.
  • DownloadQueue.afterFailure stays for the tests that call it, as a wrapper over rows 19 to 21. The engine’s copy of isPermanentHttpFailure is gone: only the queue used it.
  • A pair that is not legal is logged as a warning, except for the events sent to every entry (NetworkChanged, ServerConfirmed, ServerConfirmedDuringPoll, ClearFinished), which apply to some stages only.

What PR 4 found. The clocks, dispatcher and scope are injected; nothing the queue does changed:

  • The queue is not in application yet (PR 6), so Hilt builds it with a @Provides in DownloaderModule, which passes each value, instead of an @Inject constructor. The constructor keeps defaults for the four new parameters, so DownloadTrickplayRestartTest, which runs a real engine in real time, builds it as before.
  • The clocks are two () -> Long parameters, wallClock and monotonicClock (ns). Every coroutine the queue launches runs on the injected dispatcher inside the injected scope, as the old scope ran on Dispatchers.IO.
  • The queue never started a download before its retryAt, for two reasons: its own filter, and the machine’s check of row 5. A test that drops only the filter still passes.
  • PR 1’s tests reached the used-up retries of rows 21 and 22 by writing the queue’s list through reflection. They now run the 12.5 minutes of backoff in virtual time, so their counts of starts and saved rows are taken after the retries, just before the last attempt fails. The assertions are the same.
  • On the test’s scope an exception that escapes a queue coroutine fails the test. One fake answered a remove’s read of the source rows with NotImplementedError, which is an Error, not an Exception: the remove’s coroutine ended there unseen, after the entry was gone. The fake now answers with no rows. The production code does the same as before.
  • With one thread and virtual time, the race in a download queued as the last one finishes finds the pump active (an enqueue at the moment the pump exits) no longer happens in different orders across its rounds. The mutex still decides that race; the test now checks the order in which it runs.
  • R26 does not land here. It does not pass today, contrary to what “New architecture rules” says: MediaRepositoryImpl in application calls withContext(Dispatchers.IO) in most of its operations and reads System.currentTimeMillis() and LocalDateTime.now() itself, and ExternalRatingsService and ReloadPolicy default to System::currentTimeMillis (allowed, as a constructor default). The rule waits for a change that injects the repository’s dispatcher and clock, or for an allowlist entry with its own issue. #1104 did the first, and R26 landed with it.

What PR 5 found. The port speaks our types; what the queue shows and does is the same:

  • The failure reason needed no new type. DownloadFailure from PR 2 already names every reason the downloader gives (not enough storage with both sizes, storage unavailable, no sources, a start error with its exception), so DownloadStart.Failed carries one. A start that fails now hands the machine the downloader’s reason, where PR 3 handed it none. Row 10 sets the flag whatever the reason, so the machine decides as before.
  • The words moved from DownloaderImpl to the queue, into one function for every reason (DownloadTexts.failureText, with the server’s refusal of #383 that the queue already made). The queue formats the two sizes of “not enough storage” with the same Formatter.formatFileSize, over the application’s context as DownloaderImpl did.
  • The engine keeps its int DownloadStatus: DownloaderImpl maps it to EngineStatus at the port. The queue used to read a number the engine does not have as failed with no HTTP status, and the mapping now does the same. The int type stays for the screens until PR 7.
  • Row 15 still does not happen in the app: DownloaderImpl’s batched getProgress reports an id the engine does not know as failed, so it arrives as row 19 to 21 with no status, which the table treats the same. FakeDownloader does the same for an id no start returned (engineKnowsStartedIdsOnly). DownloadQueueCharacterisationTest leaves such an id out in a subclass, so the queue’s row 15 is still tested there.
  • One FakeDownloader in testing replaces the queue tests’ private fakes, with each test’s behaviour set in its fields or in a small subclass. DownloadQueueMachineReviewTest keeps its own, with only the types changed, because #1106 changes that test at the same time.
  • UiText.StringResource has no equality of its own. A test that compared the downloader’s text instance with the one shown now compares the resource id.
  • No build file changed and no rule was added: testing already depended on application.
  • A hard kill of the whole device (here, the emulator’s process) a few seconds after a finish can lose the last Room writes: once the row update of the finalize (row 32’s state, which the restore then finished, on main and on this branch), once every row of the item, leaving a final file without a row, and once the file’s data too (a final file of 0 bytes). Killing only the app right after a finish lost nothing. A power loss right after a finish could do the same. No row of the table covers a file left with no row at all at a start; the orphan sweep is left to delete it, as in row 27.

What PR 6 found. The queue is a service of application; what it shows and does is the same:

  • EntryState.Failed holds a DownloadText of application, not a UiText, which application cannot name. The screens already read the queue through DownloadEntry, which held a DownloadText, so they show the same. DownloadText.Resource is equal by value and UiText.StringResource was not, so an otherwise equal list with a new text instance no longer makes entries emit again. queueEntries already compared that way.
  • There is no log port for all of application yet (Q5). RepositoryLog is the repository’s and has no info level, so the queue has its own, DownloadQueueLog, with the three levels it writes (info, warn, error). Q5 can fold it into the shared port. Timber names a line’s tag after the class that logs it, so the adapter, TimberDownloadQueueLog, sets the tag DownloadQueue itself. Without it, the queue’s lines in logcat would have a new tag.
  • Three more files moved with the queue because it needs them and application cannot reach downloads. The speed sample (DownloadSpeed.kt) went to the service package with its test. The service’s notice (DownloadPumpNotice.kt) went there too, because DownloadQueueRetryTransitionTest tests it. estimateCappedDownloadSize went to dev.jdtech.jellyfin.domain.downloads.rule, because DownloaderImpl uses it as well. TestDownloadSettings went to testing, because the tests of both modules use it.
  • The rule nextDownloads reads the queue as one snapshot and reads the wall clock on every round. The pump used to read the list twice and the clock only when a slot was free and the device online. A clock read has no effect. The list could change between the two reads before as well, and each start still finds its entry again under the mutex and asks the machine (row 5), as it did. A finalizing download holds a slot in the rule, as Running does; the queue never stores that stage.
  • The entries are still the store. PR 3 said PR 6 could make the stages the store, but DownloadQueueMachineReviewTest still writes the list by reflection and downloads still reads Entry, so this waits for PR 7.
  • The tests changed only where Android was. The fake DAO under RoomDownloadStore became a fake of the DownloadSources port (queueSources), so a Smart Downloads claim is one clearSmartQueued call instead of the two DAO calls the store makes for it. RoomDownloadStoreQueueCallsTest in data now checks those two calls and the source rows a remove reads. The notices are recorded by item; DownloadQueueAndroidTest in downloads checks the notification’s text (“Show · S01E01”) and the words with their formatted sizes. SQLiteFullException in a finalize became an IllegalStateException: the queue catches any Exception. The resource id of a refusal is the test texts’ own. The real one is checked in DownloadFailureTextTest and DownloadQueueAndroidTest.
  • The restore mapping moved without a change: restoreAll, toStage and toEntry are the same code in the new package.

What PR 7 found. The screens read the stage; what they show is the same:

  • Row 7 of “The order of the PRs” named NavigationRoot as a reader of EntryState. Its EntryState is a class of its own, the saveable state of the navigation entries; no screen shows a download through it, and it was left alone.
  • There was a third type: the port’s DownloadEntryState, the copy of EntryState that DownloadQueuePort published. It went too; DownloadEntry carries the view.
  • The stage does not hold everything the queue shows. The item, the words of a failure, the download id a retry resumes (#1109) and the numbers on screen stay on DownloadQueue.Entry next to the stage. The numbers keep the rules of PR 3: a requeued download keeps its bytes and total with no percentage or speed, and a start shows the numbers from before until the engine reports.
  • The view keeps “waiting for the network” apart from queued, because the screens did: the Downloads tab and the item page show it as paused, the season list as queued. The item page says “Pending…” for a queued download where the Downloads tab says “Waiting…”; the composable picks the words (downloadStageTextRes(stage, onItemPage)).
  • The engine’s int DownloadStatus was only read by DownloaderImpl, so the engine now reports EngineStatus itself. The mapping of an unknown number to failed is gone with it: there is no unknown number.
  • A failed stage now keeps its reason. toStage gave a failed entry none (reason = null), since EntryState.Failed held only the words. No rule reads the reason of a stored stage, so nothing the queue does changes.
  • Finalizing is still never stored; its view would be running, as the entry showed it.
  • An entry can no longer be running with a retry time left over from before its start. One test of DownloadQueueRetryTransitionTest built such an entry; it builds a running one with its retry count now.
  • The item page and the season list now see a change when only the waiting-for-network flag of a queued download changes, and map it to the same state, so the screen does not change.
  • app/tv reads none of these types. Its generated baseline profiles still name the deleted classes; they are regenerated with the next release build.
  • DownloadQueueMachineReviewTest still writes the list by reflection, now of entries that hold stages.

What PR 8 found. The rules left DownloaderImpl; what it keeps and deletes is the same:

  • The finalize did not become effects of the machine’s finalizing stage, as D4 says. The machine already names the whole finalize with one effect, Finalize(downloadId), and gets one answer back, Finalized or FinalizeFailed. What happens inside depends on how each file operation went: the rename, then the row’s write, then perhaps the rename back. So the order is a rule in steps of its own, FinalizeSteps.kt (sourceFinalize, afterSourceRename, afterSourceRowWrite, and the same for an external track), as P7 has EndOfItemSteps. DownloaderImpl reads the disk and the engine into FinalizeFacts, asks each step, and does the work. The machine did not change.
  • The two finalizes differ in ways the table keeps (FinalizeStepsTest, rows F1 to F8 and T1 to T9). A video renamed before a stop is recorded without a catch, so a failed write fails the finalize with its exception and nothing is renamed back (F2); after its own rename, a failed write is caught and renamed back (F7). A track the engine no longer knows (the repair at a start) is taken when its file has bytes, whatever the engine said (T5), and keeps its row when the rename fails (T8); one the engine knows loses its row (T7).
  • The facts are read before the first step. The finalize now checks both file names and asks the engine also for a row that already has its final name, and for a subtitle whose task is gone (the answer is then not used). The sweep checks the file of a row on a volume it cannot see, and whether it was renamed before a stop. These are reads; nothing else changed.
  • The progress was no longer written twice: PRs 5 and 7 had made one function of the two. Its status is the engine’s EngineStatus, a type of application, which domain cannot name, so transferPercent takes two booleans, succeeded and running.
  • The metered and roaming rule was already one function, shouldPauseTransfer in the engine’s file. It moved as it was, with its nine tests. The queue still checks only that the device is online; who applies which rule did not change.
  • The sweep’s choice for a source row whose file is gone was in the loop of sweepOrphans, not in the helpers. It moved too (isGoneFinishedSource, sweepActiveSource). The #848 repair’s check, renamedBeforeStop, stays in DownloaderImpl, because it asks the engine and the disk; the rule takes its answer. It counts the final name only when it is a file (isFile), where the finalize’s own check takes anything that exists with bytes (exists). The two were left as they are.
  • trickplaySheetCount is not named in step 8, but it is a rule of the same file, with a test of its own, so it moved with the rest.
  • The subtitle job of #573 stays in DownloaderImpl: which engine status counts as running or as failed, the job of up to 5 minutes, and the repair at a start read EngineStatus and the engine, as “Outside the machine” below says. Only the rename of one track is a rule (T rows).
  • Rules of DownloaderImpl that step 8 does not name stayed: the 30-day limit and the kinds of a pending row (getPendingDownloads), the choice of the partial row a resume takes (#1109), the other server’s copy (#718) and the choice of storage. They have Robolectric tests (PendingDownloadRestoreTest, ResumeOwnPartialTest, OtherServersCopyTest). DownloaderImpl is at 1493 lines, so the 1100 of “Done for #970” needs at least some of them moved.
  • Five pieces had no test of their own before the move: the extension of a stream URL, the name of a track’s file, which streams are downloaded as files of their own, the match a restart uses, and the percentage. A first commit pulled them out of the class into functions of the same file, unchanged, with tests; a second moved both. Four branches had no test either: a transfer the engine has not finished, a row that is already final, a track whose rename fails while the engine knows it, and a source row whose file is gone. DownloadFinalizeFailureTest and OrphanSweepTest pin them on Robolectric.

Outside the machine, on purpose: the external subtitles. They have their own life today (finalizeFinishedMediaStreams at the start of restoreAll, retryFailedMediaStreams every 30 s while a download is Running but not Paused, the finalize-later job of up to 5 min, #573), tested by SubtitleFinalizeTest. They stay with DownloaderImpl and the queue’s poll; the machine only knows the video. Also outside: the #848 repair of row 32 (the downloader’s, at restore) and the orphan sweep.

Room. No PR of this series changes the schema: what Room stores carries every stage that survives a restart today, and Failed, Paused and the retry counters are lost at process death today as well. Keeping Failed across a restart would change what the user sees after one, so it is its own decision (Q3) for a future schema version. The lost pending row of a start that failed (#1002) needed no schema change and was fixed on its own, in #1044. A fix outside the series did change it: #1124 (PR 1125, after PR 7) added schema 23, the pending row’s savedAt, for the 30-day cleanup of rows whose item does not resolve (row 31). PR 8 and the upgrade checks after it start from schema 23.

  • A rule is a top-level function, or a value with methods, in domain. It reads no clock and launches nothing: now is a parameter. It is tested with plain JUnit Jupiter tables.
  • A stateless use case is a class named by what it does (ResolvePlayback), with one public operation, usually suspend. It takes the ports it uses, and nothing else, in its constructor.
  • A service with state (the play queue, the reports, the switches, the download queue) is a small class whose public operations are the events of its flow (onItemTransition, retry). It exposes its state as a StateFlow of its own type, and a one-off outcome as a return value or a Flow of events. The view model turns that into the screen’s state and its Channel of events.
  • Threads. A player service holds its state without locks, as PlaybackReporter does today: it is called on the player’s (main) thread only, and reads the player there, before it launches anything. Only the port calls run on the injected dispatcher. runTest does not show a mistake here, so the KDoc of each service says which thread it is called on. The download queue keeps its mutex.
  • Scope, dispatcher, clocks. A service takes CoroutineScope only when its work must outlive the caller (a stop report outlives the player: today @ApplicationScope in PlaybackReporterModule); otherwise it suspends and the caller’s scope runs it. It takes a CoroutineDispatcher for blocking work, and one injected source per clock it reads: wall time where a time is stored or compared with stored times (the queue’s addedAt and retryAt), a monotonic clock where only an order matters (the #912 guard’s nanoTime, the sleep timer’s elapsedRealtime). Two clocks stay two parameters. In application defaults appear only in the constructor (as ProfileLock and PR 987 do: the production constructor passes Dispatchers.IO). Hilt does not use Kotlin default arguments on an @Inject constructor, so a @Provides passes each one. A test passes a StandardTestDispatcher, backgroundScope and testScheduler.currentTime, and runs under runTest with advanceUntilIdle(), with no real dispatcher left running.
  • Errors. A port throws ServerException for an I/O failure. A service catches it only where its rule says what happens then; otherwise it lets it through. A report is the exception to the exception: it runs on the application’s scope, where an uncaught exception crashes the app, and postPlaybackStop also writes Room, so a report catches every exception but CancellationException, as PlaybackReporter does today. A switch is undone and returns a failure that carries the exception. CancellationException is always rethrown. Texts for the user (LoadErrorText, switchFailureText, the download texts) are made outside application, from the exception or the reason.
  • Logging. application has no logger (R19). A service that logs takes the log port AppLog (debug, warn, error), implemented over Timber in core as TimberAppLog with the tag the lines had before (Q5; since PR 13, before which the repository had RepositoryLog and the stored fallback FallbackLog).
  • Hilt. application declares no Hilt annotation and no @Inject (R19: no library but kotlinx). A feature module provides each service with @Provides in its di/ package, as ExternalRatingsModule in core provides ExternalRatingsService: the player’s services in player/local/.../di/ (unscoped, one per player, as PlaybackReporter is now), the download queue in downloads/.../di/ as a @Singleton. Cast takes the same bindings, since player/cast depends on player/local.
  • Constraints. R5 and R19: a service in application imports only Kotlin, kotlinx, the JDK and our own code, so no media3, no Uri, no Parcelable, no PlayerItem, no UiText: it gets values of our own (ids, positions in milliseconds, a missing duration as null). R6: shared player code imports no engine package; the services cannot, because they are not in player/local at all. The Cast flavours: a service is compiled once in application and used from player/cast/src/proprietary and src/main; src/libre needs nothing new. Nothing in a service names a Cast type: the receiver is PlaybackTarget.CastReceiver of domain.

The two sketches below show the shape only (where a class lives, what it takes, what it returns). They are not compiled and are not the control flow: an implementer ports the current control flow of PlaybackReporter.sendPlaybackStart and of the table above, line by line, and does not start from the sketch.

// SHAPE ONLY. application, package dev.jdtech.jellyfin.application.playback.service
class PlaybackReports(
private val reports: PlaybackReportsRole, // the role of MediaRepository after #967
private val events: PlaybackEvents,
private val reportScope: CoroutineScope, // the application's: a stop outlives the player
private val io: CoroutineDispatcher,
private val log: AppLog,
) {
/** Main thread only, like everything here: the state below has no lock. */
suspend fun sendPlaybackStart(stream: QueuedStream, player: ReportedPlayer) {
val seq = transitionSeq
stopsInFlight.toList().joinAll() // #890: the stops go first
if (seq != transitionSeq || playing?.itemId != stream.itemId) return // re-checked after the wait
val positionTicks = player.positionTicks() // read here, on the main thread (#868)
val start = reportScope.launch(io) {
try { reports.start(stream.itemId, positionTicks, stream.transcoded) }
catch (e: CancellationException) { throw e }
catch (e: Exception) { log.error(e, "playback start") } // everything: this is the app's scope
}
playing = playing?.copy(startJob = start) // recorded before the wait: progress and stop read it
start.join()
}
}
// SHAPE ONLY. domain, package dev.jdtech.jellyfin.domain.downloads.rule
data class Transition(val stage: DownloadStage?, val effects: List<DownloadEffect>)
/** One row of the table per branch; a pair that is not in the table returns this unchanged. */
fun DownloadStage?.on(event: DownloadEvent, now: Long): Transition = when {
this is Queued && starting && event is Started -> Transition(Running(facts, event.downloadId, startedAt = now), emptyList())
this == null && event is Started -> Transition(null, listOf(CancelDownload(event.downloadId))) // row 7
(this is Running || this is Paused) && event is EngineFailed && event.retriesLeft(facts) ->
Transition(Queued(facts.retried(), retryAt = now + backoff(facts.retryCount)), listOf(SavePending)) // row 19
// … one branch per row
else -> Transition(this, emptyList())
}

One flow per PR, smallest and best tested first. The marks:

  • Player: changes code the running player executes. It runs docs/mpv-checklist.md on both backends, over http and https, and waits for the owner’s check on a real device before it merges.
  • Move: a pure move in player/* (Q4). It may merge on the emulator checklist on both backends without the owner’s device check, but only when it passes the mechanical test under Q4.
  • Cast: needs a real Cast receiver. Emulators find none, and the debug stand-in (FakeCast.kt) shows states but sends no reports. Such a PR is prepared and tested on the stand-in, and is not merged until the owner has run it on a receiver, as with the device check. An unattended run stops there and reports; it never merges on the stand-in.
  • Downloads: changes what the running download queue does or how it is built. It runs the downloads guide’s device checks: a download cut off by iptables and brought back, airplane mode, and a restart during a download.
  • Upgrade: touches what the queue restores. The previous build with downloads in every stage (queued, running, cut off, failed, finished, with external subtitles), the new build installed over it, and the database and the queue compared before and after.
  • None: tests or new code without a caller. Nothing that runs changes.
# PR What it does Must not change Tests it adds Marks
1 Characterisation tests of the queue a test against the current DownloadQueue and DownloaderImpl for every row marked “none” in the table any production file one per such row None. Done: DownloadQueueCharacterisationTest, PendingDownloadRestoreTest
2 Download machine in domain the stages, events, effects and the transition function; no caller anything one per row of the table, and that every other pair is unchanged None. Done: DownloadTransitionTest
3 The queue drives the machine the queue’s decisions go through the machine; Entry and EntryState stay as the published view, mapped from the stage the tests of PR 1 and the existing DownloadQueue*Test, unchanged none new: PR 1 and 2 hold it Downloads, Upgrade. Done, with R24
4 The queue’s clocks, dispatcher and scope injected wall time and a monotonic clock as two sources, the dispatcher and the scope as constructor parameters, bound in downloads/.../di/; the tests move from Thread.sleep to runTest behaviour backoff, the #912 guard and the server’s return in virtual time Downloads. Done; R26 landed later, with #1104
5 The Downloader port reshaped Downloader to application, with a start result and a failure reason of our own instead of Pair<Long, UiText?>, and an engine status of our own instead of the int DownloadStatus in Progress; DownloaderImpl, the fakes and the callers follow what is shown and done the port’s fakes in testing Downloads. Done
6 The queue to application the service, with ports for the pump service, the failure notice and the texts; the choice of what starts next as a domain rule behaviour; R15’s names the queue without Robolectric Downloads, Upgrade. Done
7 The screens read the stage the readers of EntryState (NavigationRoot, DownloaderViewModel, DownloadPumpNotice, SmartDownloads, EpisodeDownloadSelection, DownloadsViewModel, SeasonViewModel) and both DownloadStatus types (the engine’s and the screens’) replaced by the stage’s view; the old types deleted what the screens show the view models’ mapping Downloads. Done
8 DownloaderImpl’s rules to domain the sweep, the paths, the subtitle choice, the progress, the metered and roaming rule as one function the engine calls; the finalize as effects the files kept and deleted the sweep and finalize tables Downloads, Upgrade. Done; the finalize is steps of its own, not effects of the machine
9 True moves of player rules SegmentTracker, UpNextCountdown, StillWatchingTracker, SleepTimer, PlaybackStartGate, ReportedPause to domain, as renames anything but package and import lines none: their tests move with them Move. Done; matchSeriesTrack and seriesTrackChoice went to row 10
10 Player rules with changed call sites playbackStopReport and PlayingSnapshot with a missing duration as null instead of C.TIME_UNSET (PlaybackReporter 167 and 266); AutoPlayNext without settings.domain.Constants, through #969’s port; serverAudioTracks split from ServerAudioTrack of player/core, and with it matchSeriesTrack and seriesTrackChoice to domain (they share SeriesTrackPreference.kt with it); the KDoc links of SegmentTracker and UpNextCountdown to PlayerViewModel, which no longer resolve from domain (or in 13) behaviour the moved rules’ tests, adapted Player. Done; serverAudioTracks and audioStreamIndex stayed in player/local
11 The end of an item as a rule a domain rule in steps, no caller (see P7) anything a table of today’s order in onPlayWhenReadyChanged, updateUpNext and the outro skip, with a slow autoplay answer and both clocks None
12 The view model uses the end of an item VM 1042 to 1076 and 1225 to 1535 carry out the rule’s steps the order of the end of an item the view model’s part through 11 Player (the checklist’s playlist and autoplay lines)
13 The reports to application PlaybackReporter with a stream value of our own and a log port every report and its order; PlayerInvariantsTest the existing tests, under runTest Player. Done: ReportedStream, AppLog
14 Cast uses the shared stop rule CastPlaybackReporter takes the stop’s position and percentage from domain (Cast’s clamp to 0..100 as an input), and Cast’s three report calls go through the shared service; Cast’s own gate (the receiver plays the current item, no load pending) stays every Cast report Cast’s decider over the shared rule Cast
15 ResolvePlayback to application the use case, with a resolved stream of our own every request to the server without AppPreferences Player (a quality switch over https)
16 Track preferences to application PlaylistManager’s audio choice and the view model’s remembering and applying which tracks play the order of apply, reset and read Player (a series’ saved choice and a movie)
17 The play queue to application PlaylistManager’s queue and the start position the queue on both players the queue without the mapping Player, Cast
18 The stream switches to application StreamSwitches over 15 and 17 the newest switch wins; the reload the switches over fakes Player (the checklist’s switch and slow link lines), Cast. Cast’s switch stayed Cast’s; R27 landed

Without a receiver the series goes on past 14 with 15 and 16, and stops before 17. Rule R25 then does not land, and R27 waits as well.

Order around the other issues. #967, #966 and #969 run before this series, one at a time. So when PR 1 opens: MediaRepository and DownloadStore are split by role and every service here takes the roles it uses; MediaRepositoryImpl is in application, so the report requests are built there already; and the player settings port of #969 exists, before PR 9, which settles segmentTrackerFrom, AutoPlayNext’s Constants and ResolvePlayback’s AppPreferences. Should one of them still be open when a PR here opens, the files that PR moves are frozen for it until the PR merges: git does not carry an edit across a move to another module. #971 comes last, and finds the new code already in its packages (Q2).

Done for #970:

  • PlayerViewModel at most 1800 lines (from 2583), what is left being media3 wiring, the screen’s state, the subtitle sync sheet and trickplay; DownloadQueue gone from downloads, or only its Android shell (at most 150 lines); DownloaderImpl at most 1100 lines (from 1529). The ceilings are R24’s numbers.
  • Each of the ten flows above that becomes a rule or a service (P1 to P7, D1, D2, D4) has its tests in domain or application, with no Robolectric. Of the 11 rules in the table under “Context”, all but #869 (the mpv engine’s own) and #850 (the engine’s If-Range) are then in domain or application.
  • The download machine in domain, every row of its table tested, and the rows PR 1 found untested pinned before the move.
  • No playback rule exists twice: Cast uses the stop rule and the segment rule of domain; R25 holds.
  • Every player PR ran the mpv checklist on both backends over http and https.

R20 is taken by #965; R21, R22 and R23 are reserved for #967 (the port size), #966 and #969. This series takes R24 on. The numbers are those of the PR that lands a rule; rules.md is generated from the test names, so a number that changes before merge costs one rename. What a reviewer cannot check (“a view model holds no rule”) is replaced by what a test can:

  • R24: size ceilings. A list of the largest files (PlayerViewModel, CastPlayerControllerImpl, CastViewModel, DownloaderImpl, DownloadQueue) with a line ceiling each, in a file of its own under architecture/ (a list of ceilings, not a baseline). The test fails when a file grows past its ceiling. There is no lower bound, so a PR elsewhere that shrinks one of these files (#969, an upstream sync) does not have to touch the list; this series lowers the numbers in its own PRs. Kept because it is the only check that the view model stops growing back; moving code into an extension file to pass it is a review finding. Lands with PR 3.
  • R25: one sender of playback reports. Only the reports service calls the report operations (postPlaybackStart, postPlaybackProgress, postPlaybackStop, or the report role after #967), as R16 holds the server switch to one place. Kept because it is what makes “no rule twice” true for Cast and TV, and a call site is easy to find. Lands with PR 14, when Cast’s three calls go through the service (CastPlayerControllerImpl 505, 520 and 535 call them until then).
  • R26: no hidden time in the pure modules. domain names no clock and no Dispatchers; application names them only as a constructor parameter’s default. delay is fine: virtual time covers it. Kept because it is what lets every service run under runTest. Planned for PR 4, but it did not pass then: MediaRepositoryImpl named Dispatchers.IO and the clock itself (see “What PR 4 found”). #1104 gave the repository both as constructor parameters (no defaults; MediaRepositoryModule in core passes them) and landed the rule (HiddenTimeTest), with no baseline. The defaults it allows are ProfileLock’s dispatcher and the clocks of ExternalRatingsService and ReloadPolicy.
  • R27, deferred until after PR 18: the player’s rules import no media3. Mappers import media3 by their nature (isNewEndOfItem’s player constants, toPlayerItem with C and toUri), so the rule waits until what is left of the player’s domain package is either moved to domain or application, or is a mapper in a mapping package of player/local. The rule then says that no file of player/local outside engine, mapping, presentation and di imports media3. Landed with PR 18 (PlayerRulesMedia3Test), with an allowlist of one file: see “What PR 18 found”.
  • Dropped: a rule that “the download stages are declared in domain alone”. As a test it is a denylist of two names (EntryState, DownloadStatus), and PR 7 deletes both types, which is stronger than forbidding their names.
  • The running player. Every player PR can break playback on one backend and not the other (#267, #284). The checklist on both backends over http and https, the owner’s device check, and one flow per PR are the answer. PlayerInvariantsTest reads the view model’s source: a move that renames a call there fails it, which is the point; update the test with the call, never loosen it.
  • Cast without a receiver. PRs 14, 17 and 18 wait for one (see the marks); until then Cast keeps its own reporter and its own calls.
  • The download table is long, and an implementer follows it row by row. That is why PR 1 pins every row against the current code first: a row that is wrong here shows up as a failing characterisation test, not as a change of behaviour on a phone.
  • Upgrades. No schema change in this series (#1124 added schema 23 outside it, see “Room”), but the restore mapping moves (PRs 3, 6, 8). The upgrade check covers it; a mistake there loses downloads, not only state.
  • Two vocabularies during the series. Between PR 2 and PR 7 the queue publishes EntryState mapped from the stage; between PR 9 and PR 18 some rules are in domain and the services that use them are still in player/local. Each PR leaves the app working.
  • Not done: no rewrite of the player or of the download engine; no change of behaviour in a move; no use case per repository call; no new domain events; no schema change in a PR of this series (schema 23 came from #1124, a fix outside it); no change to Cast’s behaviour, in PR 14 either.

Found while reading, filed to reproduce first rather than fixed in a move (both fixed since):

  • #1002: a download whose start fails while online, with the server away, loses its pending row and is gone after a process death. Fixed in #1044.
  • #1003: a cancel and a new enqueue of the same item while a start runs attach the old engine task to the new entry (table row 8). Fixed in #1040.

Not filed:

  • Cast asks the server for every item twice, and once more for the chosen audio, and drops the series’ remembered audio.
  • Cast sends no PlaybackEvents.

Both wait for Q6. One more trap with no bug behind it: Segment.startTicks and endTicks hold milliseconds.

Each has a recommendation, decided by the overseer on 2026-11-25 where marked. If nobody answers, the series goes with it.

Question Recommendation, and the default
Q1 Shared services in application and rules in domain, or a new pure playback module application and domain. A new module would add a layer the rules do not need; application is already the pure place every feature depends on
Q2 Packages for the new code now, ahead of #971 Yes, in the scheme #971 asks for: by area, then by what a thing is. dev.jdtech.jellyfin.domain.<area>.model and .rule, dev.jdtech.jellyfin.application.<area>.port and .service, with playback and downloads as the areas. Moved code then needs no second move. Should #971 settle on other names, that PR renames these packages with the rest
Q3 Keep a failed download failed across a restart (keep the pending row until finished, with the stage and the retry count) Not in #970. It changes what the user sees after a restart; an issue of its own once PR 3 has landed, with the upgrade check. The lost pending row of #1002 is separate and needs no schema change
Q4 May a pure move in player/* merge on the emulator checklist on both backends, without the owner’s device check Yes, only when the test below passes (overseer, 2026-11-25). Anything else in the player waits for the owner
Q5 One log port for application (debug, warn, error over Timber in core), or one per service as FallbackLog One log port, FallbackLog folded into it when PR 13 lands. Done in PR 13: AppLog
Q6 Cast’s differences (no start position, no PlaybackEvents, two requests per item, the remembered audio dropped) Kept as they are in the moves; one issue each, fixed after PR 14 with a receiver to test on
Q7 The order: #967, #966 and #969 first, then the downloads, then the player Yes (overseer, 2026-11-25)

The test for Q4. In the PR’s branch, against origin/main:

  • every changed file under player/ is a rename or a Kotlin file whose only changed lines are package and import lines (a caller’s import follows the move);
  • no build file under player/ changes;
  • no file under player/ is added or deleted;
  • the only changed Kotlin lines anywhere are package and import lines.
Terminal window
git fetch origin
# 1. Every change that touches player/ is an exact rename (R100), a rename of a Kotlin file, or a
# modified Kotlin file (M); command 2 holds the Kotlin files to package and import lines. The
# renames are detected on the whole diff first, so a move from player/ to domain/ shows as R,
# not as a deletion. A changed rename of any other file, a changed build file, or an added or
# deleted file under player/, prints (#1112).
# The path is matched after a tab, so docs/player/… does not count; git quotes a path with
# unusual characters ("player/…"), hence the optional quote.
git diff -M --name-status origin/main...HEAD \
| grep -vE '^R100[[:space:]]|^R[0-9]+[[:space:]][^[:space:]]*\.kt[[:space:]]' \
| grep -E '[[:space:]]"?player/' | grep -vE '^M[[:space:]].*\.kt$'
# 2. No changed Kotlin line other than package and import lines.
git diff -M -U0 origin/main...HEAD -- '*.kt' | grep '^[+-]' | grep -v '^\(+++\|---\)' \
| grep -v '^[+-]\(package\|import\) ' | grep -v '^[+-]$'

Both commands must print nothing. A PR for which either prints a line is marked Player, not Move.

What PR 9 found.

  • The first command of the Q4 test contradicted row 9. It wanted every changed file under player/ to be a rename, but a rule that moves to another package changes the import lines of its callers, and six callers are in player/ (PlayerViewModel, PlaybackReporter, SegmentTrackerSettings, SleepTimerLabels, CastSegmentSkipper and its test). No move with a caller in player/ could pass it. The overseer corrected the test on 2026-12-02 (above): a modified Kotlin file under player/ passes the first command, and the second holds it to package and import lines. The intent is unchanged: nothing in player/ changes but those lines, no build file, no added or deleted file. The last stage of the first command is grep -vE '^M[[:space:]].*\.kt$', not grep -vP '^M\t.*\.kt$': on a pipe, the GNU grep 3.0 of Git for Windows did not match the latter, so it printed every modified file.
  • matchSeriesTrack and seriesTrackChoice did not move. They share SeriesTrackPreference.kt with serverAudioTracks, which imports ServerAudioTrack of player/core, and R19 keeps that out of domain; moving two functions out of the file is not a rename. They go to step 10 with the serverAudioTracks split.
  • The KDoc of SegmentTracker and UpNextCountdown links to dev.jdtech.jellyfin.player.local.presentation.PlayerViewModel, which domain cannot see. It compiles, but the link no longer resolves. Changing it is not an import line, so step 10 or 13 fixes it.

What PR 10 found.

  • The setting reaches the rule as an enum of domain, AutoPlayNextSetting (SERVER, ON, OFF), not as the stored string. PlayerSettings.autoPlayNext returns it, and core maps the string in AppPreferencesPorts.kt: an unset or unknown value is SERVER, which is what the rule did with it before. The rule’s two tests for those values are now tests of that mapping (AutoPlayNextSettingTest in core).
  • Only part of SeriesTrackPreference.kt could move. audioStreamIndex goes through serverAudioTracks, which returns ServerAudioTrack, a Parcelable of player/core, so both stay in player/local (ServerAudioTracks.kt, tested in ServerAudioTracksTest). They can move with the track preferences in step 16, once the audio dialog has a type of its own.
  • PlayingSnapshot holds the start report’s Job. That is kotlinx, so domain may name it, but it is the service’s state, not a rule’s: step 13 may make it a value of the reports service.
  • refreshPlayingSnapshotMovingOn in the view model passed the snapshot’s duration to closingOutroStartMs, which found no closing outro for C.TIME_UNSET because the value is negative. It now skips a snapshot without a duration. The result is the same, and the view model stays at its R24 ceiling of 2534 lines.
  • PlaybackReporter.updatePosition still takes a known duration. refreshPlayingSnapshot turns media3’s C.TIME_UNSET away before it calls it, which is where the player’s values come in, so C.TIME_UNSET stays in the view model.

What PR 11 found.

  • The Q4 test’s first command dropped every rename, so a rename under player/ of a file that is not Kotlin, with its content changed (R090 of a strings.xml), passed both commands (#1112). It now drops only exact renames (R100) and renames of Kotlin files, which command 2 reads. Fed a made-up list, it prints an R090 xml under player/, a modified build file, an added and a deleted file, and not an R100 xml, an R095 Kotlin move, a modified Kotlin file or anything under docs/player/. A path git quotes ("player/…", non-ASCII) counts too. On PR 9’s range it prints nothing. Its middle stage is grep -E with [[:space:]], not grep -P '\t', for the same reason as the last one.

  • P7’s decision said the outro skip uses the same steps as the end of an item. It does not (see “Done in PR 11” under P7), so the rule has outro steps of its own. P7 also said autoplay is awaited only where it is needed; updateUpNext awaits it on every tick, before it looks at anything else.

    Hypotheses from reading the code, kept as they are and pinned by the rows named. Each is to be reproduced on an emulator before anything is changed; none is filed:

    • O7: an automatic outro skip to the next item never asks “Are you still watching?”. When the prompt is due at the next advance, the card hides itself (U8), so the skip seeks straight to the next item. That seek is not marked as automatic (pendingAutoAdvanceSeek), so onPositionDiscontinuity takes it as the user’s and resets the tracker: a series with automatic outro skips may never ask.
    • E12: the sleep timer is not read again after the autoplay wait. A timer set to the end of the item, or a duration timer that fires, while a slow server answers, lets the advance go on. Only a slow first answer can show it.
    • O8: if the countdown runs out on the same tick as the outro skip, updateUpNext advances (or asks), and the skip then skips again. Probably not reachable: the countdown starts with the outro.
    • The outro skip checks no item after either wait: a next pressed while a slow server answers makes the skip act on the new item. And updateUpNext reads the item and the duration before its wait and the position after it, so the countdown may get one item’s id with another’s position. No row: the steps take what the view model reads, and step 12 must read in the same order.

What PR 12 found.

  • The rule fitted the view model as it is: no step, row or test of EndOfItemSteps changed, only its KDoc, which said it had no caller. The line numbers under P7 and in row 12 were out of date by then (the end of an item started at VM 1204, the outro skip at 1021); search by name.
  • Where the view model now does a little differently, with the same effect:
    • LastItem calls autoAdvanceToNextItem directly, as P7 says, instead of going through advanceOrAskStillWatching with no next item. advance(hasNextItem = false) counts nothing and returns Next, so nothing changes.
    • updateUpNext returns its decision, and the outro skip reads that instead of _upNext.value?.secondsLeft. Both give the same answer: a countdown shows only when the card is eligible, which needs a next item in the queue, so Show with seconds always sets _upNext. Nothing suspends between the two.
    • The outro skip is a function of its own, autoSkip, called from updateCurrentSegment.
    • The prompt’s deadline is read before the pause and the stop report, not after them: microseconds apart, on the same clock.
    • Each step reads the player once (hasNextMediaItem, the item) where the old conditions read it two or three times in a row, on the main thread with nothing in between. The reads around the autoplay wait keep their order: in updateUpNext the item and the duration before it, the position after it; at the end of an item, the item again after it.
  • The view model hardly shrinks (2534 to 2530 lines). The steps replace the conditions, but the glue that carries the results out (a when per step, UpNextFacts) is nearly as long. The lines go in PRs 13 to 18.
  • Tests: the order is EndOfItemStepsTest’s. PlayerInvariantsTest now checks that the view model calls every step, reads none of sleepTimer.stopsAtEndOfItem, upNextCountdown.isCancelled/update, stillWatchingTracker.onAutoAdvance/ wouldPromptOnAutoAdvance or SegmentTracker.autoSkipTarget itself, and reads the item again after the autoplay wait. What each result does (the pause, the reports, the seeks, the card’s state, NavigateBack) has no unit test: the view model cannot be built without Android. The emulator walk in the PR covers it.

What PR 13 found.

  • application already had a log port of the shape Q5 asks for: RepositoryLog of #966 (debug, warn, error), which this ADR did not name. It became AppLog, and FallbackLog was folded into it, so there is one port and not a third. In core, TimberRepositoryLog and TimberFallbackLog are now two TimberAppLogs with the tags they had (MediaRepositoryImpl, StoredFallbackKt). The reporter’s lines are tagged PlaybackReporter. Before, DebugTree tagged the lines written inside a coroutine with the lambda’s class (PlaybackReporter$reportStopped), so a logcat filter on the exact tag sees them under the class name now. The text of every line is unchanged.
  • The sketch above names the service PlaybackReports, which is the name of the repository’s role since #967. The service kept the name PlaybackReporter, which also keeps the calls that PlayerInvariantsTest looks for.
  • The stream value is ReportedStream in the service’s package, not a model of domain: only the service uses it. The mapping from PlayerItem is new code in the view model’s package (presentation/ReportedStreams.kt), so the view model needs no import for it. With the old import of the reporter replaced by the new one, it stays at 2534 lines, its R24 ceiling. It did not shrink: this step changes three of its call sites and no logic.
  • The Job is kept as ReportedItem (the snapshot and the job), which takePlaying and onPlayerReleased return and reportStopped takes. Its constructor and the job are internal, so only the service reads the job. playing is still the plain PlayingSnapshot, which is all the view model reads. PlayingSnapshot no longer imports kotlinx.
  • The tests already ran under runTest in virtual time, with a StandardTestDispatcher for the report scope, since #765: the move changed nothing about their timing. 31 tests before and after.
  • PlayerInvariantsTest reads a file of another module now (../../application/… from player/local). Two of its checks name the service’s private state, playingItem?.startJob, where they named playing?.startJob; they check the same lines.

What PR 14 found.

  • The service had no way in for a report that another class has already decided: every operation of the local player reads the player, keeps state and sends PlaybackEvents. It got three that send what they are given at once, in the caller’s coroutine, and let a failure through: sendDecidedStart (no position, Q6), sendDecidedProgress and sendDecidedStop, with positions in milliseconds that the service turns into ticks. They read and change none of the local player’s state and send no PlaybackEvents (Q6). Cast still launches each call in its own scope on the main thread and catches and logs a failure with the same Timber line as before, so what reaches the repository, on which thread, and the log are unchanged.
  • The two stops did the same arithmetic: a float division, times 100, truncated to an Int. Clamping was the only difference. Cast’s stop without a known duration (no percentage) is the rule’s stop with startSent = true, since Cast stops only an item whose start it reported. Cast never stores a duration of 0 or less, and the rule treats one as unknown as well. So the rule took one input, clampPercentage, and its other callers pass nothing.
  • CastReport.Stop keeps the position in milliseconds and takes only the percentage from the rule. The rule’s positionTicks is the same value (a test says so), and keeping the type kept the 41 tests of CastPlaybackReporterTest unchanged.
  • Cast takes a PlaybackReporter from PlaybackReporterModule, as “How a use case is shaped” says it would. It is unscoped, and the controller is a singleton, so Cast has one. Its scope, dispatcher and the local player’s state go unused there.
  • setPlaySession is still called by Cast directly. R25 names the three report operations, and this step moves only them; the play session goes through the service with the queue (step 17), or stays where it is.
  • R25 is a text check, as R16 and R28 are: a call or a function reference of the three names counts, a declaration (fun postPlaybackStop( in MediaRepositoryImpl and the role, or an extension of that name) and a comment do not. “The report role after #967” is PlaybackReports, whose operations kept their names.
  • The independent review of the PR found that a class could still go around the role to the server’s playback port (MediaServer.playback.reportStart, reportProgress, reportStopped): the Cast controller holds a MediaServer. R25 covers that too now: only MediaRepositoryImpl, which implements the role over the port, and the adapter (server/jellyfin) call them. testing calls them in its contract suites and is left out as a test dependency (R8). The port’s names are only taken as the port’s when they are called on playback or in a file that names PlaybackPort, because PlaybackReporter.reportStopped, reportProgress and UserDataSyncPort.reportStopped share them. A call through a variable of another name in a file that never names the port would pass; no such call exists. No other caller turned up.
  • SyncWorker tells the server that a downloaded item stopped, through UserDataSyncPort.reportStopped (#584), when it syncs what was played without the server. That is a port and a flow of its own, not a playback report of a running player, and R25 does not cover it.
  • The review also named two edge cases of the text check. A // inside a string was already handled: withoutComments keeps string literals as they are, and a test of R25 says so now. An extension declaration (fun PlaybackReports.postPlaybackStop() was taken for a call; the declaration pattern now allows type parameters and a receiver.
  • “New architecture rules” puts Cast’s calls at CastPlayerControllerImpl 505, 520 and 535; on main before this step they were at 546, 561 and 576. The order of the PRs says R25 does not land without a receiver. It lands here, because this PR waits for the owner’s receiver check before it merges.
  • The debug stand-in (FakeCastPlayerController) replaces the whole controller, so on an emulator no Cast report reaches the server, before or after this step. The emulator shows that the stand-in and the local player’s reports still work; what a receiver’s session sends is the owner’s check.

What PR 15 found.

  • The use case has more than one operation. Next to resolve (one request, then the pick) it keeps the operations it had: the view model’s quality picker reads and stores the cap per network through it (qualityNetwork, maxBitrateSetting, storedMaxBitrate, storeMaxBitrate), and PlaylistManager.withChosenAudio still calls sources for the audio of a transcode, and picks from the answer in its own way: only a server source with the same id, else the source it had. pick would fall back to another version, so that request could not go through resolve without a change of behaviour. The audio request goes with step 16, the cap with step 18.
  • ResolvedStream holds the ItemSource that plays and the cap it was asked with (null for a download), not a copy of the fields P1 lists. toPlayerItem reads more of the source than that list: the bitrates, the frame rate, the subtitles, the trickplay of that version and the default audio stream. The URL, the transcode and the play session are read from the source. There is no list of audio streams: serverAudioTracks reads the source’s streams, as before.
  • The sources of the first item are asked for next to the item itself (getInitialItem), so resolved picks from sources asked for ahead, without a request, and resolve asks and picks. An empty answer asked for ahead is still the end: it does not ask again.
  • PlayerSettings had to name the network, so QualityNetwork moved from settings to domain. AppVariant stays in settings: the use case takes qualityPerNetwork, and ResolvePlaybackModule passes true for the phone. The port gained preferredAudioLanguage, maxBitrate(network) and setMaxBitrate, the first write on it; it has 9 members (R21 allows 15). Which preference is behind each is AppPreferencesPlayerSettingsTest’s in core, and the phone and TV choice is ResolvePlaybackModuleTest’s in player/local.
  • Tests: ResolvePlaybackTest had 15 tests in player/local. Five were added against the old class (the cap per network read and stored, the cap of the network in use, the preferred language, the sources as the server gives them), with PlaylistManagerResolvedStreamTest (6: what the queue asks for and carries at the start and on a quality switch). The 20 moved to application over FakePlayerSettings and FakeNetworkConnectivity of testing, with five more for resolve and resolved. player/local went from 441 to 434 tests (20 out, 13 in), application from 200 to 225, core from 184 to 187.
  • No ceiling changed: PlayerViewModel stays at 2530 lines (its imports of ResolvePlayback and QualityNetwork moved). PlaylistManager grew from 697 to 701 lines; it has no ceiling.
  • Cast is untouched: it resolves through the local PlaylistManager, as before, and asks for the receiver’s source on its own.

What PR 16 found.

  • Two classes, not one service. The view model’s choice lives as long as the player and is read ahead in its scope; the audio of a transcode reads the saved row fresh each time and remembers what it asked for per item. They share no state, so one class would have held two unrelated halves. The view model builds its TrackPreferences with viewModelScope (not through Hilt), and PlaylistManager builds its TranscodeAudio; neither changed its constructor.
  • trackSelections reads every candidate before it returns the selections, on the same thread and without a suspension, as the view model did. The view model still checks that the item is the same after the series’ row is read, then applies.
  • A saved row with a track type other than audio (1) or subtitles (3) is now dropped when it is read. The app never writes one. The rows still hold media3’s numbers (TrackKind.storedType), so no Room migration was needed.
  • serverAudioTracks stays in player/local: it builds the player’s track rows. Only the filter of the streams a transcode can be asked for moved (transcodeAudioStreams), with audioStreamIndex.
  • ResolvedStream is made only in application now, so a copy with another source is made there too (TranscodeAudio’s second request).
  • Logs: the lines keep their tags (PlayerViewModel, PlaylistManager) through TimberAppLog. A failed audio request now logs its exception with the stack trace.
  • Tests: the order was pinned on a copy in player/local first (26 tests), then moved. player/local went from 434 to 427 tests, application from 228 to 273 (TrackPreferencesTest, SessionTrackPicksTest with one more, TranscodeAudioTest with 11).
  • PlayerViewModel went from 2530 to 2443 lines and its ceiling with it. PlaylistManager went from 701 to 620; it has no ceiling.
  • On a phone, a build of main and this branch chose the same audio and subtitle tracks, and asked the server for the same audio index, in every step of the sequence on both players: a movie with and without a preferred audio language, a series’ choice over three episodes and back, after a restart, subtitles off, a pick by hand and a quality switch, a version and a download.

What PR 17 found.

  • The queue’s rules were all in PlaylistManager. The view model and the Cast controller only call it (start, load the episode list, previous and next, the current item, a jump, the upcoming items, forget, a switch), so neither got smaller. PlayerViewModel stays at 2443 lines: the start position became one call (one line less), and its import is one line more. CastPlayerControllerImpl stays at 1190 and CastViewModel at 609. No ceiling changed. PlaylistManager went from 620 to 253 lines, and PlayQueue has 488; neither has a ceiling.
  • P2 says the service “hands out items, not PlayerItems”. It does, but an item counts as handed out only once the player made its PlayerItem: a stream that fails to resolve leaves the item for the next lookup. A jump and a switch also change the queue only after the conversion. So each operation takes the caller’s conversion as a function and runs it where PlaylistManager ran toPlayerItem. Returning the item and marking it afterwards would have changed what two lookups that overlap see while the server answers (#657).
  • The queue asks for the first item’s sources next to the item, since step 15, so it takes ResolvePlayback for the sources and the cap of the network in use, and hands both on in a QueueStart. The pick, the stream and TranscodeAudio stay in PlaylistManager’s mapping.
  • Cast uses the queue through PlaylistManager, not directly. It needs the PlayerItem for its first request (the local target and cap, kept by Q6) and for what it shows, and that mapping is the player’s. CastPlaylistOrder stays in player/cast: it is the order of the receiver’s queue as far as Cast was told, not a rule of the queue. Cast’s code did not change.
  • NeighbourLoader stays in player/local. Its rule is where a neighbour goes in the player’s playlist, and P2 keeps that playlist with the player. QueueRebuild belongs to step 18.
  • The start position (VM 755 to 760 at 41de995ad) is PlayQueue.startPositionMs: the position saved for the player, else where the queue said the item starts. C.TIME_UNSET for “neither” stays in the view model.
  • setPlaySession stays where it is: in Cast, and in PlaybackReporter.onStreamQueued for the local player. PR 14 left it to this step or to stay; the play session belongs to a stream, and the queue holds items.
  • Logs: the lines keep their tag (PlaylistManager) through TimberAppLog. Four failures (the episode in full, the episode list, the previous or next item, the next season) now log their exception as the throwable, with the stack trace, instead of in the message.
  • Tests: 17 tests pinned what no test held, on PlaylistManager as it was (handing out once and again after a forget, a failed stream or a jump; an item that is not queued; a failed episode list; the start positions; a series without next up; a kind with no queue; a shuffled season at its end). Then the queue’s tests moved to application (PlayQueueTest, PlayQueueNextSeasonTest, PlayQueueShuffleTest, PlayQueueNextUpTest), and five of the pinned tests stayed on PlaylistManager for the player’s part (PlaylistManagerQueueTest). The moved tests check the Item; one more test there checks that the PlayerItem carries the trickplay of the source that plays and the chapters, which the old next-up and shuffle tests read. application went from 273 to 311 tests, player/local from 429 to 416 (17 pinned, 31 moved, 1 added; 429 is main with the tests of #1134 and #1116), player/cast stayed at 144 (proprietary) and 45 (libre).
  • The review of PR 16 left four things for this PR, all done: TranscodeAudio logs a failure once; TranscodeAudioTest tests saved audio that was switched off on its own; the subtitles area lists TranscodeAudio.kt and TrackPicks.kt again; and FakeCurrentAccount has a file of its own. An area holds eight paths at most. So that no file falls out of every area (the guide check asks only about listed files), the subtitles area traded PlayerViewModel.kt, which the player and playback-reporting areas list, for SubtitleStyle.kt, and the player area lists its domain/ folder in place of three of its files, which made room for JellyfinDeviceProfiles.kt and PlaybackService.kt.

What PR 18 found.

  • The two players share less than P4 assumed. The local player’s switch asks for the whole queue again, keeps the newest of overlapping picks, and stores and undoes a cap per network. Cast’s audio switch asks for one receiver source with the picked track (PlaybackTarget.CastReceiver, not ResolvePlayback), loads it at the receiver’s position and lets the receiver refill its own queue; it stores no cap, and its quality applies on the next load. What both do is “the newest switch wins, a failure undoes its own change”, and Cast does that with its own job and a load token that live in the Cast SDK’s callbacks. Moving that into the service would have changed what Cast sends, so Cast’s switch stayed in CastPlayerControllerImpl, and its ceiling (1190) and CastViewModel’s (609) did not change. docs/areas/cast.md says so.
  • The service is generic over the player’s item (StreamSwitches<T>, rebuildQueue<T> with an idOf), not over a stream type of application: what the view model swaps in is its own PlayerItem list, built by PlaylistManager.recreatePlayerItem, and a copy into a type of our own and back would add a mapping for nothing.
  • The failure still comes back through the host (Host.failed), not as a returned value: a switch runs in the caller’s scope and ends when a newer one cancels it, so nobody waits on a result. The text is switchFailureText, now in a file of its own in player/local (domain/ SwitchFailureText.kt), since StreamSwitches.kt left the module.
  • The cap per network moved into the service (PR 15 left “the cap” to this step). The view model no longer keeps the network of the last pick (pickedBitrateNetwork): selectBitrate reads the network when the pick is made and stores it there, which is what the view model did in the same call. followNetworkQuality became itemPlays(itemId, streamCap), which returns the cap the queue is asked for again under; the view model logs that line, as before, since AppLog has no info level. The line is now written just after the first request starts, not before it.
  • swapInQueue stays in the view model: whether every URL is the same, the index and position, the start report on mpv, prepare and playWhenReady all read or drive the player.
  • R27 needed more than the moves of steps 9 to 18. Five files of the player’s domain package imported media3: EndOfItem.kt, Extensions.kt (the track names), SubtitleFiles.kt (MIME types), TrackPicks.kt (track types) and NetworkRecovery.kt (two error codes). Extensions.kt, SubtitleFiles.kt and TrackPicks.kt are mappers and moved to dev.jdtech.jellyfin.player.local.mapping as renames, with their tests. The other two hold rules, which stay in domain on our own values: isNewEndOfItem (#477) takes two booleans, and isNewEndOfItemReport in mapping reads media3’s reason and state for it. NetworkRecovery takes the error codes as a constructor parameter, and the set is NETWORK_ERROR_CODES in mapping (PlaybackErrorsTest pins it). PlaylistManager no longer imports media3 since step 17 and stays in domain.
  • One file outside the four packages still names media3: PlaybackService.kt, the media session’s service, whose class name the manifest holds. architecture/baseline/player-media3.txt lists it with that reason. PlayerMediaSessions.kt, which hands the view model’s session to it, moved to presentation.
  • R27 is a text check, as R6 is: a full name without an import counts, a comment does not. It checks names, not use: a rule could still use a media3 type that a mapping function returns, through inference, without naming it. Nothing does today. Its scanner test is R27 finds media3 in code only.
  • Tests: StreamSwitchesTest moved to application with its 19 tests, over FakePlayerSettings and FakeNetworkConnectivity instead of a map the host stored in; five more test itemPlays, which had no test in the view model, and RebuildQueueTest (4) tests rebuildQueue on its own. QueueRebuildTest stays in player/local: it runs the rebuild with NeighbourLoader and PlaylistManager. PlaybackErrorsTest (1) is new. application went from 311 to 339 tests, player/local from 416 to 398 (19 out, 1 in), architecture from 65 to 67; domain (356) and player/cast (144 proprietary, 45 libre) did not change.
  • The R24 ceiling of PlayerViewModel went down from 2443 to 2420.

Where the series ended. “Done for #970” set three numbers, and they were not all reached:

  • PlayerViewModel has 2420 lines, not at most 1800. The rules left it, but the glue that carries their results out, the media3 wiring, the subtitle sync sheet and trickplay are still in it. Splitting the view model further is a task of its own.
  • DownloaderImpl has 1493 lines, not at most 1100: step 8 took its rules, and what is left is the engine’s I/O.
  • DownloadQueue left downloads (step 6); its Android side has 113 lines, under the 150 allowed.
  • Every flow P1 to P7 and D1, D2, D4 has its tests in domain or application. Cast uses the stop rule and the segment rule of domain, and R25 holds. Cast’s switch is its own (above), so one playback flow still exists twice, in a different shape.
  • R24 to R27 landed; R27 last, with this step.
  • The rules of playback and downloads are tested in seconds, without Android, and the download queue’s backoff with virtual time instead of real sleeps.
  • Cast and the local player share one set of report, segment and queue rules; a fix lands once.
  • PlayerViewModel and DownloaderImpl shrink, and R24 keeps them from growing back.
  • Upstream changes to PlayerViewModel and PlaylistManager merge by hand after PRs 12 to 18, as after ADR 0002’s tasks.
  • About 18 PRs, none visible to a user. Breakdown:
    • Seven touch the running player beyond imports: 10, 12, 13, 15, 16, 17, 18.
    • Three need a Cast receiver: 14, 17, 18.
    • Six change the running download queue or its screens: 3 to 8. Three of those also change its restore: 3, 6, 8.
    • One is a pure move: 9.
    • Three change nothing that runs: 1, 2, 11.

Source: docs/architecture/adr/0003-playback-and-download-use-cases.md · raw Markdown