Cast
Status: Google Cast in the proprietary flavour of the phone app (#626); libre and app/tv have no Cast SDK. As of 2026-11-25 (main).
Start here
Section titled “Start here”- Cast lives in
player/cast(which haslibreandproprietaryflavours, plusdebugfor the emulator stand-in) and the phone UI inapp/phone/.../presentation/cast/.app/tvdoes not depend onplayer/cast. - Everything that touches the Cast SDK (
com.google.android.gms:play-services-cast-framework,androidx.mediarouter) is inplayer/cast/src/proprietary/.player/cast/src/libre/provides stubs (CastSessionManagerImpl,CastPlayerControllerImpl) that reportCastAvailability.NOT_IN_BUILD. CastViewModel(player/cast/src/main/.../presentation/CastViewModel.kt) feeds every Cast surface: the top bar button (CastButton), the device sheet (CastDeviceSheet), the mini player (CastMiniPlayer), and the expanded/side-panel player (CastPlayer).CastHost(app/phone/.../presentation/cast/CastHost.kt) wraps the navigation display and is the only Cast entryNavigationRootknows.server/jellyfin/.../server/jellyfin/cast/builds the Chromecast device profiles (Chromecast,ChromecastH265) and resolves receiver stream URLs (ReceiverSource,ReceiverUrls).- Test fast:
./gradlew :player:cast:testLibreDebugUnitTest :player:cast:testProprietaryDebugUnitTestand./gradlew :app:phone:compileLibreDebugKotlin :app:phone:compileProprietaryDebugKotlin.
What it does
Section titled “What it does”In proprietary builds, CastSessionManagerImpl wraps the Play Services CastContext and MediaRouter to discover Cast receivers, track connection state (CastConnectionState), and connect or disconnect. When CastAvailability is checked, CastSessionManager.availability returns CastAvailability.DISABLED when the Cast setting (castEnabled) is off, CastAvailability.NO_PLAY_SERVICES when CastContext is unavailable, and CastAvailability.AVAILABLE otherwise (it does not depend on the current server; if the Cast button is hidden, check the setting first).
CastPlayerControllerImpl (src/proprietary/) loads items onto the receiver’s RemoteMediaClient with CastCustomData (serialized mediaSourceId, playSessionId, transcoded, defaultAudioStreamIndex, and track lists; no stream URL or token, since the receiver already has the stream URL), handles play/pause/seek/queue navigation and track switches (CastTracks, CastUrls), takes its queue from the local player’s PlaylistManager, over the shared PlayQueue of application (step 17 of #970), and keeps the neighbours it was handed in CastPlaylistOrder, and decides playback reports through CastPlaybackReporter, which sends none itself: the controller sends them through the shared PlaybackReporter of application (R25, step 14 of #970), and the stop’s percentage is playbackStopReport of domain with Cast’s clamp to 0..100. An audio switch (setAudioTrack) asks the server for the item’s receiver source with the picked track and loads it again at the receiver’s position: one LOAD, a stop report for the old stream and a start for the new one. A subtitle switch only changes the receiver’s active tracks, and the cap (castMaxBitrateMbps) applies on the next load. Cast does not use the local player’s StreamSwitches (step 18 of #970): that service rebuilds the player’s whole queue and stores a cap per network, while Cast reloads one item and the receiver refills its own queue (manageQueue). What they share is the idea that the newest switch wins and a failure undoes its own change, which Cast keeps with its own job and load token. CastPositions.ranOut (src/main/) detects the brief position-0 report when an item runs out at the end, shared by CastPlaybackReporter and CastSegmentSkipper (#851, #994).
CastSegmentSkipper (src/main/) applies SegmentTracker (domain/.../playback/rule/) to receiver position updates: auto-skipping segments configured to skip (seeking to endTicks, capped at durationMs - END_MARGIN_MS when durationMs > 0L; no seek occurs when the capped target is not ahead of the playback position) and showing the skip button for “ask” segments, while guarding against stale positions after a load or seek, foreign item reports, and the end-of-item position-0 report (#994).
In libre builds, CastSessionManagerImpl and CastPlayerControllerImpl are no-op stubs with CastAvailability.NOT_IN_BUILD, and CastHost renders its content directly without adding any Cast UI.
Where the code is
Section titled “Where the code is”| Path | What |
|---|---|
player/cast/build.gradle.kts |
libre and proprietary flavours; proprietaryImplementation for Cast Framework and MediaRouter |
player/cast/src/main/.../CastSessionManager.kt, CastPlayerController.kt |
Shared interfaces for session discovery/connection and remote playback control |
player/cast/src/main/.../presentation/CastViewModel.kt |
Single @HiltViewModel per activity driving all Cast surfaces (CastUiState, CastEvent) |
player/cast/src/main/.../presentation/CastSegmentSkipper.kt, CastPositions.kt |
Segment auto-skip/button logic over receiver reports (#994); CastPositions.ranOut |
player/cast/src/main/.../di/CastModule.kt |
Provides CastSessionManager and CastPlayerController, using CastStandIn when active |
player/cast/src/proprietary/.../CastPlayerControllerImpl.kt, CastSessionManagerImpl.kt |
Real Cast SDK implementation (RemoteMediaClient, CastContext, MediaRouter) |
player/cast/src/proprietary/.../CastCustomData.kt, CastPlaybackReporter.kt, CastOptionsProvider.kt |
Queue item custom data (#767), receiver playback report decisions, notification/receiver options |
player/cast/src/proprietary/.../CastTracks.kt, CastUrls.kt, CastPlaylistOrder.kt, LegacyPlaybackInfo.kt |
Track mapping, castContentType / audioStreamIndexOf, queue ordering, playback info parsing |
player/cast/src/libre/.../ |
Stub CastSessionManagerImpl (NOT_IN_BUILD) and CastPlayerControllerImpl |
player/cast/src/debug/.../FakeCast.kt |
Debug stand-in (FakeCastModule, FakeCastSessionManager, FakeCastPlayerController) gated by debug.ephyra.cast |
app/phone/.../presentation/cast/CastHost.kt |
Wraps navigation content; hosts CastMiniPlayer, CastDeviceSheet, CastPlayer, CastButton, CastDialogs, CastPlayback |
server/jellyfin/.../server/jellyfin/cast/ |
Chromecast, ChromecastH265, ReceiverSource, ReceiverUrls |
- R1, R2: no Jellyfin SDK types or
JellyfinApioutsideserver/jellyfin. - R10: ids (
ItemId,MediaSourceId) are value classes, serialized as strings inCastCustomData. - R25: only
PlaybackReportercallspostPlaybackStart,postPlaybackProgressandpostPlaybackStop, and onlyMediaRepositoryImplthe playback port’sreportStart,reportProgressandreportStopped: the controller holds aMediaServer, but may not report throughmediaServer.playback. Cast’s reports go through itssendDecided*functions;setPlaySessionstays a direct call ofPlaybackReports. - Flavour separation:
libremust stay free of Google Play Services and Cast SDK imports (CastOptionsProviderandReconnectionServicelive only inplayer/cast/src/proprietary/AndroidManifest.xml). Every change inplayer/cast/src/main/orapp/phone/.../presentation/cast/must compile in bothlibreandproprietaryflavours (compileLibreDebugKotlinandcompileProprietaryDebugKotlin).
How to test it
Section titled “How to test it”./gradlew :player:cast:testLibreDebugUnitTest :player:cast:testProprietaryDebugUnitTest./gradlew :app:phone:compileLibreDebugKotlin :app:phone:compileProprietaryDebugKotlinUnit tests in player/cast:
src/test/:CastSegmentSkipperTest,CastViewModelSegmentTest(runs in bothlibreandproprietaryflavours using Robolectric and fakes).src/testProprietary/:CastCustomDataTest,CastMediaIdentityTest,CastAudioPreparationTest,CastItemIdTest,CastPlaybackReporterTest,CastPlayerControllerSeekTest,CastReportSendingTest,CastPlaylistOrderTest,CastQueueVisitTest,CastReceiverItemsTest,CastTracksTest,CastUrlsTest,LegacyPlaybackInfoTest.
On an emulator (proprietary debug build only): emulators find no real Cast receivers. Set the system property to enable the debug stand-in (FakeCast.kt):
adb shell setprop debug.ephyra.cast fake # restart the app afterwardsSupported scenarios via debug.ephyra.cast: fake (normal connected devices), fake:none (no devices found), fake:connectfail, fake:fail, fake:error, fake:drop, fake:lost, fake:end, fake:unavailable (no Play Services).
What cannot be tested without a real Cast receiver:
- Actual device discovery, Cast session connection/reconnection, and standby behaviour (
onStandbyStateChanged, #851). - Real receiver media loading, HLS/MP4 playback, subtitle/audio track switching on the receiver, and receiver-emitted stale/foreign/end-of-item position reports (the stand-in moves its position immediately on seek and sends nothing to the server).
Before a PR
Section titled “Before a PR”./gradlew ktfmtCheck./gradlew :player:cast:testLibreDebugUnitTest :player:cast:testProprietaryDebugUnitTest./gradlew :app:phone:compileLibreDebugKotlin :app:phone:compileProprietaryDebugKotlinDecisions and history
Section titled “Decisions and history”- #626:
proprietaryflavour with Google Cast;librestays free of Google code; singleCastViewModelandCastHost. - #767:
CastCustomDatakeeps stream metadata on the receiver without URLs or tokens so a session can be picked up after process death. - #851, #994:
CastSegmentSkipperandCastPositions.ranOutfor segment skipping during Cast; TV standby handling inCastPlayerControllerImplremains open in #851.
Pitfalls
Section titled “Pitfalls”-
Accept each neighbour before asking for the other (#1141).
PlayQueuehands out each successfully converted item once.CastPlaylistOrder.loadNeighboursrecords Next and lets the controller publish its availability before asking for Previous. Lookup remains sequential in one supervised child; accepted receiver insertions run as sibling children, so waiting for receiver status or media building cannot hold up Previous lookup or availability. Lookup cancellation propagates in its own child without cancelling accepted insertions; replacing the queue job cancels every child of that visit. Superseded preparations share their original audio rollback baseline until a LOAD is submitted; each LOAD keeps its own copy for rejection. Guarded rollback restores only those audio tracks onto the latest sender item, preserving newer subtitles, and another item or forgotten playlist cannot inherit that baseline. Cancellation of audio preparation clears and notifies only its own pending load before propagating; a new audio generation is reserved before cancelling its predecessor. Losing the receiver client or item clears only the owned pending state and baseline, without restoring old audio onto its replacement. An audio attempt does not replace the receiver visit: preparation failure or LOAD rejection preserves the same receiver visit and its queue job. Rollback starts a replacement queue job only when an established anchor has demonstrably changed to a different valid receiver identity (queue id or a new opaque media token) for the same item; unknown, zero, foreign-item and unchanged anchors never authorize a refill. An accepted LOAD replaces that job throughonCurrentItemSet. Queue work binds a nonzero receiver queue item id only when its media matches the expected item. When initial status is absent or still belongs to the prior item, availability can publish while the same job waits for SDK status events to bind its first matching anchor. An unbound visit waits for a pending LOAD outcome before accepting its first anchor; rollback wakes that same waiter, while success cancels it. A bound anchor never switches, so a same-item LOAD that changes that identity invalidates old insertion even before the LOAD callback. Visit replacement or session cleanup cancels the waiter along with its queue job. Receiver insertion checks the active job, item, playlist and receiver anchor again after building the media; Previous is inserted before the current receiver queue item by its stable queue item id, not an index. A later job using the samePlaylistManagerkeeps that first answer even if the manager returns null for it. Sender-built media carries an opaque per-build token. Both normal and audio LOAD refills require that token before accepting status, so an old callback-time snapshot cannot bind even when a new queue reuses its predecessor’s numeric id; restored legacy media needs no expected token. Queue-entry media with an Ephyra item id supplies both item and token together, with mediaInfo used only when that entry has no usable item id. Audio submission checks its generation before announcement and again immediately before clearing the shared baseline and sending; rollback also updates the sender item cache. Each handoff checks that the manager still belongs to the current playlist; a late lookup must not fill a playlist that replaced it. -
Compiling only
libremissesproprietarybreakages.app/phoneandplayer/castdefault tolibre; always runcompileProprietaryDebugKotlinandtestProprietaryDebugUnitTestwhen touching shared Cast code. -
Stand-in hides receiver timing quirks.
FakeCastPlayerControllerupdates position immediately on seek and does not report to the server, so late position reports, end-of-item position-0 blips, and playback reporting must be covered by unit tests (CastSegmentSkipperTest,CastViewModelSegmentTest,CastPlaybackReporterTest) and verified on a real receiver when available. -
Direct play container assumption (
CastUrls.kt).castContentType(isTranscoded)returns"video/mp4"for direct play and"application/x-mpegurl"for transcodes rather than trusting ffprobe’s container list.
Source: docs/areas/cast.md · raw Markdown