Compare commits

..

No commits in common. "main" and "v0.6.1" have entirely different histories.
main ... v0.6.1

43 changed files with 418 additions and 996 deletions

View file

@ -35,11 +35,6 @@ jobs:
if test -f distribution/Kaleido.apk; then if test -f distribution/Kaleido.apk; then
(cd distribution && sha256sum -c Kaleido.apk.sha256) (cd distribution && sha256sum -c Kaleido.apk.sha256)
.tools/sdk/build-tools/35.0.0/apksigner verify --verbose --print-certs distribution/Kaleido.apk .tools/sdk/build-tools/35.0.0/apksigner verify --verbose --print-certs distribution/Kaleido.apk
# The APK's own manifest must carry the advertised version (and, for a tag, version.properties').
case "${{ github.ref }}" in
refs/tags/v*) python3 scripts/verify_distribution.py --release ;;
*) python3 scripts/verify_distribution.py ;;
esac
fi fi
- name: Publish signed tag release - name: Publish signed tag release
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v')

View file

@ -35,17 +35,7 @@ Install `app/build/outputs/apk/release/app-release.apk` instead for performance/
## Testing suite ## Testing suite
Use `& $KaleidoPython` before the Python commands below. **Never run competing device/UI tests in parallel.** Use `& $KaleidoPython` before the Python commands below. Run only checks relevant to the change; **never run competing device/UI tests in parallel**. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home. After a functional debug batch, restore the signed release and its ART profile before returning the device to normal use; never judge performance from an unoptimized debug build.
**Test in tiers; don't run every suite for every change.** Each device script cold-starts Kaleido, waits for playback and real timers, and dumps the UI per check, so a full pass takes 30+ minutes.
1. **Every change:** `.\Build.ps1 -Test` (compile, JVM unit tests, lint; about a minute). Put pure logic (ordering, parsing, fingerprints, countdown rules) in unit-testable functions with JVM tests instead of proving it on the TV.
2. **UI or device behaviour changed:** run only the one or two scripts for the area touched (map below), plus a screenshot of the changed screen. One script is usually 1–4 minutes.
3. **Before a release, or after broad navigation/playback/startup changes:** the full set: `verify_ui.py browse` and `player`, `repro_runtime.py controls episode postplay credits sections`, `verify_player_features.py`, `verify_settings.py`, then the release build with `repro_runtime.py browse` for frame pacing.
Area → checks: Home/Movies/TV rows, focus, details Back → `verify_ui.py browse` · player bar, menus, scrubbing → `verify_ui.py player` · previous/next episode, auto-skip, server picker, cross-device refresh → `verify_player_features.py <phase>` · post-play/autoplay/credits → `repro_runtime.py postplay` or `credits` · Settings rows/dialogs → `verify_settings.py` · details/cast → `verify_details_layout.py` / `verify_movie_details.py` · library A–Z/search → `verify_library_jump.py` · startup/tab loading → `repro_runtime.py sections` · scrolling smoothness → release + `repro_runtime.py browse`. Skip suites for untouched areas and say which were skipped.
Run only checks relevant to the change. Live playback tests change real Plex progress and can change playback preferences. Restore a useful final state, normally the release build on Home. After a functional debug batch, restore the signed release and its ART profile before returning the device to normal use; never judge performance from an unoptimized debug build.
| Command | Purpose / required build | | Command | Purpose / required build |
| --- | --- | | --- | --- |
@ -55,8 +45,8 @@ Run only checks relevant to the change. Live playback tests change real Plex pro
| `scripts/repro_runtime.py browse` | Horizontal bounds and frame pacing; **optimized release with profile compilation** | | `scripts/repro_runtime.py browse` | Horizontal bounds and frame pacing; **optimized release with profile compilation** |
| `scripts/repro_runtime.py controls` | One-press Back, OK reveal, timed hide and exit; **debug** | | `scripts/repro_runtime.py controls` | One-press Back, OK reveal, timed hide and exit; **debug** |
| `scripts/repro_runtime.py episode` | Next-episode replacement/crash regression; **debug** | | `scripts/repro_runtime.py episode` | Next-episode replacement/crash regression; **debug** |
| `scripts/repro_runtime.py postplay` | Natural ending → Up Next countdown → next episode READY; **debug** | | `scripts/repro_runtime.py postplay` | Natural ending → five-second countdown → next episode READY; **debug** |
| `scripts/repro_runtime.py credits` | Credits → Up Next (mini-player), season/related rows, any-press cancel, Back to video; **debug** | | `scripts/repro_runtime.py credits` | Visible Skip credits, season/related rows and cancellable countdown; **debug** |
| `scripts/device.py screenshot <name>` | Capture to ignored `evidence/private/`; also supports `hierarchy`, `logs`, `launch`, `key` | | `scripts/device.py screenshot <name>` | Capture to ignored `evidence/private/`; also supports `hierarchy`, `logs`, `launch`, `key` |
| `scripts/profile_browse.py` | Targeted atrace investigation when navigation performance regresses | | `scripts/profile_browse.py` | Targeted atrace investigation when navigation performance regresses |
| `scripts/profile_transitions.py <label>` | Skipped frames per D-pad transition (tabs, hero, rows, Movies) from framestats; first cycle is the first pass after launch; profiled **release**; raw frames kept for `resummarize` | | `scripts/profile_transitions.py <label>` | Skipped frames per D-pad transition (tabs, hero, rows, Movies) from framestats; first cycle is the first pass after launch; profiled **release**; raw frames kept for `resummarize` |
@ -68,8 +58,7 @@ Run only checks relevant to the change. Live playback tests change real Plex pro
| `scripts/verify_movie_details.py` | Movie safe header, related movies and Back focus restoration; debug or release | | `scripts/verify_movie_details.py` | Movie safe header, related movies and Back focus restoration; debug or release |
| `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences | | `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences |
| `scripts/verify_library_jump.py` | Scoped Movie/TV categories, A–Z jumps beyond the first page, details/Back focus and exact Silo search | | `scripts/verify_library_jump.py` | Scoped Movie/TV categories, A–Z jumps beyond the first page, details/Back focus and exact Silo search |
| `scripts/verify_player_features.py [phase…]` | Phases `previous_episode`, `auto_skip` (Skipping intro fill, Down/Back cancel), `server_picker` (Back/Cancel), `refresh` (resume and open-app Continue Watching sync; moves and restores Silo 1×1 progress); **debug**; restores skip preferences | | `scripts/verify_audio_preferences.py` | Theme/boost persistence and actual boosted playback; **debug**; restores prior audio preferences |
| `scripts/verify_audio_preferences.py` | Theme persistence and actual playback audio; **debug**; restores prior audio preferences |
Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation: Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation:
@ -86,7 +75,7 @@ These require the private test session. Playback test intents (`testTitleId`, `t
## Important regression traps ## Important regression traps
- Keep initialization independent of cancellable tab requests and apply section results atomically. Cancelling initialization during a startup tab switch previously left Movies/TV blank. - Keep initialization independent of cancellable tab requests and apply section results atomically. Cancelling initialization during a startup tab switch previously left Movies/TV blank.
- Foreground library sync polls revisions every 15 seconds with a 60-second refresh fallback, and checks within a second of returning to the foreground. The revision includes a Continue Watching fingerprint (membership, order, watch count, progress in 5% steps) so watching on another device shows up without refreshing Home on every poll; pause it for playback/background and stage updates before applying them. Preserve stable hub/card focus IDs and current library filters/range. `LibrarySyncIntegrationTest` tests the real timer against an in-memory HTTP fixture without changing Plex or the encrypted session. - Foreground library sync polls revisions every 15 seconds with a 60-second refresh fallback; pause it for playback/background and stage updates before applying them. Preserve stable hub/card focus IDs and current library filters/range. `LibrarySyncIntegrationTest` tests the real timer against an in-memory HTTP fixture without changing Plex or the encrypted session.
- Home, Movies and TV stay composed once shown; hidden ones are unplaced, have no semantics and must never request focus (gate effects on `active`). Catalog and rails prefetch through `FramePrefetch`/`CacheWindows`, which must remain a `CacheWindowLogic` or rows stop being kept around. With any accessibility service enabled, Compose walks every composed node after each layout change: keep offscreen rows and cards without semantics (`semanticsOnScreen`). See `docs/runtime-verification.md` (frame pacing). - Home, Movies and TV stay composed once shown; hidden ones are unplaced, have no semantics and must never request focus (gate effects on `active`). Catalog and rails prefetch through `FramePrefetch`/`CacheWindows`, which must remain a `CacheWindowLogic` or rows stop being kept around. With any accessibility service enabled, Compose walks every composed node after each layout change: keep offscreen rows and cards without semantics (`semanticsOnScreen`). See `docs/runtime-verification.md` (frame pacing).
- Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread. - Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread.
- Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**. - Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**.
@ -94,9 +83,8 @@ These require the private test session. Playback test intents (`testTitleId`, `t
- A text field keeps the D-pad: route Down/IME actions out of Search's field explicitly. Give every `focusRestorer()` a fallback, or it overrides explicit focus targets. Per-card modifiers on browse rows must be `Modifier.Node`s, not `composed {}`, and must not animate per card. - A text field keeps the D-pad: route Down/IME actions out of Search's field explicitly. Give every `focusRestorer()` a fallback, or it overrides explicit focus targets. Per-card modifiers on browse rows must be `Modifier.Node`s, not `composed {}`, and must not animate per card.
- Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats. - Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats.
- **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test. - **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test.
- Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them. Automatic skips (Settings › Playback, 0 = button only) show "Skipping intro/credits" with a filling background rather than a number, count down only while playing, and are cancelled by any remote press (OK on the button skips now; Back only cancels). - Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them.
- Theme tracks come from Plex metadata and inherit from the show for seasons/episodes. Stop music on video playback/background. Volume boost was removed because it degraded audio; keep passthrough and the normal audio path. - Theme tracks come from Plex metadata and inherit from the show for seasons/episodes. Stop music on video playback/background. Volume boost processes decoded PCM; Off must preserve passthrough and the normal audio path.
- A server-stopped session (Plex dashboard Stop) arrives as `terminationCode`/`terminationText` on the timeline response. Leave the player with the reason and never fall back or reconnect afterwards; timelines keep reporting `buffering` while a stream stalls so the stop is still noticed.
### Performance testing ### Performance testing

View file

@ -1,31 +1,5 @@
# Kaleido releases # Kaleido releases
## 0.8.1
- Fix a title page where Down from the buttons did nothing, leaving you stuck at the top. This happened when the Seasons, Cast or another row below had been scrolled away from its first card, for example by reopening a show from Continue Watching. Down now moves to a card in view.
## 0.8.0
- Replace the two countdowns at the end of an episode with one Up Next screen. When the credits start, the video shrinks into the top-left corner and keeps playing, beside the next episode's artwork, details, rating and synopsis, with the rest of the season and related shows below. Play next episode fills as it counts down, and pressing any button on the remote stops the countdown. Press Left and select the video, or press Back, to return to the credits.
- Update Continue Watching as soon as you leave the player, including an episode you have just started.
- Remove the label above the featured title on Home ("Recently released", "Suggested for you" and similar), as in Kaleido Desktop.
## 0.7.0
- Add a Previous episode button to the player, and redesign its controls: elapsed and remaining time at the ends of the timeline, previous episode, back 10 seconds, play, forward 30 seconds and next episode grouped in the centre, and the finish time beside Exit. Previous episode also steps back through a shuffle.
- Skip intros and credits automatically after a delay you choose in Settings › Playback (3, 5, 10 or 15 seconds, or show the button only). A pending skip reads "Skipping intro" with a filling background; pressing any button on the remote cancels it, and OK skips straight away. The earlier "Automatically" setting becomes a 5-second skip.
- Show what you watch on other devices promptly: Kaleido checks Continue Watching every 15 seconds while open and as soon as you return to it.
- Keep playback paused when you leave Kaleido while a stream is still starting, and only count down to the next episode while Kaleido is on screen.
- Keep the resume point when leaving a title before its stream has started, and keep progress reports on the server the title came from.
- Close Settings › Choose server with Back or the new Cancel button, and enter Home's rows from the Home tab when there is no featured title.
- Cancel slow network requests when they are no longer needed, and connect to the best server address as soon as it answers.
- Update a title's format badges when you pick another version, keep New Seasons when one show can't be loaded, and keep focus on Continue Watching when a card is replaced while a title page is open.
- Remove Volume boost, which degraded audio, and leave the player with the server's reason when a stream is stopped from the Plex dashboard.
## 0.6.2
- New startup animation, the same as Kaleido Desktop's: a kaleidoscope of shards turns and gathers into the Kaleido mark, then the view flies through its centre into Home.
## 0.6.1 ## 0.6.1
- Make browsing noticeably smoother on Android TV hardware. Switching between Home, Movies and TV no longer rebuilds each section, returning to the hero or from a title page no longer redraws Home, and moving between rows prepares the next cards ahead of time instead of mid-scroll. - Make browsing noticeably smoother on Android TV hardware. Switching between Home, Movies and TV no longer rebuilds each section, returning to the hero or from a title page no longer redraws Home, and moving between rows prepares the next cards ahead of time instead of mid-scroll.

View file

@ -10,7 +10,7 @@ A Plex client for Android TV, designed for browsing from the couch. Kaleido puts
- **Home** brings together featured titles, Plex recommendations and Continue Watching. Resume a movie or get back to your current series without digging through your library. - **Home** brings together featured titles, Plex recommendations and Continue Watching. Resume a movie or get back to your current series without digging through your library.
- **Movies** starts with recent releases and recommendations. **TV Shows** leads with your next episodes, new seasons and newly added episodes. - **Movies** starts with recent releases and recommendations. **TV Shows** leads with your next episodes, new seasons and newly added episodes.
- **Library** gives you an A–Z poster grid with watched-status and sorting controls; **Categories** browses by genre. If you have more than one movie or TV library, choose which one each section shows. - **Library** gives you an A–Z poster grid with genre, watched-status and sorting controls. If you have more than one movie or TV library, choose which one each section shows.
- **Search** finds movies, shows, episodes and people across your libraries. Type with the remote or search by voice. - **Search** finds movies, shows, episodes and people across your libraries. Type with the remote or search by voice.
- **Title pages** include ratings, a synopsis, trailers and extras, and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first. Season and episode pages show the episode you move to in the season row; select it, or Play, to watch. - **Title pages** include ratings, a synopsis, trailers and extras, and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first. Season and episode pages show the episode you move to in the season row; select it, or Play, to watch.
- **Quick actions**: hold OK (or press Menu) on any title to play, start over, mark it watched, remove it from Continue Watching, or jump to its season or show. - **Quick actions**: hold OK (or press Menu) on any title to play, start over, mark it watched, remove it from Continue Watching, or jump to its season or show.

View file

@ -30,14 +30,6 @@ class BrowsePolicyTest {
assertEquals(listOf("unknown1","unknown2","s1"),result.take(3).map{it.id}) assertEquals(listOf("unknown1","unknown2","s1"),result.take(3).map{it.id})
assertTrue(groupRecentSeasons(emptyList()){error("Empty row")}.isEmpty()) assertTrue(groupRecentSeasons(emptyList()){error("Empty row")}.isEmpty())
} }
@Test fun recentSeasonsSurviveOneUnavailableShow()=runBlocking {
val newest=title("s4","season").copy(parentId="gone",parentTitle="Missing",title="Season 4")
val older=title("s3","season").copy(parentId="gone",parentTitle="Missing",title="Season 3")
val other=title("s9","season").copy(parentId="show-c",parentTitle="Other",title="Season 9")
val result=groupRecentSeasons(listOf(newest,older,other)){throw PlexException("This item is no longer available.",404)}
assertEquals(listOf("s4","s9"),result.map{it.id})
assertEquals("Missing · Season 4",result.first().title)
}
@Test fun partiallyWatchedShowUsesEpisodeCountsEvenWithViewCount() { @Test fun partiallyWatchedShowUsesEpisodeCountsEvenWithViewCount() {
val show=Title.parse(JSONObject("""{"type":"show","viewCount":12,"leafCount":30,"viewedLeafCount":10}""")) val show=Title.parse(JSONObject("""{"type":"show","viewCount":12,"leafCount":30,"viewedLeafCount":10}"""))

View file

@ -111,29 +111,14 @@ import androidx.compose.ui.text.input.TextFieldValue
// A reopened episode page resets its selection, but its saved scroll can still // A reopened episode page resets its selection, but its saved scroll can still
// point elsewhere. Compose the entry card before the header sends focus Down. // point elsewhere. Compose the entry card before the header sends focus Down.
LaunchedEffect(rowId){if(initialItem!=null)row.scrollToItem((initial-1).coerceAtLeast(0))} LaunchedEffect(rowId){if(initialItem!=null)row.scrollToItem((initial-1).coerceAtLeast(0))}
val entryIndex=if(entryFocus!=null)rememberRowEntry(row,entry).value else -1
Column { Column {
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)} Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)}
LazyRow(state=row,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) { LazyRow(state=row,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) {
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=(if(index==entryIndex&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier),onMove={anticipateTileMove(vm,items,index,it,0)},episodeTitle=episodeTitles,current=item.id==selectedItem,onFocused=onFocused,onClick=onClick)} itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=(if(index==entry&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier),onMove={anticipateTileMove(vm,items,index,it,0)},episodeTitle=episodeTitles,current=item.id==selectedItem,onFocused=onFocused,onClick=onClick)}
} }
} }
} }
/**
* The card a row is entered at from above: [preferred] while it is in view, otherwise the first
* card fully in view. A card scrolled out of a lazy row (e.g. a restored or scrolled Seasons row)
* is not composed, so an explicit focus move to its requester fails and strands focus above.
*/
internal fun rowEntryIndex(preferred:Int,visible:List<LazyListItemInfo>,viewportStart:Int):Int {
if(visible.isEmpty()||visible.any{it.index==preferred})return preferred
return (visible.firstOrNull{it.offset>=viewportStart} ?: visible.first()).index
}
/** [rowEntryIndex], updated only when a card enters or leaves the row's view. */
@Composable internal fun rememberRowEntry(row:LazyListState,preferred:Int):State<Int> =
remember(row,preferred){derivedStateOf{row.layoutInfo.let{rowEntryIndex(preferred,it.visibleItemsInfo,it.viewportStartOffset)}}}
internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) { internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
val target=when(direction){ val target=when(direction){
Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1 Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1
@ -173,6 +158,7 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
val name=if(vm.page.kind=="movies")"Movies"else "TV Shows" val name=if(vm.page.kind=="movies")"Movies"else "TV Shows"
LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()} LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()}
var sortMenu by remember{mutableStateOf(false)} var sortMenu by remember{mutableStateOf(false)}
var genreMenu by remember{mutableStateOf(false)}
var sectionMenu by remember{mutableStateOf(false)} var sectionMenu by remember{mutableStateOf(false)}
val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()} val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
val filterFocus=remember{FocusRequester()};val categoryEntryFocus=remember{FocusRequester()};val railFocus=remember{FocusRequester()};val sectionFocus=remember{FocusRequester()} val filterFocus=remember{FocusRequester()};val categoryEntryFocus=remember{FocusRequester()};val railFocus=remember{FocusRequester()};val sectionFocus=remember{FocusRequester()}
@ -221,7 +207,8 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) { Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) {
Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp) Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus},selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)} TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus}){genreMenu=true}
TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true} TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true}
} }
val grid=rememberLazyGridState() val grid=rememberLazyGridState()
@ -262,7 +249,7 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
val lastColumn=index%6==5||index==vm.library.lastIndex val lastColumn=index%6==5||index==vm.library.lastIndex
MediaTile(vm,item,"library:${item.id}",fillWidth=true,modifier=Modifier.focusRequester(requester).then(if(lastColumn)Modifier.focusProperties{right=railFocus}else Modifier),onMove={anticipateTileMove(vm,vm.library,index,it,6)},onFocused={vm.onLibraryGridFocused()}) MediaTile(vm,item,"library:${item.id}",fillWidth=true,modifier=Modifier.focusRequester(requester).then(if(lastColumn)Modifier.focusProperties{right=railFocus}else Modifier),onMove={anticipateTileMove(vm,vm.library,index,it,6)},onFocused={vm.onLibraryGridFocused()})
} }
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another category or watch filter.")} if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")}
if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}} if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}}
} }
LibraryJumpRail(enabledLetters,vm.libraryJumpLetter,railFocus,{scope.launch{runCatching{ returnFocusToGrid() }}},{vm.jumpToLibraryLetter(it)}) LibraryJumpRail(enabledLetters,vm.libraryJumpLetter,railFocus,{scope.launch{runCatching{ returnFocusToGrid() }}},{vm.jumpToLibraryLetter(it)})
@ -270,6 +257,7 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
} }
} }
if(sortMenu)ChoiceDialog("Sort by",sortLabels.map{it.second},sortLabels.indexOfFirst{it.first==vm.sort},{sortMenu=false}){vm.filter(sortValue=sortLabels[it].first);sortMenu=false} if(sortMenu)ChoiceDialog("Sort by",sortLabels.map{it.second},sortLabels.indexOfFirst{it.first==vm.sort},{sortMenu=false}){vm.filter(sortValue=sortLabels[it].first);sortMenu=false}
if(genreMenu)ChoiceDialog("Genres",listOf("All genres")+vm.genres.map{it.second},vm.genres.indexOfFirst{it.first==vm.genre}+1,{genreMenu=false}){vm.filter(genreValue=if(it==0)""else vm.genres[it-1].first);genreMenu=false}
if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}} if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}}
} }

View file

@ -9,7 +9,13 @@ import androidx.media3.exoplayer.audio.ForwardingAudioSink
/** Android rejects a center-only PCM mask; one-channel audio uses its standard mono output. */ /** Android rejects a center-only PCM mask; one-channel audio uses its standard mono output. */
@androidx.annotation.OptIn(UnstableApi::class) @androidx.annotation.OptIn(UnstableApi::class)
internal class CompatibleAudioSink(sink:AudioSink):ForwardingAudioSink(sink) { internal class CompatibleAudioSink(sink:AudioSink,private val decodedOnly:Boolean=false):ForwardingAudioSink(sink) {
override fun supportsFormat(format:Format):Boolean =
if(decodedOnly&&format.sampleMimeType!=MimeTypes.AUDIO_RAW)false else super.supportsFormat(format)
override fun getFormatSupport(format:Format):Int =
if(decodedOnly&&format.sampleMimeType!=MimeTypes.AUDIO_RAW)AudioSink.SINK_FORMAT_UNSUPPORTED else super.getFormatSupport(format)
override fun getFormatOffloadSupport(format:Format):androidx.media3.exoplayer.audio.AudioOffloadSupport =
if(decodedOnly)androidx.media3.exoplayer.audio.AudioOffloadSupport.DEFAULT_UNSUPPORTED else super.getFormatOffloadSupport(format)
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
override fun configure(config:AudioSink.AudioSinkConfig) { override fun configure(config:AudioSink.AudioSinkConfig) {
val format=compatiblePcmFormat(config.format) val format=compatiblePcmFormat(config.format)

View file

@ -177,15 +177,11 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
} }
scrolling.join() scrolling.join()
} }
/** The first card of the first row: where Down goes when Home has no hero to hold focus. */
suspend fun enterFirstRow(){hubs.firstOrNull{it.items.isNotEmpty()}?.let{hub->val item=hub.items.first();anticipateCard(item);moveToRow(hub.id,item.id)}}
suspend fun moveToHero()=coroutineScope { suspend fun moveToHero()=coroutineScope {
heroActive=true heroActive=true
val scrolling=launch{list.animateBrowseTo(0)} val scrolling=launch{list.animateBrowseTo(0)}
focusHero();scrolling.join() focusHero();scrolling.join()
} }
/** Whether focus is inside this screen; a card key in [KaleidoViewModel.focusId] alone doesn't mean it is. */
val screenFocus=remember{booleanArrayOf(false)}
LaunchedEffect(hubs) { LaunchedEffect(hubs) {
val old=previousHubs val old=previousHubs
if(old==hubs)return@LaunchedEffect if(old==hubs)return@LaunchedEffect
@ -210,19 +206,6 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
previousHubs=hubs previousHubs=hubs
// A hidden screen moves no focus; it finds its card again when shown. // A hidden screen moves no focus; it finds its card again when shown.
if(!active())return@LaunchedEffect if(!active())return@LaunchedEffect
if(oldHub==null) {
// The card being restored (e.g. after details) was already gone from the previous rows,
// and this refresh cancelled that restoration. Finish it here instead of leaving focus
// on the top bar: the card itself if it is back, else the first card of its row.
val key=focus
val row=hubs.firstOrNull{key.startsWith("${it.id}:")&&it.items.isNotEmpty()}
if(row!=null&&!screenFocus[0]) {
val item=row.items.firstOrNull{"${row.id}:${it.id}"==key} ?: row.items.first()
columns[row.id]=item.id;pendingColumns[row.id]=item.id
navigationJob[0]=scope.launch{withFrameNanos{};moveToRow(row.id,item.id)}
}
return@LaunchedEffect
}
if(oldHub!=null&&oldTitle!=null) { if(oldHub!=null&&oldTitle!=null) {
val sameHub=hubs.firstOrNull{it.id==oldHub.id} val sameHub=hubs.firstOrNull{it.id==oldHub.id}
@ -261,8 +244,6 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
// Discover is fixed above the catalog. Enter it immediately, without resetting // Discover is fixed above the catalog. Enter it immediately, without resetting
// or waiting for two lazy lists to lay out. The next Down explicitly enters row 0. // or waiting for two lazy lists to lay out. The next Down explicitly enters row 0.
if(!home)runCatching{local.section.requestFocus()} if(!home)runCatching{local.section.requestFocus()}
// Continue Watching and other rows can exist without an eligible featured title.
else if(activeFeature.value==null)navigationJob[0]=scope.launch{enterFirstRow()}
else { else {
if(heroActive)runCatching{heroFocus.requestFocus()} if(heroActive)runCatching{heroFocus.requestFocus()}
navigationJob[0]=scope.launch{moveToHero()} navigationJob[0]=scope.launch{moveToHero()}
@ -298,6 +279,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
} }
// Hidden, the screen keeps its state but gives up focus: an unplaced card must not take key // Hidden, the screen keeps its state but gives up focus: an unplaced card must not take key
// events. Shown again, it focuses what a freshly composed screen would. // events. Shown again, it focuses what a freshly composed screen would.
val screenFocus=remember{booleanArrayOf(false)}
val focusManager=LocalFocusManager.current val focusManager=LocalFocusManager.current
suspend fun reveal() { suspend fun reveal() {
withFrameNanos{} withFrameNanos{}
@ -309,7 +291,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(key=="discovery-entry"&&!home)runCatching{local.section.requestFocus()} if(key=="discovery-entry"&&!home)runCatching{local.section.requestFocus()}
return return
} }
if(key=="home-feature"){if(home&&feature!=null)moveToHero()else if(home)enterFirstRow();return} if(key=="home-feature"){if(home&&feature!=null)moveToHero();return}
val card=hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{"${hub.id}:${it.id}"==key}?.let{hub to it}} val card=hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{"${hub.id}:${it.id}"==key}?.let{hub to it}}
if(card!=null){moveToRow(card.first.id,card.second.id);return} if(card!=null){moveToRow(card.first.id,card.second.id);return}
if(requesters[key]?.let{runCatching{it.requestFocus()}.getOrDefault(false)}==true)return if(requesters[key]?.let{runCatching{it.requestFocus()}.getOrDefault(false)}==true)return
@ -660,6 +642,8 @@ internal fun runtimeLabel(ms:Long):String {val minutes=(ms/60000).coerceAtLeast(
val metadata by produceState(item,item.id){value=item;value=vm.previewDetails(item)} val metadata by produceState(item,item.id){value=item;value=vm.previewDetails(item)}
Column { Column {
val parts=copyParts(3) val parts=copyParts(3)
Eyebrow(feature.reason)
Spacer(Modifier.height(9.dp))
TitleIdentity(vm.api,item,Modifier.width(264.dp).height(80.dp)) TitleIdentity(vm.api,item,Modifier.width(264.dp).height(80.dp))
if(parts>=2)Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) { if(parts>=2)Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=10.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false)) Text(listOf(item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=10.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))

View file

@ -1,6 +1,6 @@
package tv.kaleido.app package tv.kaleido.app
data class HomeFeature(val item:Title) data class HomeFeature(val item:Title,val reason:String)
/** Interleave discovery categories; Continue Watching has its own rail. */ /** Interleave discovery categories; Continue Watching has its own rail. */
internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>,random:kotlin.random.Random=kotlin.random.Random.Default):List<HomeFeature> { internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,continuing:List<Title>,random:kotlin.random.Random=kotlin.random.Random.Default):List<HomeFeature> {
@ -9,10 +9,10 @@ internal fun homeFeatures(recent:List<Title>,rated:List<Title>,hubs:List<Hub>,co
item.id !in excluded&&!item.fullyWatched&&item.offset==0L item.id !in excluded&&!item.fullyWatched&&item.offset==0L
// Shuffle movies and shows together rather than always leading with the same movie section. // Shuffle movies and shows together rather than always leading with the same movie section.
val buckets=listOf( val buckets=listOf(
recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled(random).map{HomeFeature(it)}, recent.filter{eligible(it)&&it.releaseDate.isNotBlank()}.sortedByDescending{it.releaseDate}.take(18).shuffled(random).map{HomeFeature(it,"Recently released")},
rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled(random).map{HomeFeature(it)}, rated.filter{eligible(it)&&it.viewedLeafCount==0}.shuffled(random).map{HomeFeature(it,"Highly rated · Unwatched")},
hubs.filterNot{h->listOf("continue","ondeck","inprogress","recentlyviewed","recentlyadded","recentlyaired","recent").any{h.id.contains(it,true)}} hubs.filterNot{h->listOf("continue","ondeck","inprogress","recentlyviewed","recentlyadded","recentlyaired","recent").any{h.id.contains(it,true)}}
.flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled(random).map{HomeFeature(it)} .flatMap{it.items}.filter(::eligible).distinctBy{it.id}.shuffled(random).map{HomeFeature(it,"Suggested for you")}
) )
val seen=mutableSetOf<String>() val seen=mutableSetOf<String>()
return buildList { return buildList {

View file

@ -35,11 +35,6 @@ private fun categoryArtworkHint(section:Section,genre:String):String?=when {
else->null else->null
} }
private const val SyncQuietMillis=2000L private const val SyncQuietMillis=2000L
/** The countdown an earlier "Automatically" skip setting becomes. */
internal const val AutoSkipDefaultSeconds=5
/** Returning to Kaleido checks the server almost at once, so watching elsewhere shows up promptly. */
private const val ResumeSyncDelayMillis=750L
private const val PlaybackReportWaitMillis=4_000L
class KaleidoViewModel(app: Application): AndroidViewModel(app) { class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication val application = app as KaleidoApplication
val api = application.api val api = application.api
@ -102,8 +97,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var playbackReturn by mutableIntStateOf(0); private set var playbackReturn by mutableIntStateOf(0); private set
private var retryAction:(()->Unit)?=null private var retryAction:(()->Unit)?=null
private var previousTab="home" private var previousTab="home"
/** Observable, so the version button, format badges and technical line all follow a new choice. */ private val mediaChoices=mutableMapOf<String,Int>()
private val mediaChoices=androidx.compose.runtime.mutableStateMapOf<String,Int>()
/** The episode a season or episode page shows, by page id. Focus in its season row chooses it. */ /** The episode a season or episode page shows, by page id. Focus in its season row chooses it. */
val episodeSelections=androidx.compose.runtime.mutableStateMapOf<String,String>() val episodeSelections=androidx.compose.runtime.mutableStateMapOf<String,String>()
var query by mutableStateOf(""); private set var query by mutableStateOf(""); private set
@ -126,9 +120,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var remoteQuality by mutableStateOf(preferences.getString("remoteQuality",null)?.let{n->StreamQuality.entries.firstOrNull{it.name==n}} ?: StreamQuality.FullHD); private set var remoteQuality by mutableStateOf(preferences.getString("remoteQuality",null)?.let{n->StreamQuality.entries.firstOrNull{it.name==n}} ?: StreamQuality.FullHD); private set
/** Seconds before the next episode starts; 0 turns autoplay off. */ /** Seconds before the next episode starts; 0 turns autoplay off. */
var autoplaySeconds by mutableIntStateOf(preferences.getInt("autoplaySeconds",5)); private set var autoplaySeconds by mutableIntStateOf(preferences.getInt("autoplaySeconds",5)); private set
/** Seconds the Skip intro/credits button counts down before skipping by itself; 0 only shows the button. */ var autoSkipIntro by mutableStateOf(preferences.getBoolean("autoSkipIntro",false)); private set
var autoSkipIntroSeconds by mutableIntStateOf(autoSkipSeconds("autoSkipIntro")); private set var autoSkipCredits by mutableStateOf(preferences.getBoolean("autoSkipCredits",false)); private set
var autoSkipCreditsSeconds by mutableIntStateOf(autoSkipSeconds("autoSkipCredits")); private set
var subtitleSize by mutableStateOf(preferences.getString("subtitleSize",null)?.let{n->SubtitleSize.entries.firstOrNull{it.name==n}} ?: SubtitleSize.Normal); private set var subtitleSize by mutableStateOf(preferences.getString("subtitleSize",null)?.let{n->SubtitleSize.entries.firstOrNull{it.name==n}} ?: SubtitleSize.Normal); private set
var subtitleStyle by mutableStateOf(preferences.getString("subtitleStyle",null)?.let{n->SubtitleStyle.entries.firstOrNull{it.name==n}} ?: SubtitleStyle.Box); private set var subtitleStyle by mutableStateOf(preferences.getString("subtitleStyle",null)?.let{n->SubtitleStyle.entries.firstOrNull{it.name==n}} ?: SubtitleStyle.Box); private set
/** Debug test intents force a delivery mode (0 file, 1 direct stream, 2 convert); never set in release. */ /** Debug test intents force a delivery mode (0 file, 1 direct stream, 2 convert); never set in release. */
@ -141,6 +134,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var colourWash by mutableStateOf(preferences.getBoolean("colourWash",true)); private set var colourWash by mutableStateOf(preferences.getBoolean("colourWash",true)); private set
var themeMusic by mutableStateOf(preferences.getBoolean("themeMusic",false)); private set var themeMusic by mutableStateOf(preferences.getBoolean("themeMusic",false)); private set
var themeVolume by mutableIntStateOf(preferences.getInt("themeVolume",30).coerceIn(10,100)); private set var themeVolume by mutableIntStateOf(preferences.getInt("themeVolume",30).coerceIn(10,100)); private set
var volumeBoostDb by mutableIntStateOf(preferences.getInt("volumeBoostDb",0).coerceIn(0,12)); private set
var episodeQueue by mutableStateOf(emptyList<Title>());private set var episodeQueue by mutableStateOf(emptyList<Title>());private set
var relatedShows by mutableStateOf(emptyList<Title>());private set var relatedShows by mutableStateOf(emptyList<Title>());private set
var transitioningEpisode by mutableStateOf(false);private set var transitioningEpisode by mutableStateOf(false);private set
@ -174,8 +168,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
Thread({android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);task.run()},"KaleidoArtworkPrefetch").apply{isDaemon=true} Thread({android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);task.run()},"KaleidoArtworkPrefetch").apply{isDaemon=true}
}.asCoroutineDispatcher() }.asCoroutineDispatcher()
init { init {
// Volume boost was removed; drop its stored level.
if(preferences.contains("volumeBoostDb"))preferences.edit().remove("volumeBoostDb").apply()
// Development provisioning is private app data, never an APK resource or build constant. // Development provisioning is private app data, never an APK resource or build constant.
if(BuildConfig.DEBUG) { if(BuildConfig.DEBUG) {
val seed=File(app.filesDir,"bootstrap.json") val seed=File(app.filesDir,"bootstrap.json")
@ -243,25 +235,20 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
librarySyncJob?.cancel();librarySyncJob=null librarySyncJob?.cancel();librarySyncJob=null
if(!value)return if(!value)return
librarySyncJob=viewModelScope.launch { librarySyncJob=viewModelScope.launch {
// Kept across background spells: returning compares against what was last applied, var observedSession=session
// so Continue Watching changes made on another device show up within a second. var sync=newLibrarySync()
var interval=ResumeSyncDelayMillis var interval=LibrarySync.POLL_MS
var backoff=LibrarySync.POLL_MS
while(isActive) { while(isActive) {
delay(interval);interval=backoff delay(interval)
val sync=librarySync?.takeIf{librarySyncSession==session} ?: newLibrarySync().also{librarySync=it;librarySyncSession=session} if(session!=observedSession){observedSession=session;sync=newLibrarySync()}
if(session==null||playing!=null||busy||markingId!=null||initializeJob?.isActive==true)continue if(session==null||playing!=null||busy||markingId!=null||initializeJob?.isActive==true)continue
try{sync.check();backoff=LibrarySync.POLL_MS} try{sync.check();interval=LibrarySync.POLL_MS}
catch(e:CancellationException){throw e} catch(e:CancellationException){throw e}
catch(_:Exception){backoff=(backoff*2).coerceAtMost(LibrarySync.FALLBACK_MS)} catch(_:Exception){interval=(interval*2).coerceAtMost(LibrarySync.FALLBACK_MS)}
interval=backoff
} }
} }
} }
private var librarySyncSession:Session?=null private fun newLibrarySync()=LibrarySync(api::libraryRevision,::syncLibrary,android.os.SystemClock::elapsedRealtime)
private var librarySync:LibrarySync?=null
/** Library contents plus Continue Watching progress, which changes when anything is watched elsewhere. */
private fun newLibrarySync()=LibrarySync({api.libraryRevision()+"#"+api.continueWatchingRevision()},::syncLibrary,android.os.SystemClock::elapsedRealtime)
private suspend fun syncLibrary():Boolean { private suspend fun syncLibrary():Boolean {
val expectedSession=session ?: return false val expectedSession=session ?: return false
val expectedPage=page;val generation=loadGeneration val expectedPage=page;val generation=loadGeneration
@ -293,7 +280,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles|| section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles||
playing!=null||busy||markingId!=null)return false playing!=null||busy||markingId!=null)return false
sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features
android.util.Log.i("KaleidoSync","APPLIED continue=${freshHome.hubs.firstOrNull{it.id=="continue"}?.items?.size ?: 0}")
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear() sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear()
sectionStale=freshSection==null sectionStale=freshSection==null
if(freshSection!=null){section=active;discoverHubs=freshSection.hubs;genres=freshSection.genres;library=freshSection.library.items;total=freshSection.library.total} if(freshSection!=null){section=active;discoverHubs=freshSection.hubs;genres=freshSection.genres;library=freshSection.library.items;total=freshSection.library.total}
@ -338,36 +324,23 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
fun beginAccountLink(){linkingAccount=true;linkAccount()} fun beginAccountLink(){linkingAccount=true;linkAccount()}
fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false} fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false}
/** Rating keys are only unique per server: drop per-title state when the server or account changes. */
private fun clearServerState(){
searchJob?.cancel();searchJob=null;query="";searchResults=SearchResults()
episodeContextJob?.cancel();episodeContextJob=null;episodeTransitionJob?.cancel();episodeTransitionJob=null
episodeQueue=emptyList();relatedShows=emptyList();shuffleEpisodes=null;transitioningEpisode=false
mediaChoices.clear();episodeSelections.clear()
}
fun chooseServer(server: Server) = launchLoad { fun chooseServer(server: Server) = launchLoad {
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState() sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery()
val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome() val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
} }
fun manualConnect(address: String, token: String) = launchLoad { fun manualConnect(address: String, token: String) = launchLoad {
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState() sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery()
require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."} require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."}
require(token.isNotBlank()){ "Enter an access token." } require(token.isNotBlank()){ "Enter an access token." }
val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex","")) val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex",""))
authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome() authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
} }
fun signOut(){loadJob?.cancel();initializeJob?.cancel();clearServerState();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();clearDiscovery();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()} fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();clearDiscovery();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
/** Back or Cancel from the server picker: keep the current server, or start over with a new sign-in code. */
fun dismissServerPicker(){
loadJob?.cancel();busy=false
if(session==null){servers=emptyList();linkAccount()}else cancelAccountLink()
}
fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) } fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) }
fun tab(kind: String){ fun tab(kind: String){
if(pages.size==1&&page.kind==kind)return if(pages.size==1&&page.kind==kind)return
// Search and Settings return to the browsing tab they were opened from. // Search and Settings return to the browsing tab they were opened from.
if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind
if(kind!="search"){searchJob?.cancel();searchJob=null}
cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv")){allTitles=false;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null};pages=listOf(Page(kind));loadPage(true) cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv")){allTitles=false;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null};pages=listOf(Page(kind));loadPage(true)
} }
fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()} fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
@ -387,7 +360,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
/** The version (Plex Media) chosen for this title in this session; the first version by default. */ /** The version (Plex Media) chosen for this title in this session; the first version by default. */
fun mediaIndex(item:Title)=(mediaChoices[item.id] ?: 0).coerceIn(0,(item.media.size-1).coerceAtLeast(0)) fun mediaIndex(item:Title)=(mediaChoices[item.id] ?: 0).coerceIn(0,(item.media.size-1).coerceAtLeast(0))
fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index} fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index;detail=detail?.let{if(it.id==item.id)it.copy()else it}}
fun openActor(actor:CastMember){ fun openActor(actor:CastMember){
if(actor.id.isBlank())return if(actor.id.isBlank())return
pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage() pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage()
@ -480,11 +453,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s) cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s)
if(keepCategories){allTitles=true;categories=true;focusId="categories-entry"} if(keepCategories){allTitles=true;categories=true;focusId="categories-entry"}
} }
fun setAll(value: Boolean){ fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;libraryJumpIndex=-1;libraryJumpLetter=null}
// Genre filtering belongs to Categories; the Library grid always lists the whole section.
val hadGenre=genre.isNotBlank();focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null
if(hadGenre)refreshLibrary()
}
fun openCategories(){val hadGenre=genre.isNotBlank();allTitles=true;categories=true;genre="";focusId="categories-entry";libraryJumpIndex=-1;libraryJumpLetter=null;if(hadGenre)refreshLibrary()} fun openCategories(){val hadGenre=genre.isNotBlank();allTitles=true;categories=true;genre="";focusId="categories-entry";libraryJumpIndex=-1;libraryJumpLetter=null;if(hadGenre)refreshLibrary()}
fun loadCategoryArtworks() { fun loadCategoryArtworks() {
val selectedSection=section ?: return val selectedSection=section ?: return
@ -570,7 +539,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
} }
fun selectCategory(value:String){if(value.isBlank())return;categories=true;allTitles=true;genre=value;sort="titleSort:asc";focusId="category-grid";libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()} fun selectCategory(value:String){if(value.isBlank())return;categories=true;allTitles=true;genre=value;sort="titleSort:asc";focusId="category-grid";libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}
fun filter(sortValue: String=sort,unwatchedValue: Boolean=unwatched){sort=sortValue;unwatched=unwatchedValue;libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()} fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}
private fun refreshLibrary() { private fun refreshLibrary() {
val selectedSection=section ?: return val selectedSection=section ?: return
val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched
@ -691,38 +660,11 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
} }
} }
/** The episode before [item]: the previous one in the show, or the previous shuffle pick. */
fun precedingEpisode(item:Title):Title? {
val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.preceding(item.id)
val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>0)episodeQueue[i-1]else null
}
/** False only once the episode list has loaded and [item] is the show's first episode (or the shuffle's first pick). */
fun mayHavePrecedingEpisode(item:Title):Boolean {
val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.preceding(item.id)!=null
val i=episodeQueue.indexOfFirst{it.id==item.id};return i!=0
}
fun followingEpisode(item:Title):Title? { fun followingEpisode(item:Title):Title? {
val shuffle=shuffleEpisodes val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.following(item.id) if(shuffle!=null)return shuffle.following(item.id)
val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null
} }
fun previousEpisode(item: Title) {
if(episodeTransitionJob?.isActive==true)return
episodeTransitionJob=viewModelScope.launch {
transitioningEpisode=true
try {
val shuffle=shuffleEpisodes
val previous=if(shuffle!=null)shuffle.preceding(item.id) else {
val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
val i=episodes.indexOfFirst{it.id==item.id};if(i>0)episodes[i-1]else null
} ?: return@launch
val metadata=api.details(previous.id)
if(playing?.id==item.id){if(shuffle!=null)shuffle.retreat(item.id,previous.id);startFromZero=true;playbackInstance++;playing=metadata}
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The previous episode could not be loaded."){previousEpisode(item)}}finally{transitioningEpisode=false}
}
}
fun nextEpisode(item: Title) { fun nextEpisode(item: Title) {
if(episodeTransitionJob?.isActive==true)return if(episodeTransitionJob?.isActive==true)return
episodeTransitionJob=viewModelScope.launch { episodeTransitionJob=viewModelScope.launch {
@ -738,14 +680,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The next episode could not be loaded."){nextEpisode(item)}}finally{transitioningEpisode=false} }catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The next episode could not be loaded."){nextEpisode(item)}}finally{transitioningEpisode=false}
} }
} }
/** The server ended this session: leave the player and explain, offering to resume from the saved position. */
fun playbackStoppedByServer(item:Title,message:String){
if(playing?.id!=item.id)return
stopPlayback();fail(message){play(item)}
}
/** Each player's timeline reporter, until it has sent its final position. */
private val playbackReports=java.util.concurrent.CopyOnWriteArraySet<Job>()
internal fun trackPlaybackReports(job:Job){playbackReports+=job;job.invokeOnCompletion{playbackReports-=job}}
fun stopPlayback(){ fun stopPlayback(){
val finished=playing val finished=playing
shuffleEpisodes=null shuffleEpisodes=null
@ -753,9 +687,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
// A season or episode page shows the last episode played, with fresh progress in its row. // A season or episode page shows the last episode played, with fresh progress in its row.
detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id} detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id}
launchLoad { launchLoad {
// The player closes after this frame and only then reports where it stopped. Reloading
// before Plex has that report showed the previous Continue Watching.
kotlinx.coroutines.withTimeoutOrNull(PlaybackReportWaitMillis){playbackReports.toList().forEach{it.join()}}
homeHubs=loadHome() homeHubs=loadHome()
detail?.let { detail?.let {
if(it.type in listOf("movie","episode"))detail=api.details(it.id) if(it.type in listOf("movie","episode"))detail=api.details(it.id)
@ -764,8 +695,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
} }
} }
} }
// Earlier versions stored an on/off switch that skipped at once; on becomes a short, cancellable countdown.
private fun autoSkipSeconds(name:String)=preferences.getInt("${name}Seconds",if(preferences.getBoolean(name,false))AutoSkipDefaultSeconds else 0).coerceIn(0,60)
// Earlier versions stored a mode (Original/Direct stream/Transcode) and a separate transcode quality. // Earlier versions stored a mode (Original/Direct stream/Transcode) and a separate transcode quality.
private fun savedStreamQuality()=preferences.getString("streamQuality",null)?.let{name->StreamQuality.entries.firstOrNull{it.name==name}} private fun savedStreamQuality()=preferences.getString("streamQuality",null)?.let{name->StreamQuality.entries.firstOrNull{it.name==name}}
?: if(preferences.getInt("playbackModeV2",1)==2)(if(preferences.getInt("quality",20000)>20000)StreamQuality.UltraHD else StreamQuality.FullHD)else StreamQuality.Original ?: if(preferences.getInt("playbackModeV2",1)==2)(if(preferences.getInt("quality",20000)>20000)StreamQuality.UltraHD else StreamQuality.FullHD)else StreamQuality.Original
@ -774,8 +703,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
/** The player's quality menu changes the preference for the connection in use. */ /** The player's quality menu changes the preference for the connection in use. */
fun chooseActiveQuality(value: StreamQuality)=if(localConnection)chooseStreamQuality(value)else chooseRemoteQuality(value) fun chooseActiveQuality(value: StreamQuality)=if(localConnection)chooseStreamQuality(value)else chooseRemoteQuality(value)
fun chooseAutoplaySeconds(value:Int){autoplaySeconds=value.coerceAtLeast(0);preferences.edit().putInt("autoplaySeconds",autoplaySeconds).apply()} fun chooseAutoplaySeconds(value:Int){autoplaySeconds=value.coerceAtLeast(0);preferences.edit().putInt("autoplaySeconds",autoplaySeconds).apply()}
fun chooseAutoSkipIntro(seconds:Int){autoSkipIntroSeconds=seconds.coerceIn(0,60);preferences.edit().putInt("autoSkipIntroSeconds",autoSkipIntroSeconds).remove("autoSkipIntro").apply()} fun chooseAutoSkipIntro(value:Boolean){autoSkipIntro=value;preferences.edit().putBoolean("autoSkipIntro",value).apply()}
fun chooseAutoSkipCredits(seconds:Int){autoSkipCreditsSeconds=seconds.coerceIn(0,60);preferences.edit().putInt("autoSkipCreditsSeconds",autoSkipCreditsSeconds).remove("autoSkipCredits").apply()} fun chooseAutoSkipCredits(value:Boolean){autoSkipCredits=value;preferences.edit().putBoolean("autoSkipCredits",value).apply()}
fun chooseSubtitleSize(value:SubtitleSize){subtitleSize=value;preferences.edit().putString("subtitleSize",value.name).apply()} fun chooseSubtitleSize(value:SubtitleSize){subtitleSize=value;preferences.edit().putString("subtitleSize",value.name).apply()}
fun chooseSubtitleStyle(value:SubtitleStyle){subtitleStyle=value;preferences.edit().putString("subtitleStyle",value.name).apply()} fun chooseSubtitleStyle(value:SubtitleStyle){subtitleStyle=value;preferences.edit().putString("subtitleStyle",value.name).apply()}
fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()} fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()}
@ -783,6 +712,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun chooseColourWash(value:Boolean){colourWash=value;preferences.edit().putBoolean("colourWash",value).apply()} fun chooseColourWash(value:Boolean){colourWash=value;preferences.edit().putBoolean("colourWash",value).apply()}
fun chooseThemeMusic(value:Boolean){themeMusic=value;preferences.edit().putBoolean("themeMusic",value).apply()} fun chooseThemeMusic(value:Boolean){themeMusic=value;preferences.edit().putBoolean("themeMusic",value).apply()}
fun chooseThemeVolume(value:Int){themeVolume=value.coerceIn(10,100);preferences.edit().putInt("themeVolume",themeVolume).apply()} fun chooseThemeVolume(value:Int){themeVolume=value.coerceIn(10,100);preferences.edit().putInt("themeVolume",themeVolume).apply()}
fun chooseVolumeBoostDb(value:Int){volumeBoostDb=value.coerceIn(0,12);preferences.edit().putInt("volumeBoostDb",volumeBoostDb).apply()}
fun checkUpdate(manual: Boolean=true){viewModelScope.launch { fun checkUpdate(manual: Boolean=true){viewModelScope.launch {
if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
updateStatus="Checking for updates…" updateStatus="Checking for updates…"

View file

@ -48,17 +48,16 @@ data class TimelineReport(val position: Long,val state: String,val duration: Lon
class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
private val app=vm.application private val app=vm.application
val api=vm.api val api=vm.api
/** The server this title belongs to. Progress reports finish after close and must not follow a server change. */
private val server=api.session
val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate) val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate)
val selector=DefaultTrackSelector(app) val selector=DefaultTrackSelector(app)
private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"}))) private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"})))
private val renderers=object:DefaultRenderersFactory(app) { private val renderers=object:DefaultRenderersFactory(app) {
override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink = override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink =
CompatibleAudioSink(androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context) CompatibleAudioSink(androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput) .setAudioProcessors(if(vm.volumeBoostDb>0)arrayOf(VolumeBoostProcessor(vm.volumeBoostDb){Log.i("KaleidoPlayback","BOOST processing PCM db=${vm.volumeBoostDb}")})else emptyArray())
.setEnableFloatOutput(enableFloatOutput&&vm.volumeBoostDb==0)
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams) .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
.build()) .build(),decodedOnly=vm.volumeBoostDb>0)
}.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing() }.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing()
val player=ExoPlayer.Builder(app,renderers).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply { val player=ExoPlayer.Builder(app,renderers).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true) setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true)
@ -105,36 +104,30 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
private var streamStart=0L private var streamStart=0L
private var preparing=false private var preparing=false
private var closed=false private var closed=false
/** False while the app is stopped (Home, another app): a pending preparation must not start playing. */
private var foreground=true
private val prepareMutex=Mutex() private val prepareMutex=Mutex()
private val streamSelectionMutex=Mutex() private val streamSelectionMutex=Mutex()
private var fallbackPending=false private var fallbackPending=false
private var nativeSelectionApplied=false private var nativeSelectionApplied=false
private val reports=Channel<TimelineReport>(Channel.UNLIMITED) private val reports=Channel<TimelineReport>(Channel.UNLIMITED)
// Trailers and other extras are not library progress.
private val synced=!validation&&item.type!="clip"
/** Set once the server ends this session (dashboard Stop); nothing may reconnect or fall back after it. */
private var serverStopped=false
private val reportJob=app.scope.launch { private val reportJob=app.scope.launch {
val watched=WatchedProgress{api.watched(item,true,server);withContext(Dispatchers.Main){if(api.session==server)vm.refreshWatched(item)}} val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}}
// Trailers and other extras are not library progress.
val synced=!validation&&item.type!="clip"
for(r in reports) { for(r in reports) {
if(synced) { if(synced) {
runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession,server)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")} runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
.getOrNull()?.let{if(!r.final)withContext(Dispatchers.Main){stoppedByServer(it)}}
runCatching{watched.report(r.position,r.duration,vm.watchedPercent)} runCatching{watched.report(r.position,r.duration,vm.watchedPercent)}
.onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")} .onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")}
} }
if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession,server)};break} if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession)};break}
} }
} }
init { init {
vm.trackPlaybackReports(reportJob)
audit?.let{player.addAnalyticsListener(it)} audit?.let{player.addAnalyticsListener(it)}
// Sparse diagnostics also survive in release logcat when an intermittent dropout occurs. // Sparse diagnostics also survive in release logcat when an intermittent dropout occurs.
player.addAnalyticsListener(object:androidx.media3.exoplayer.analytics.AnalyticsListener { player.addAnalyticsListener(object:androidx.media3.exoplayer.analytics.AnalyticsListener {
override fun onAudioUnderrun(t:androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,size:Int,duration:Long,elapsed:Long) { override fun onAudioUnderrun(t:androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,size:Int,duration:Long,elapsed:Long) {
Log.w("KaleidoAudio","UNDERRUN item=${item.id} position=${t.eventPlaybackPositionMs} bufferMs=$duration sinceFeedMs=$elapsed mode=$mode") Log.w("KaleidoAudio","UNDERRUN item=${item.id} position=${t.eventPlaybackPositionMs} bufferMs=$duration sinceFeedMs=$elapsed mode=$mode boost=${vm.volumeBoostDb}")
} }
override fun onAudioSinkError(t:androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,e:Exception) { override fun onAudioSinkError(t:androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,e:Exception) {
Log.w("KaleidoAudio","SINK_ERROR item=${item.id} position=${t.eventPlaybackPositionMs} kind=${e.javaClass.simpleName}") Log.w("KaleidoAudio","SINK_ERROR item=${item.id} position=${t.eventPlaybackPositionMs} kind=${e.javaClass.simpleName}")
@ -173,39 +166,23 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
override fun onPlayerError(e: PlaybackException) { override fun onPlayerError(e: PlaybackException) {
Log.w("KaleidoPlayback","ERROR code=${e.errorCodeName} mode=$mode") Log.w("KaleidoPlayback","ERROR code=${e.errorCodeName} mode=$mode")
if(serverStopped)return if(mode<2&&localValidationFile==null)fallback(e.errorCodeName)else{loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}
if(mode<2&&localValidationFile==null)fallback(e.errorCodeName)
else scope.launch{if(!checkServerStopped(position)){loading=false;error="Playback failed (${e.errorCodeName}). Check the server transcoder, network connection, and media availability."}}
} }
}) })
scope.launch {prepare(mode,position)} scope.launch {prepare(mode,position)}
if(audit!=null)scope.launch{while(isActive){delay(1000);audit.sample(mode)}} if(audit!=null)scope.launch{while(isActive){delay(1000);audit.sample(mode)}}
scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=(partOffset+player.bufferedPosition).coerceIn(0,duration);val d=player.duration;if(d>0&&parts.size==1)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!ended)report(if(preparing||loading)"buffering"else if(isPlaying)"playing"else "paused")}} scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=(partOffset+player.bufferedPosition).coerceIn(0,duration);val d=player.duration;if(d>0&&parts.size==1)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!preparing&&!ended)report(if(isPlaying)"playing"else "paused")}}
} }
/** Position on the title's timeline, across parts. */ /** Position on the title's timeline, across parts. */
private fun currentPosition() = (partOffset+player.currentPosition).coerceIn(0,duration.coerceAtLeast(0)) private fun currentPosition() = (partOffset+player.currentPosition).coerceIn(0,duration.coerceAtLeast(0))
private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))} private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))}
private fun stoppedByServer(termination:PlaybackTermination) {
if(closed||serverStopped)return
serverStopped=true
Log.i("KaleidoPlayback","TERMINATED item=${item.id} code=${termination.code} mode=$mode")
seekJob?.cancel();player.stop();loading=false
vm.playbackStoppedByServer(item,termination.message)
}
/** A failed stream may be one the server stopped: ask Plex before reconnecting, so a stopped session stays stopped. */
private suspend fun checkServerStopped(offset:Long):Boolean {
if(serverStopped)return true
if(!synced)return false
val termination=withTimeoutOrNull(3000){runCatching{api.timeline(item,offset,"buffering",duration,streamSession,server)}.getOrNull()} ?: return false
stoppedByServer(termination);return true
}
private fun fallback(reason:String) { private fun fallback(reason:String) {
if(closed||serverStopped||mode>=2||localValidationFile!=null||fallbackPending)return if(closed||mode>=2||localValidationFile!=null||fallbackPending)return
fallbackPending=true fallbackPending=true
val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady
scope.launch { scope.launch {
try {prepareMutex.withLock { try {prepareMutex.withLock {
if(!closed&&session==streamSession&&!checkServerStopped(offset)) { if(!closed&&session==streamSession) {
audit?.event("fallback",org.json.JSONObject().put("reason",reason).put("fromMode",mode).put("offset",offset)) audit?.event("fallback",org.json.JSONObject().put("reason",reason).put("fromMode",mode).put("offset",offset))
prepareInternal(mode+1,offset,resume) prepareInternal(mode+1,offset,resume)
} }
@ -214,14 +191,14 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) = prepareMutex.withLock{prepareInternal(newMode,offset,resume)} suspend fun prepare(newMode: Int,offset: Long,resume:Boolean=true) = prepareMutex.withLock{prepareInternal(newMode,offset,resume)}
private suspend fun prepareInternal(newMode: Int,offset: Long,resume:Boolean) { private suspend fun prepareInternal(newMode: Int,offset: Long,resume:Boolean) {
if(closed||serverStopped)return if(closed)return
preparing=true;loading=true;error=null;ended=false;nativeSelectionApplied=false preparing=true;loading=true;error=null;ended=false;nativeSelectionApplied=false
serverConverting=false;serverAudioConverting=false serverConverting=false;serverAudioConverting=false
// Empty track events from stop must not be mistaken for a missing video track. // Empty track events from stop must not be mistaken for a missing video track.
player.stop() player.stop()
selector.parameters=selector.buildUponParameters().clearOverrides().build() selector.parameters=selector.buildUponParameters().clearOverrides().build()
try { try {
if(mode>0)runCatching{api.stopTranscode(streamSession,server)} if(mode>0)runCatching{api.stopTranscode(streamSession)}
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset
partIndex=partFor(parts,offset) partIndex=partFor(parts,offset)
val partOffsetMs=(offset-partOffset).coerceAtLeast(0) val partOffsetMs=(offset-partOffset).coerceAtLeast(0)
@ -255,7 +232,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
// Plex HLS exposes the part's original timeline, including a seek-start offset: // Plex HLS exposes the part's original timeline, including a seek-start offset:
// never add the requested offset again. // never add the requested offset again.
player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume&&foreground;player.setPlaybackSpeed(playbackRate) player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate)
Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset part=${partIndex+1}/${parts.size} media=${mediaIndex+1}/${item.media.size} local=$local") Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset part=${partIndex+1}/${parts.size} media=${mediaIndex+1}/${item.media.size} local=$local")
}catch(e:CancellationException){throw e}catch(e:Exception){ }catch(e:CancellationException){throw e}catch(e:Exception){
audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status)) audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status))
@ -276,10 +253,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
/** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */ /** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */
fun scrubBy(delta:Long,settle:Long=650){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(settle);commitScrub()}} fun scrubBy(delta:Long,settle:Long=650){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(settle);commitScrub()}}
fun commitScrub(){val target=scrubPosition ?: return;scrubPosition=null;seekTo(target)} fun commitScrub(){val target=scrubPosition ?: return;scrubPosition=null;seekTo(target)}
fun pause(){player.pause();if(!preparing)position=currentPosition();report("paused")} fun pause(){player.pause();position=currentPosition();report("paused")}
/** The app left the foreground: pause, and keep any preparation still in flight paused. */
fun enterBackground(){foreground=false;pause()}
fun enterForeground(){foreground=true}
fun select(type:Int,groupIndex:Int,trackIndex:Int) { fun select(type:Int,groupIndex:Int,trackIndex:Int) {
val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build() val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build()
} }
@ -331,7 +305,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
} }
} }
} }
fun close(){if(closed)return;if(!preparing)position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()} fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()}
} }
/** The single playback quality preference: the original stream, then conversions from highest to lowest resolution. */ /** The single playback quality preference: the original stream, then conversions from highest to lowest resolution. */
enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) { enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) {

View file

@ -19,19 +19,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import androidx.compose.material3.Icon
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
@Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) { @Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) {
val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f) val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f)
@ -55,142 +43,49 @@ import androidx.compose.ui.input.key.type
internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toString().removeSuffix(".0")}×" internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toString().removeSuffix(".0")}×"
/** Where the playing video shrinks to while Up Next is open, on the 960 × 540 dp canvas. */ @Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,dismiss:()->Unit,next:()->Unit) {
internal object UpNextFrame {
val x=44.dp;val y=34.dp;val width=352.dp;val height=198.dp
}
/**
* Up Next's page beneath the player's surface: the next episode's artwork, top-right, fading into
* the page, and a black frame under the mini-player for letterboxed video. Drawn before the
* PlayerView, whose SurfaceView shows through only where nothing is drawn above it.
*/
@Composable internal fun UpNextBackdrop(vm:KaleidoViewModel,item:Title,modifier:Modifier) {
val upcoming=vm.followingEpisode(item)
val path=upcoming?.let{it.still.ifBlank{it.thumb}.ifBlank{it.art}} ?: item.art.ifBlank{item.thumb}
Box(modifier.fillMaxSize().background(Ink)) {
Box(Modifier.align(Alignment.TopEnd).width(640.dp).aspectRatio(16f/9f)) {
if(path.isNotBlank())Artwork(vm.api,path,Modifier.fillMaxSize(),960,540,animate=false)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(0f to Ink,.42f to Ink.copy(alpha=.72f),1f to Color.Transparent)))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(.35f to Color.Transparent,1f to Ink)))
}
Box(Modifier.offset(UpNextFrame.x,UpNextFrame.y).size(UpNextFrame.width,UpNextFrame.height).background(Color.Black))
}
}
/**
* Up Next, over the shrunken player: the next episode with one countdown, the season and related shows.
* Any remote press stops the countdown. Left from Play next (or Back) returns to the playing video.
*/
@Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,controller:PlaybackController,watchVideo:()->Unit,next:()->Unit) {
val upcoming=vm.followingEpisode(item) val upcoming=vm.followingEpisode(item)
// Settings › Playback sets the countdown; 0 turns autoplay off. // Settings › Playback sets the countdown; 0 turns autoplay off.
val countdown=if(vm.shuffling&&vm.autoplaySeconds==0)5 else vm.autoplaySeconds val countdown=if(vm.shuffling&&vm.autoplaySeconds==0)5 else vm.autoplaySeconds
var cancelled by remember{mutableStateOf(false)} var autoplay by remember{mutableStateOf(countdown>0)}
val counting=upcoming!=null&&countdown>0&&!cancelled var seconds by remember{mutableIntStateOf(countdown)}
var elapsed by remember{mutableLongStateOf(0)} LaunchedEffect(autoplay,upcoming?.id) {
// The countdown runs only while Kaleido is on screen; leaving it restarts on return. if(autoplay&&upcoming!=null&&countdown>0){seconds=countdown;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(countdown){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()}
val lifecycle by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
val onScreen=lifecycle.isAtLeast(Lifecycle.State.STARTED)
LaunchedEffect(counting,upcoming?.id,onScreen) {
if(!counting||!onScreen||upcoming==null)return@LaunchedEffect
val total=countdown*1000L;elapsed=0
android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}")
while(elapsed<total){delay(50);elapsed+=50}
android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()
} }
val playFocus=remember{FocusRequester()}
val videoFocus=remember{FocusRequester()}
LaunchedEffect(Unit){withFrameNanos{};runCatching{(if(upcoming!=null)playFocus else videoFocus).requestFocus()}}
val season=vm.episodeQueue.filter{it.parentId==item.parentId} val season=vm.episodeQueue.filter{it.parentId==item.parentId}
Box(Modifier.fillMaxSize().onPreviewKeyEvent{ LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) {
if(it.type==KeyEventType.KeyDown&&counting){cancelled=true;android.util.Log.i("KaleidoPlayback","AUTOPLAY cancelled item=${item.id}")} item {
false Text(if(vm.shuffling)"Up next · Shuffle"else if(upcoming!=null)"Up next"else "More to watch",color=Accent,fontSize=25.sp,fontWeight=FontWeight.SemiBold)
}) { Row(Modifier.padding(top=13.dp),horizontalArrangement=Arrangement.spacedBy(20.dp),verticalAlignment=Alignment.CenterVertically) {
// The video itself is the PlayerView beneath; this is its focus target and outline. if(upcoming!=null)Artwork(vm.api,upcoming.still.ifBlank{upcoming.thumb},Modifier.width(205.dp).aspectRatio(16f/9f).clip(RoundedCornerShape(5.dp)),480,270,animate=false)
var videoFocused by remember{mutableStateOf(false)} Column(Modifier.weight(1f)) {
Box(Modifier.offset(UpNextFrame.x-4.dp,UpNextFrame.y-4.dp).size(UpNextFrame.width+8.dp,UpNextFrame.height+8.dp) Text(upcoming?.displayTitle ?: item.displayTitle,color=Accent,fontSize=21.sp,fontWeight=FontWeight.SemiBold)
.focusRequester(videoFocus).focusProperties{right=if(upcoming!=null)playFocus else FocusRequester.Default} Text(upcoming?.let{"S${it.parentIndex} · E${it.index} ${it.title}"} ?: "You've reached the end of this series.",color=Cinema.secondary,fontSize=12.sp,modifier=Modifier.padding(top=5.dp,bottom=15.dp))
.navigationSound().onFocusChanged{videoFocused=it.isFocused} Row(horizontalArrangement=Arrangement.spacedBy(10.dp),verticalAlignment=Alignment.CenterVertically) {
.border(if(videoFocused)2.dp else 1.dp,Color.White.copy(alpha=if(videoFocused)1f else .16f),RoundedCornerShape(8.dp)) if(upcoming!=null)ActionButton(if(vm.transitioningEpisode)"Loading…"else if(autoplay)"Play in $seconds"else "Play now",Icons.Filled.PlayArrow,modifier=Modifier.onFocusChanged{if(it.isFocused&&BuildConfig.DEBUG)android.util.Log.i("KaleidoPlayback","POSTPLAY focus=play")},primary=true,initialFocus=true){autoplay=false;next()}
.semantics{contentDescription="Return to "+item.displayTitle}.clickable(onClick=watchVideo)) if(upcoming!=null&&countdown>0)TvButton(if(autoplay)"Cancel autoplay"else "Autoplay off"){autoplay=!autoplay;android.util.Log.i("KaleidoPlayback","AUTOPLAY ${if(autoplay)"enabled"else "cancelled"} item=${item.id}")}
NowPlaying(item,controller,videoFocused,Modifier.offset(UpNextFrame.x,UpNextFrame.y+UpNextFrame.height+10.dp).width(UpNextFrame.width)) TvButton("Back to video"){autoplay=false;dismiss()}
Column(Modifier.padding(start=UpNextFrame.x+UpNextFrame.width+36.dp,top=36.dp,end=Cinema.gutter)) {
Eyebrow(if(upcoming==null)"More to watch"else if(vm.shuffling)"Up next · Shuffle"else "Up next")
Spacer(Modifier.height(8.dp))
// The playing episode carries its show's title art; listed episodes may not.
TitleIdentity(vm.api,item,Modifier.size(240.dp,44.dp))
if(upcoming!=null) {
val metadata by produceState(upcoming,upcoming.id){value=upcoming;value=vm.previewDetails(upcoming)}
Text(upcoming.title,color=Accent,fontSize=21.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=6.dp))
Row(Modifier.padding(top=6.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(metadata.contentRating.isNotBlank())FormatBadge(metadata.contentRating,Modifier.padding(end=8.dp))
Text(listOf("S${upcoming.parentIndex} · E${upcoming.index}",if(upcoming.duration>0)runtimeLabel(upcoming.duration)else "").filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1)
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
if(metadata.summary.isNotBlank())Text(metadata.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=8.dp))
UpNextButton(if(vm.transitioningEpisode)"Loading…"else "Play next episode",if(counting)({(elapsed.toFloat()/(countdown*1000)).coerceIn(0f,1f)})else null,
Modifier.padding(top=14.dp).focusRequester(playFocus).focusProperties{left=videoFocus}.onFocusChanged{if(it.isFocused&&BuildConfig.DEBUG)android.util.Log.i("KaleidoPlayback","POSTPLAY focus=play")}) {
cancelled=true;next()
} }
} }
else Text("You've reached the end of this series.",color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=8.dp))
} }
LazyColumn(Modifier.fillMaxWidth().padding(top=292.dp),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=24.dp),verticalArrangement=Arrangement.spacedBy(14.dp)) {
val up=if(upcoming!=null)playFocus else videoFocus
if(season.isNotEmpty())item {
val current=season.indexOfFirst{it.id==item.id}
PostPlayRail(vm,if(item.parentIndex>0)"Season ${item.parentIndex}"else "Episodes",season,up,(current-1).coerceAtLeast(0),{when(it.id){item.id->"Now playing";upcoming?.id->"Up next";else->if(it.duration>0)runtimeLabel(it.duration)else ""}}){vm.play(it,true)}
}
if(vm.relatedShows.isNotEmpty())item {PostPlayRail(vm,"Related shows",vm.relatedShows,if(season.isEmpty())up else null,0,{it.year}){vm.stopPlayback();vm.open(it)}}
} }
if(season.isNotEmpty())item {PostPlayRail(vm,"Episodes in this season",season){autoplay=false;vm.play(it,true)}}
if(vm.relatedShows.isNotEmpty())item {PostPlayRail(vm,"Related shows",vm.relatedShows){autoplay=false;vm.stopPlayback();vm.open(it)}}
} }
} }
/** Where the playing episode is, under the mini-player. Its own scope: position ticks recompose only this. */ @Composable private fun PostPlayRail(vm:KaleidoViewModel,label:String,titles:List<Title>,choose:(Title)->Unit) {
@Composable private fun NowPlaying(item:Title,controller:PlaybackController,focused:Boolean,modifier:Modifier) {
Column(modifier) {
Row(verticalAlignment=Alignment.CenterVertically) {
Text((if(item.type=="episode")"S${item.parentIndex} · E${item.index} "else "")+item.title,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f))
Text("−"+clockTime(controller.duration-controller.position),color=Cinema.quiet,fontSize=10.sp,lineHeight=14.sp,maxLines=1,modifier=Modifier.padding(start=10.dp))
}
val progress=if(controller.duration>0)(controller.position.toFloat()/controller.duration).coerceIn(0f,1f)else 0f
Box(Modifier.padding(top=6.dp).fillMaxWidth().height(3.dp).clip(RoundedCornerShape(2.dp)).background(Color.White.copy(alpha=.22f))) {
Box(Modifier.fillMaxHeight().fillMaxWidth(progress).background(Accent))
}
}
}
/** Play next episode. While autoplay counts down ([progress] non-null) a lighter fill sweeps across it, without numbers. */
@Composable private fun UpNextButton(label:String,progress:(()->Float)?,modifier:Modifier,onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val shape=RoundedCornerShape(5.dp)
val foreground=if(focused)Ink else Accent
Row(modifier.height(34.dp).navigationSound().onFocusChanged{focused=it.isFocused}.clip(shape)
.drawBehind{
val fill=progress?.invoke()
drawRect(if(focused)(if(fill!=null)Color(0xFFBDBDBD)else Accent)else Color.White.copy(alpha=.16f))
if(fill!=null)drawRect(if(focused)Accent else Color.White.copy(alpha=.18f),size=androidx.compose.ui.geometry.Size(size.width*fill,size.height))
}
.semantics{contentDescription=label}.clickable(onClick=onClick).padding(horizontal=14.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
Icon(Icons.Filled.PlayArrow,null,tint=foreground,modifier=Modifier.size(17.dp))
Text(label,color=foreground,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.SemiBold)
}
}
@Composable private fun PostPlayRail(vm:KaleidoViewModel,label:String,titles:List<Title>,up:FocusRequester?,start:Int,caption:(Title)->String,choose:(Title)->Unit) {
Column { Column {
Text(label,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp)) Text(label,color=Accent,fontSize=16.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=8.dp))
LazyRow(state=rememberLazyListState(start),horizontalArrangement=Arrangement.spacedBy(12.dp)) { LazyRow(horizontalArrangement=Arrangement.spacedBy(12.dp)) {
items(titles,key={it.id}){title-> items(titles,key={it.id}){title->
var focused by remember{mutableStateOf(false)} var focused by remember{mutableStateOf(false)}
Column(Modifier.width(188.dp).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier).navigationSound().onFocusChanged{focused=it.isFocused}.semantics{contentDescription=title.displayTitle+" "+title.subtitle}.clickable{choose(title)}) { Column(Modifier.width(167.dp).navigationSound().onFocusChanged{focused=it.isFocused}.semantics{contentDescription=title.displayTitle+" "+title.subtitle}.clickable{choose(title)}) {
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(6.dp))) { Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).clip(RoundedCornerShape(4.dp))) {
Artwork(vm.api,if(title.type=="episode")title.still.ifBlank{title.thumb}else title.art.ifBlank{title.thumb},Modifier.fillMaxSize(),384,216,animate=false) Artwork(vm.api,if(title.type=="episode")title.still.ifBlank{title.thumb}else title.art.ifBlank{title.thumb},Modifier.fillMaxSize(),384,216,animate=false)
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(6.dp))) if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(4.dp)))
} }
Text(if(title.type=="episode")"${title.index}. ${title.title}"else title.title,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp)) Text(if(title.type=="episode")"${title.index}. ${title.title}"else title.title,color=if(focused)Accent else Cinema.secondary,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=4.dp))
Text(caption(title),color=Cinema.quiet,fontSize=10.sp,lineHeight=14.sp,maxLines=1)
} }
} }
} }

View file

@ -28,14 +28,11 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.focus.* import androidx.compose.ui.focus.*
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.layout
import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.input.key.* import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
@ -100,61 +97,32 @@ import kotlinx.coroutines.delay
// Derived: the player only recomposes when a marker starts or ends, not on every position tick. // Derived: the player only recomposes when a marker starts or ends, not on every position tick.
val marker by remember{derivedStateOf{item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}}} val marker by remember{derivedStateOf{item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}}}
fun skip(marker:Marker){ fun skip(marker:Marker){
// Episodes go to Up Next, where the credits keep playing in the corner. if(marker.type=="credits"&&item.type=="episode"){controller.pause();android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true}
if(marker.type=="credits"&&item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true}
else controller.seekTo(marker.end) else controller.seekTo(marker.end)
} }
// Each marker counts down to an automatic skip once, so seeking back into it plays it. // Each marker is skipped automatically once, so seeking back into it plays it.
// The countdown runs only while playing; any remote press cancels it (OK on the button skips now).
val autoSkipped=remember{mutableSetOf<Marker>()} val autoSkipped=remember{mutableSetOf<Marker>()}
var autoSkip by remember{mutableStateOf<Marker?>(null)} LaunchedEffect(marker,controller.loading) {
var autoSkipTotal by remember{mutableLongStateOf(0)} val m=marker ?: return@LaunchedEffect
var autoSkipRemaining by remember{mutableLongStateOf(0)} if(controller.loading||postPlay||m in autoSkipped)return@LaunchedEffect
fun cancelAutoSkip(){val m=autoSkip ?: return;autoSkipped+=m;autoSkip=null;android.util.Log.i("KaleidoPlayback","AUTOSKIP cancelled ${m.type} item=${item.id}")} if(m.type=="intro"&&vm.autoSkipIntro||m.type=="credits"&&vm.autoSkipCredits){autoSkipped+=m;android.util.Log.i("KaleidoPlayback","AUTOSKIP ${m.type} item=${item.id}");skip(m)}
LaunchedEffect(marker,controller.loading,postPlay) {
val m=marker
if(m==null||controller.loading||postPlay||m in autoSkipped){if(m==null||postPlay)autoSkip=null;return@LaunchedEffect}
val seconds=when(m.type){"intro"->vm.autoSkipIntroSeconds;"credits"->vm.autoSkipCreditsSeconds;else->0}
if(seconds<=0)return@LaunchedEffect
// Up Next has the one countdown (to the next episode), so automatic credits open it at once.
if(m.type=="credits"&&item.type=="episode"){autoSkipped+=m;android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=credits");postPlay=true;return@LaunchedEffect}
if(autoSkip!=m){autoSkip=m;autoSkipTotal=seconds*1000L;autoSkipRemaining=autoSkipTotal;android.util.Log.i("KaleidoPlayback","AUTOSKIP countdown ${m.type} seconds=$seconds item=${item.id}")}
while(autoSkipRemaining>0){delay(50);if(autoSkip!=m)return@LaunchedEffect;if(controller.isPlaying)autoSkipRemaining-=50}
if(autoSkip!=m)return@LaunchedEffect
autoSkipped+=m;autoSkip=null;android.util.Log.i("KaleidoPlayback","AUTOSKIP ${m.type} item=${item.id}");skip(m)
} }
DisposableEffect(controller) { DisposableEffect(controller) {
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val observer=LifecycleEventObserver{_,event->when(event){Lifecycle.Event.ON_STOP->controller.enterBackground();Lifecycle.Event.ON_START->controller.enterForeground();else->{}}} val observer=LifecycleEventObserver{_,event->if(event==Lifecycle.Event.ON_STOP)controller.pause()}
owner.lifecycle.addObserver(observer) owner.lifecycle.addObserver(observer)
// Created while already stopped (e.g. a next episode loading behind Home): start paused.
if(!owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))controller.enterBackground()
onDispose{owner.lifecycle.removeObserver(observer);activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);controller.close()} onDispose{owner.lifecycle.removeObserver(observer);activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);controller.close()}
} }
// Up Next owns focus while open: hiding the controls behind it must not take focus back. LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu) {
LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu,postPlay) { if(controls&&controller.isPlaying&&trackMenu==0){delay(5000);controls=false}
if(controls&&controller.isPlaying&&trackMenu==0&&!postPlay){delay(5000);controls=false}
} }
LaunchedEffect(controls) {if(!controls&&!postPlay){timelineReveal=false;delay(210);if(!postPlay)runCatching{rootFocus.requestFocus()}}} LaunchedEffect(controls) {if(!controls){timelineReveal=false;delay(210);runCatching{rootFocus.requestFocus()}}}
LaunchedEffect(seekFocus,controls) {if(seekFocus&&controls){delay(220);runCatching{timelineFocus.requestFocus()};timelineReveal=true;seekFocus=false}} LaunchedEffect(seekFocus,controls) {if(seekFocus&&controls){delay(220);runCatching{timelineFocus.requestFocus()};timelineReveal=true;seekFocus=false}}
LaunchedEffect(restoreMenuFocus,trackMenu) {if(restoreMenuFocus!=0&&trackMenu==0){delay(16);runCatching{(when(restoreMenuFocus){1->audioFocus;2->subtitleFocus;else->optionsFocus}).requestFocus()};restoreMenuFocus=0}} LaunchedEffect(restoreMenuFocus,trackMenu) {if(restoreMenuFocus!=0&&trackMenu==0){delay(16);runCatching{(when(restoreMenuFocus){1->audioFocus;2->subtitleFocus;else->optionsFocus}).requestFocus()};restoreMenuFocus=0}}
// Leaving Up Next returns to the full-screen video without revealing the controls. fun goBack(){if(postPlay)postPlay=false else if(trackMenu!=0)closeTracks()else if(controls)controls=false else vm.stopPlayback()}
var refocusRoot by remember{mutableIntStateOf(0)}
LaunchedEffect(refocusRoot){if(refocusRoot>0){withFrameNanos{};runCatching{rootFocus.requestFocus()}}}
fun leaveUpNext(){postPlay=false;controls=false;refocusRoot++;android.util.Log.i("KaleidoPlayback","POSTPLAY closed item=${item.id}")}
// The video shrinks into Up Next's corner and grows back; only its layout reads the animation.
val upNext=androidx.compose.animation.core.animateFloatAsState(if(postPlay)1f else 0f,tween(320),label="upNext")
fun goBack(){if(postPlay)leaveUpNext() else if(trackMenu!=0)closeTracks()else if(controls)controls=false else vm.stopPlayback()}
BackHandler(onBack=::goBack) BackHandler(onBack=::goBack)
val visible=controls&&!postPlay val visible=controls&&!postPlay
Box(Modifier.fillMaxSize().background(Color.Black).focusRequester(rootFocus).onPreviewKeyEvent{event-> Box(Modifier.fillMaxSize().background(Color.Black).focusRequester(rootFocus).onPreviewKeyEvent{event->
// A pending automatic skip yields to the remote. Back only cancels it; OK on a hidden
// player still takes the Skip button, which skips now.
val okHidden=!visible&&event.nativeKeyEvent.keyCode in listOf(android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER)
if(autoSkip!=null&&event.type==KeyEventType.KeyDown&&!okHidden&&!postPlay){
cancelAutoSkip()
if(event.key==Key.Back)return@onPreviewKeyEvent true
}
if(event.key==Key.Back){if(event.type==KeyEventType.KeyDown)goBack();true} if(event.key==Key.Back){if(event.type==KeyEventType.KeyDown)goBack();true}
else if(event.type!=KeyEventType.KeyDown||postPlay)false else { else if(event.type!=KeyEventType.KeyDown||postPlay)false else {
interacted() interacted()
@ -165,7 +133,7 @@ import kotlinx.coroutines.delay
android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD->{controller.seekTo(controller.position+30000);controls=true;seekFocus=true;true} android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD->{controller.seekTo(controller.position+30000);controls=true;seekFocus=true;true}
android.view.KeyEvent.KEYCODE_MEDIA_REWIND->{controller.seekTo(controller.position-10000);controls=true;seekFocus=true;true} android.view.KeyEvent.KEYCODE_MEDIA_REWIND->{controller.seekTo(controller.position-10000);controls=true;seekFocus=true;true}
// With the controls hidden, OK takes a visible Skip intro/credits; otherwise it reveals them. // With the controls hidden, OK takes a visible Skip intro/credits; otherwise it reveals them.
android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){marker?.let{autoSkip=null;autoSkipped+=it;skip(it)} ?: run{controls=true};true}else false} android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){marker?.let(::skip) ?: run{controls=true};true}else false}
android.view.KeyEvent.KEYCODE_DPAD_LEFT,android.view.KeyEvent.KEYCODE_DPAD_RIGHT->{ android.view.KeyEvent.KEYCODE_DPAD_LEFT,android.view.KeyEvent.KEYCODE_DPAD_RIGHT->{
val delta=if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000L else 10000L val delta=if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000L else 10000L
when { when {
@ -181,7 +149,6 @@ import kotlinx.coroutines.delay
} }
} }
}.focusable()) { }.focusable()) {
if(postPlay)UpNextBackdrop(vm,item,Modifier.graphicsLayer{alpha=upNext.value})
AndroidView(factory={context->PlayerView(context).apply { AndroidView(factory={context->PlayerView(context).apply {
setEnableComposeSurfaceSyncWorkaround(true) setEnableComposeSurfaceSyncWorkaround(true)
player=controller.player player=controller.player
@ -190,14 +157,8 @@ import kotlinx.coroutines.delay
descendantFocusability=ViewGroup.FOCUS_BLOCK_DESCENDANTS descendantFocusability=ViewGroup.FOCUS_BLOCK_DESCENDANTS
setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER) setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)
setKeepContentOnPlayerReset(true) setKeepContentOnPlayerReset(true)
}},update={view->view.subtitleView?.let{applySubtitleStyle(it,vm.subtitleSize,vm.subtitleStyle)}},modifier=Modifier.fillMaxSize().layout{measurable,constraints-> }},update={view->view.subtitleView?.let{applySubtitleStyle(it,vm.subtitleSize,vm.subtitleStyle)}},modifier=Modifier.fillMaxSize(),onRelease={it.player=null})
val f=upNext.value if(controller.loading)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp))
fun lerp(a:Int,b:Int)=(a+(b-a)*f).toInt()
val width=lerp(constraints.maxWidth,UpNextFrame.width.roundToPx());val height=lerp(constraints.maxHeight,UpNextFrame.height.roundToPx())
val placeable=measurable.measure(androidx.compose.ui.unit.Constraints.fixed(width,height))
layout(constraints.maxWidth,constraints.maxHeight){placeable.place(lerp(0,UpNextFrame.x.roundToPx()),lerp(0,UpNextFrame.y.roundToPx()))}
},onRelease={it.player=null})
if(controller.loading&&!postPlay)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp))
QuickSkipFeedback(skipSeconds,skipPulse,!visible&&!postPlay,Modifier.align(if(skipForward)Alignment.CenterEnd else Alignment.CenterStart).padding(horizontal=32.dp)) QuickSkipFeedback(skipSeconds,skipPulse,!visible&&!postPlay,Modifier.align(if(skipForward)Alignment.CenterEnd else Alignment.CenterStart).padding(horizontal=32.dp))
AnimatedVisibility(visible=visible,enter=fadeIn(tween(190))+slideInVertically(tween(190)){it/8},exit=fadeOut(tween(190))+slideOutVertically(tween(190)){it/10},modifier=Modifier.align(Alignment.BottomCenter)) { AnimatedVisibility(visible=visible,enter=fadeIn(tween(190))+slideInVertically(tween(190)){it/8},exit=fadeOut(tween(190))+slideOutVertically(tween(190)){it/10},modifier=Modifier.align(Alignment.BottomCenter)) {
Column(Modifier.fillMaxWidth().background(Brush.verticalGradient(0f to Color.Transparent,.35f to Color.Black.copy(alpha=.5f),1f to Color.Black.copy(alpha=.85f))).padding(start=Cinema.gutter,end=Cinema.gutter,top=48.dp,bottom=16.dp)) { Column(Modifier.fillMaxWidth().background(Brush.verticalGradient(0f to Color.Transparent,.35f to Color.Black.copy(alpha=.5f),1f to Color.Black.copy(alpha=.85f))).padding(start=Cinema.gutter,end=Cinema.gutter,top=48.dp,bottom=16.dp)) {
@ -214,44 +175,31 @@ import kotlinx.coroutines.delay
Spacer(Modifier.width(18.dp)) Spacer(Modifier.width(18.dp))
Text(controller.qualityLabel,color=Color.White.copy(alpha=.6f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=360.dp)) Text(controller.qualityLabel,color=Color.White.copy(alpha=.6f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=360.dp))
} }
// Elapsed and remaining time sit at the timeline's ends and follow a pending scrub. SeekTimeline(controller,item,Modifier.fillMaxWidth().focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted)
val shownPosition=controller.scrubPosition ?: controller.position Box(Modifier.fillMaxWidth().height(40.dp)) {
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) { Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
Text(clockTime(shownPosition),color=Color.White.copy(alpha=.82f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,modifier=Modifier.width(58.dp)) IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=30.dp,iconSize=18.dp,onFocused=::interacted){vm.stopPlayback()}
SeekTimeline(controller,item,Modifier.weight(1f).focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted) Text(clockTime(controller.position),color=Color.White.copy(alpha=.78f),fontSize=10.sp,lineHeight=14.sp)
Text("−"+clockTime(controller.duration-shownPosition),color=Color.White.copy(alpha=.62f),fontSize=10.sp,lineHeight=14.sp,maxLines=1,textAlign=TextAlign.End,modifier=Modifier.width(58.dp))
} }
Box(Modifier.fillMaxWidth().padding(top=6.dp).height(48.dp)) { Row(Modifier.align(Alignment.Center),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(16.dp)) {
Row(Modifier.align(Alignment.CenterStart),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) { IconControl(Icons.Outlined.Replay10,"Back 10 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position-10000);interacted()}
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Exit playback",size=32.dp,iconSize=19.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){vm.stopPlayback()} IconControl(if(controller.isPlaying)Icons.Filled.Pause else Icons.Filled.PlayArrow,if(controller.isPlaying)"Pause"else "Play",size=38.dp,iconSize=28.dp,requester=playFocus,initialFocus=controls&&!seekFocus&&!timelineReveal,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.toggle();controls=true;interacted()}
Text("Ends "+endsAt(controller),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,maxLines=1) IconControl(Icons.Outlined.Forward30,"Forward 30 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position+30000);interacted()}
}
// Transport: episodes step between neighbours around the seek and play controls.
// An absent previous episode keeps its space, so Play stays centred.
Row(Modifier.align(Alignment.Center),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(14.dp)) {
val up=Modifier.focusProperties{up=timelineFocus}
if(item.type=="episode") {
if(vm.mayHavePrecedingEpisode(item))IconControl(Icons.Outlined.SkipPrevious,"Previous episode",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){vm.previousEpisode(item);interacted()}
else Spacer(Modifier.size(34.dp))
}
IconControl(Icons.Outlined.Replay10,"Back 10 seconds",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){controller.seekTo(controller.position-10000);interacted()}
IconControl(if(controller.isPlaying)Icons.Filled.Pause else Icons.Filled.PlayArrow,if(controller.isPlaying)"Pause"else "Play",size=46.dp,iconSize=30.dp,requester=playFocus,selected=true,initialFocus=controls&&!seekFocus&&!timelineReveal,modifier=up,onFocused=::interacted){controller.toggle();controls=true;interacted()}
IconControl(Icons.Outlined.Forward30,"Forward 30 seconds",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){controller.seekTo(controller.position+30000);interacted()}
if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=34.dp,iconSize=22.dp,modifier=up,onFocused=::interacted){vm.nextEpisode(item);interacted()}
} }
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) { Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) {
IconControl(Icons.AutoMirrored.Outlined.VolumeUp,"Audio tracks",size=32.dp,iconSize=20.dp,requester=audioFocus,selected=trackMenu==1,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=1;interacted()} Text("−"+clockTime(controller.duration-controller.position)+" · Ends "+endsAt(controller),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(end=8.dp))
IconControl(Icons.Outlined.Subtitles,"Subtitles",size=32.dp,iconSize=20.dp,requester=subtitleFocus,selected=trackMenu==2,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=2;interacted()} if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=30.dp,iconSize=21.dp,onFocused=::interacted){vm.nextEpisode(item)}
IconControl(Icons.Outlined.Settings,"Playback options",size=32.dp,iconSize=20.dp,requester=optionsFocus,selected=trackMenu>=3,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=3;interacted()} IconControl(Icons.AutoMirrored.Outlined.VolumeUp,"Audio tracks",size=30.dp,iconSize=21.dp,requester=audioFocus,selected=trackMenu==1,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=1;interacted()}
IconControl(Icons.Outlined.Subtitles,"Subtitles",size=30.dp,iconSize=21.dp,requester=subtitleFocus,selected=trackMenu==2,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=2;interacted()}
IconControl(Icons.Outlined.Settings,"Playback options",size=30.dp,iconSize=21.dp,requester=optionsFocus,selected=trackMenu>=3,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=3;interacted()}
} }
} }
} }
} }
marker?.let{marker->if(!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)146.dp else 45.dp)) { marker?.let{marker->if(!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)130.dp else 45.dp)) {
val counting=autoSkip==marker&&autoSkipTotal>0 ActionButton(if(marker.type=="intro")"Skip intro"else "Skip credits",Icons.Outlined.ChevronRight,modifier=Modifier.background(Color.Black.copy(alpha=.9f),RoundedCornerShape(5.dp)).border(1.dp,Color.White.copy(alpha=.75f),RoundedCornerShape(5.dp))){skip(marker);interacted()}
SkipMarkerButton(marker.type=="intro",if(counting)1f-(autoSkipRemaining.toFloat()/autoSkipTotal).coerceIn(0f,1f)else null){autoSkip=null;autoSkipped+=marker;skip(marker);interacted()}
}} }}
if(postPlay)PostPlayScreen(vm,item,controller,::leaveUpNext){vm.nextEpisode(item)} if(postPlay)PostPlayScreen(vm,item,{postPlay=false;controls=true},{vm.nextEpisode(item)})
controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})} controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})}
if(trackMenu==1)AudioTrackPanel(controller,::closeTracks,::closeTracks) if(trackMenu==1)AudioTrackPanel(controller,::closeTracks,::closeTracks)
if(trackMenu==2) { if(trackMenu==2) {
@ -270,27 +218,6 @@ import kotlinx.coroutines.delay
} }
} }
/**
* Skip intro/credits. While an automatic skip is pending ([progress] non-null) it reads
* "Skipping intro" and a lighter fill sweeps across it until the skip happens, without numbers.
*/
@Composable private fun SkipMarkerButton(intro:Boolean,progress:Float?,onClick:()->Unit) {
var focused by remember{mutableStateOf(false)}
val shape=RoundedCornerShape(6.dp)
val label=if(progress!=null)(if(intro)"Skipping intro"else "Skipping credits")else if(intro)"Skip intro"else "Skip credits"
val foreground=if(focused)Ink else Accent
Row(Modifier.height(36.dp).navigationSound().onFocusChanged{focused=it.isFocused}.clip(shape)
.drawBehind{
drawRect(if(focused)Accent else Color(0xE6181818))
if(progress!=null&&!focused)drawRect(Color.White.copy(alpha=.2f),size=androidx.compose.ui.geometry.Size(size.width*progress,size.height))
}
.border(1.dp,Color.White.copy(alpha=if(focused)0f else .55f),shape).semantics{contentDescription=label}
.clickable(onClick=onClick).padding(horizontal=16.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) {
Text(label,color=foreground,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.SemiBold)
Icon(Icons.Filled.SkipNext,null,tint=foreground,modifier=Modifier.size(17.dp))
}
}
/** The same track selector is reachable from the speaker and from Playback options. */ /** The same track selector is reachable from the speaker and from Playback options. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable internal fun AudioTrackPanel(controller:PlaybackController,dismiss:()->Unit,close:()->Unit) { @Composable internal fun AudioTrackPanel(controller:PlaybackController,dismiss:()->Unit,close:()->Unit) {

View file

@ -1,13 +1,10 @@
package tv.kaleido.app package tv.kaleido.app
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import okhttp3.FormBody import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
@ -18,10 +15,6 @@ import java.io.IOException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
class PlexException(message: String, val status: Int = 0): IOException(message) class PlexException(message: String, val status: Int = 0): IOException(message)
/** Plex's timeline answer after the server ends a playback session. */
data class PlaybackTermination(val code: Int, val reason: String) {
val message get() = listOf("The server stopped this stream.", reason.trim()).filter { it.isNotBlank() }.joinToString("\n\n")
}
class PlexApi(val clientId: String) { class PlexApi(val clientId: String) {
val http = OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).addNetworkInterceptor { chain -> val http = OkHttpClient.Builder().connectTimeout(10,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).addNetworkInterceptor { chain ->
val original=chain.call().request().url;val current=chain.request().url val original=chain.call().request().url;val current=chain.request().url
@ -34,24 +27,16 @@ class PlexApi(val clientId: String) {
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV");put("X-Plex-Device-Name","Kaleido TV") put("X-Plex-Client-Identifier",clientId);put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV");put("X-Plex-Device-Name","Kaleido TV")
if(!token.isNullOrBlank()) put("X-Plex-Token",token) if(!token.isNullOrBlank()) put("X-Plex-Token",token)
} }
suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = coroutineScope { suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = withContext(Dispatchers.IO) {
val req=Request.Builder().url(url).apply { headers(token).forEach { (k,v) -> header(k,v) }; if(method!="GET") method(method,FormBody.Builder().apply { form.forEach { (k,v)->add(k,v) } }.build()) }.build() val req=Request.Builder().url(url).apply { headers(token).forEach { (k,v) -> header(k,v) }; if(method!="GET") method(method,FormBody.Builder().apply { form.forEach { (k,v)->add(k,v) } }.build()) }.build()
val call=http.newCall(req) http.newCall(req).execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" }
// execute() blocks until the server answers; a cancelled caller (a timeout, a replaced load) aborts the call.
val abort=launch(start=CoroutineStart.UNDISPATCHED){try{awaitCancellation()}finally{call.cancel()}}
try {
withContext(Dispatchers.IO) {
call.execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" }
} }
} finally { abort.cancel() } fun url(path: String, params: Map<String,String> = emptyMap()): String {
} val s=session ?: throw PlexException("Choose a Plex server first.")
/** [server] pins a request to one server; by default it follows the current session. */
fun url(path: String, params: Map<String,String> = emptyMap(), server: Session? = session): String {
val s=server ?: throw PlexException("Choose a Plex server first.")
require(!path.startsWith("http")) { "Expected a server-relative Plex path" } require(!path.startsWith("http")) { "Expected a server-relative Plex path" }
return (s.server.trimEnd('/')+"/"+path.trimStart('/')).toHttpUrl().newBuilder().apply { params.forEach { (k,v)->addQueryParameter(k,v) } }.build().toString() return (s.server.trimEnd('/')+"/"+path.trimStart('/')).toHttpUrl().newBuilder().apply { params.forEach { (k,v)->addQueryParameter(k,v) } }.build().toString()
} }
suspend fun container(path: String, params: Map<String,String> = emptyMap(), server: Session? = session): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params,server),server?.serverToken).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()} suspend fun container(path: String, params: Map<String,String> = emptyMap()): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params)).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()}
suspend fun validate(s: Session): Session { suspend fun validate(s: Session): Session {
val j=JSONObject(request(s.server.trimEnd('/')+"/",s.serverToken)).getJSONObject("MediaContainer") val j=JSONObject(request(s.server.trimEnd('/')+"/",s.serverToken)).getJSONObject("MediaContainer")
if(j.optString("machineIdentifier").isBlank()) throw PlexException("This address is not a Plex Media Server.") if(j.optString("machineIdentifier").isBlank()) throw PlexException("This address is not a Plex Media Server.")
@ -70,12 +55,9 @@ class PlexApi(val clientId: String) {
// Try TLS connections first; local HTTP remains available for servers without TLS. // Try TLS connections first; local HTTP remains available for servers without TLS.
var last: Throwable? = null var last: Throwable? = null
for (group in server.connections.partition { it.startsWith("https://") }.toList()) { for (group in server.connections.partition { it.startsWith("https://") }.toList()) {
// Probe together, but accept in preference order (local first, relay last): the best val results=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }.awaitAll()
// answering address wins without waiting for slower, less preferred probes to time out. results.firstOrNull { it.isSuccess }?.getOrNull()?.let { return@coroutineScope it }
val attempts=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } } last=results.lastOrNull()?.exceptionOrNull() ?: last
try {
for (attempt in attempts) attempt.await().onSuccess { return@coroutineScope it }.onFailure { last=it }
} finally { attempts.forEach { it.cancel() } }
} }
throw PlexException("Cannot reach ${server.name}. Check that the server is online and reachable from this TV.") throw PlexException("Cannot reach ${server.name}. Check that the server is online and reachable from this TV.")
} }
@ -87,12 +69,6 @@ class PlexApi(val clientId: String) {
suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse),it.optString("key"),it.opt("more").let{v->v==true||v==1||v=="1"||v=="true"}) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }} suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse),it.optString("key"),it.opt("more").let{v->v==true||v==1||v=="1"||v=="true"}) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }}
/** A hub's complete list, for "View all". Plex keys may already carry query parameters. */ /** A hub's complete list, for "View all". Plex keys may already carry query parameters. */
suspend fun hubItems(key:String):List<Title> = withContext(Dispatchers.Default){container(key,mapOf("X-Plex-Container-Start" to "0","X-Plex-Container-Size" to "500","includeExternalMetadata" to "1")).optJSONArray("Metadata").objects().map(Title::parse)} suspend fun hubItems(key:String):List<Title> = withContext(Dispatchers.Default){container(key,mapOf("X-Plex-Container-Start" to "0","X-Plex-Container-Size" to "500","includeExternalMetadata" to "1")).optJSONArray("Metadata").objects().map(Title::parse)}
/**
* Continue Watching as a fingerprint. Watching on another device changes it without changing the
* library revision above: new, finished or reordered titles at once, progress in 5% steps (so
* a title playing elsewhere doesn't rebuild Home on every poll).
*/
suspend fun continueWatchingRevision():String = continueWatchingFingerprint(container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects())
suspend fun onDeck(): List<Title> = container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects().map(Title::parse) suspend fun onDeck(): List<Title> = container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects().map(Title::parse)
suspend fun recentSeasons(section:String):List<Title> = withContext(Dispatchers.Default){ suspend fun recentSeasons(section:String):List<Title> = withContext(Dispatchers.Default){
// Fetch beyond the display limit so one large series import doesn't fill the row. // Fetch beyond the display limit so one large series import doesn't fill the row.
@ -151,11 +127,9 @@ class PlexApi(val clientId: String) {
} }
/** Removes an in-progress title from Continue Watching without changing its watched state. */ /** Removes an in-progress title from Continue Watching without changing its watched state. */
suspend fun removeFromContinueWatching(item:Title){request(url("/actions/removeFromContinueWatching",mapOf("ratingKey" to item.id)),method="PUT")} suspend fun removeFromContinueWatching(item:Title){request(url("/actions/removeFromContinueWatching",mapOf("ratingKey" to item.id)),method="PUT")}
suspend fun watched(item: Title, watched: Boolean, server: Session? = session) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library"),server) } suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }
/** Reports progress; a stream the server stopped (Plex dashboard "Stop", or shutdown) comes back as a termination. */ suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String) {
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String, server: Session? = session): PlaybackTermination? { container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId))
val c=container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId),server)
return if(c.has("terminationCode"))PlaybackTermination(c.optInt("terminationCode",-1),c.optString("terminationText"))else null
} }
suspend fun selectStreams(part: Part, audio: String? = null, subtitle: String? = null) { suspend fun selectStreams(part: Part, audio: String? = null, subtitle: String? = null) {
request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT") request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT")
@ -173,7 +147,7 @@ class PlexApi(val clientId: String) {
val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}} val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}}
put("X-Plex-Client-Profile-Extra",if(mode==1&&hevcAvailable)"append-transcode-target-codec(type=videoProfile&context=streaming&protocol=hls&videoCodec=hevc)"else "") put("X-Plex-Client-Profile-Extra",if(mode==1&&hevcAvailable)"append-transcode-target-codec(type=videoProfile&context=streaming&protocol=hls&videoCodec=hevc)"else "")
} }
suspend fun stopTranscode(sessionId: String, server: Session? = session) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId),server) } suspend fun stopTranscode(sessionId: String) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId)) }
} }
/** Index of the part containing [time] on the title's combined timeline. */ /** Index of the part containing [time] on the title's combined timeline. */
@ -183,8 +157,3 @@ internal fun partFor(parts:List<Part>,time:Long):Int {
return 0 return 0
} }
internal fun partStart(parts:List<Part>,index:Int):Long = parts.take(index.coerceAtLeast(0)).sumOf{it.duration.coerceAtLeast(0)} internal fun partStart(parts:List<Part>,index:Int):Long = parts.take(index.coerceAtLeast(0)).sumOf{it.duration.coerceAtLeast(0)}
internal fun continueWatchingFingerprint(items:List<JSONObject>):String = items.joinToString("|"){j->
val duration=j.optLong("duration");val offset=j.optLong("viewOffset")
val step=if(duration>0)(offset*20/duration).toString()else (offset/120_000).toString()
"${j.optString("ratingKey")}:${j.optString("viewCount")}:$step"
}

View file

@ -1,19 +1,14 @@
package tv.kaleido.app package tv.kaleido.app
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
/** /** Preserve newest-first order. A multi-season addition opens the real show's season list. */
* Preserve newest-first order. A multi-season addition opens the real show's season list; if that
* show can't be loaded, its newest season stands in rather than discarding the whole row.
*/
internal suspend fun groupRecentSeasons(seasons:List<Title>,loadShow:suspend (String)->Title):List<Title> = coroutineScope { internal suspend fun groupRecentSeasons(seasons:List<Title>,loadShow:suspend (String)->Title):List<Title> = coroutineScope {
seasons.distinctBy{it.id}.groupBy{it.parentId.ifBlank{"season:${it.id}"}}.values.take(18).map { group->async { seasons.distinctBy{it.id}.groupBy{it.parentId.ifBlank{"season:${it.id}"}}.values.take(18).map { group->async {
val season=group.first() val season=group.first()
val single=season.copy(title=listOf(season.parentTitle,season.title).filter{it.isNotBlank()}.joinToString(" · ")) if(group.size>1&&season.parentId.isNotBlank())loadShow(season.parentId)
if(group.size>1&&season.parentId.isNotBlank())try{loadShow(season.parentId)}catch(e:CancellationException){throw e}catch(_:Exception){single} else season.copy(title=listOf(season.parentTitle,season.title).filter{it.isNotBlank()}.joinToString(" · "))
else single
}}.awaitAll() }}.awaitAll()
} }

View file

@ -118,9 +118,8 @@ import java.io.File
splashExit.animateTo(1f,tween(StartupExitMillis,easing=LinearEasing));startup=false splashExit.animateTo(1f,tween(StartupExitMillis,easing=LinearEasing));startup=false
} }
} }
// The server picker covers every page, so Back closes it before navigating underneath. BackHandler(enabled=vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
BackHandler(enabled=vm.servers.isNotEmpty()||vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){ if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
if(vm.servers.isNotEmpty())vm.dismissServerPicker()else if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
} }
NavigationSounds(vm.navigationSounds&&!startup) { NavigationSounds(vm.navigationSounds&&!startup) {
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{vm.lastInteraction=android.os.SystemClock.uptimeMillis();startup}) { Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{vm.lastInteraction=android.os.SystemClock.uptimeMillis();startup}) {
@ -198,7 +197,7 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
Spacer(Modifier.height(14.dp));OutlinedTextField(address,{address=it},label={Text("Server URL")},singleLine=true,modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(10.dp));OutlinedTextField(token,{token=it},label={Text("Access token")},singleLine=true,visualTransformation=PasswordVisualTransformation(),modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(18.dp));TvButton("Connect",primary=true,onClick={vm.manualConnect(address,token)});Spacer(Modifier.height(10.dp));TvButton("Use Plex account",onClick=back) Spacer(Modifier.height(14.dp));OutlinedTextField(address,{address=it},label={Text("Server URL")},singleLine=true,modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(10.dp));OutlinedTextField(token,{token=it},label={Text("Access token")},singleLine=true,visualTransformation=PasswordVisualTransformation(),modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(18.dp));TvButton("Connect",primary=true,onClick={vm.manualConnect(address,token)});Spacer(Modifier.height(10.dp));TvButton("Use Plex account",onClick=back)
} }
@Composable fun ServerPicker(vm: KaleidoViewModel) { @Composable fun ServerPicker(vm: KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})};if(vm.session!=null){Spacer(Modifier.height(6.dp));TvButton("Cancel",onClick={vm.dismissServerPicker()})}} Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})}}
} }
@Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}} @Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}}
@Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick=retry);TvButton("Dismiss",onClick=dismiss)}}}} @Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick=retry);TvButton("Dismiss",onClick=dismiss)}}}}

View file

@ -44,11 +44,10 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
var watchedDialog by remember { mutableStateOf(false) } var watchedDialog by remember { mutableStateOf(false) }
var remoteDialog by remember { mutableStateOf(false) } var remoteDialog by remember { mutableStateOf(false) }
var autoplayDialog by remember { mutableStateOf(false) } var autoplayDialog by remember { mutableStateOf(false) }
var introDialog by remember { mutableStateOf(false) }
var creditsDialog by remember { mutableStateOf(false) }
var subtitleSizeDialog by remember { mutableStateOf(false) } var subtitleSizeDialog by remember { mutableStateOf(false) }
var subtitleStyleDialog by remember { mutableStateOf(false) } var subtitleStyleDialog by remember { mutableStateOf(false) }
var themeVolumeDialog by remember { mutableStateOf(false) } var themeVolumeDialog by remember { mutableStateOf(false) }
var volumeBoostDialog by remember { mutableStateOf(false) }
val remoteFocus = remember { FocusRequester() } val remoteFocus = remember { FocusRequester() }
val autoplayFocus = remember { FocusRequester() } val autoplayFocus = remember { FocusRequester() }
val introFocus = remember { FocusRequester() } val introFocus = remember { FocusRequester() }
@ -57,6 +56,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
val themeMusicFocus = remember { FocusRequester() } val themeMusicFocus = remember { FocusRequester() }
val colourWashFocus = remember { FocusRequester() } val colourWashFocus = remember { FocusRequester() }
val themeVolumeFocus = remember { FocusRequester() } val themeVolumeFocus = remember { FocusRequester() }
val volumeBoostFocus = remember { FocusRequester() }
val categoryFocus = remember { List(categories.size) { FocusRequester() } } val categoryFocus = remember { List(categories.size) { FocusRequester() } }
val entryFocus = remember { List(categories.size) { FocusRequester() } } val entryFocus = remember { List(categories.size) { FocusRequester() } }
@ -74,8 +74,8 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
delay(140) delay(140)
runCatching { entryFocus[selectedCategory].requestFocus() } runCatching { entryFocus[selectedCategory].requestFocus() }
} }
val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog || introDialog || creditsDialog || val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog ||
subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog || volumeBoostDialog
LaunchedEffect(anyDialogOpen, dialogRestoreFocus) { LaunchedEffect(anyDialogOpen, dialogRestoreFocus) {
if (!anyDialogOpen) { if (!anyDialogOpen) {
dialogRestoreFocus?.let { requester -> dialogRestoreFocus?.let { requester ->
@ -236,7 +236,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
) )
SettingsValueRow( SettingsValueRow(
title = "Autoplay next episode", title = "Autoplay next episode",
description = "Up Next counts down to the next episode. Any remote press stops it.", description = "Count down to the next episode when one ends.",
value = autoplayLabel(vm.autoplaySeconds), value = autoplayLabel(vm.autoplaySeconds),
requester = autoplayFocus, requester = autoplayFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
@ -244,19 +244,27 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
) )
SettingsValueRow( SettingsValueRow(
title = "Skip intros", title = "Skip intros",
description = "Uses intro markers from your Plex server. Any remote press cancels an automatic skip.", description = "Uses intro markers from your Plex server.",
value = autoSkipLabel(vm.autoSkipIntroSeconds), value = if (vm.autoSkipIntro) "Automatically" else "Show button",
requester = introFocus, requester = introFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { dialogRestoreFocus = introFocus; introDialog = true } onClick = { vm.chooseAutoSkipIntro(!vm.autoSkipIntro) }
) )
SettingsValueRow( SettingsValueRow(
title = "Skip credits", title = "Skip credits",
description = "Automatic: episodes open Up Next as the credits start; movies skip past them after the delay.", description = "Episodes go straight to Up Next; movies skip past the credits.",
value = autoSkipLabel(vm.autoSkipCreditsSeconds), value = if (vm.autoSkipCredits) "Automatically" else "Show button",
requester = creditsFocus, requester = creditsFocus,
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { dialogRestoreFocus = creditsFocus; creditsDialog = true } onClick = { vm.chooseAutoSkipCredits(!vm.autoSkipCredits) }
)
SettingsValueRow(
title = "Volume boost",
description = "Raise quiet titles. Higher boosts can distort loud peaks. Uses decoded audio instead of passthrough.",
value = volumeBoostLabel(vm.volumeBoostDb),
requester = volumeBoostFocus,
leftTarget = categoryFocus[1],
onClick = { dialogRestoreFocus = volumeBoostFocus; volumeBoostDialog = true }
) )
Text( Text(
"Completed titles keep their Plex watched status.", "Completed titles keep their Plex watched status.",
@ -407,18 +415,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
remoteDialog = false remoteDialog = false
} }
} }
if (introDialog) {
ChoiceDialog("Skip intros", AutoSkipChoices.map(::autoSkipLabel), AutoSkipChoices.indexOf(vm.autoSkipIntroSeconds).coerceAtLeast(0), { introDialog = false }) {
vm.chooseAutoSkipIntro(AutoSkipChoices[it])
introDialog = false
}
}
if (creditsDialog) {
ChoiceDialog("Skip credits", AutoSkipChoices.map(::autoSkipLabel), AutoSkipChoices.indexOf(vm.autoSkipCreditsSeconds).coerceAtLeast(0), { creditsDialog = false }) {
vm.chooseAutoSkipCredits(AutoSkipChoices[it])
creditsDialog = false
}
}
if (autoplayDialog) { if (autoplayDialog) {
val choices = listOf(0, 5, 10, 15, 30) val choices = listOf(0, 5, 10, 15, 30)
ChoiceDialog("Autoplay next episode", choices.map(::autoplayLabel), choices.indexOf(vm.autoplaySeconds), { autoplayDialog = false }) { ChoiceDialog("Autoplay next episode", choices.map(::autoplayLabel), choices.indexOf(vm.autoplaySeconds), { autoplayDialog = false }) {
@ -451,12 +447,17 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
themeVolumeDialog = false themeVolumeDialog = false
} }
} }
if (volumeBoostDialog) {
val choices = listOf(0, 3, 6, 9, 12)
ChoiceDialog("Volume boost", choices.map(::volumeBoostLabel), choices.indexOf(vm.volumeBoostDb).coerceAtLeast(0), { volumeBoostDialog = false }) {
vm.chooseVolumeBoostDb(choices[it])
volumeBoostDialog = false
}
}
} }
private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds" private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds"
/** 0 only shows the Skip button; otherwise the button counts down this long before skipping. */ private fun volumeBoostLabel(db: Int) = if (db == 0) "Off (+0 dB)" else "+$db dB"
private val AutoSkipChoices = listOf(0, 3, 5, 10, 15)
private fun autoSkipLabel(seconds: Int) = if (seconds <= 0) "Show button" else "Automatically after $seconds s"
/** A sample line in the chosen subtitle look, rendered by the player's own subtitle view. */ /** A sample line in the chosen subtitle look, rendered by the player's own subtitle view. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)

View file

@ -22,19 +22,6 @@ internal class ShuffleEpisodes<T>(
return nextCycle?.firstOrNull() ?: makeNextCycle(order[currentIndex]).also { nextCycle = it }.firstOrNull() return nextCycle?.firstOrNull() ?: makeNextCycle(order[currentIndex]).also { nextCycle = it }.firstOrNull()
} }
/** The item played before [currentId] in this bag, or null at the bag's start. */
fun preceding(currentId: String): T? {
if (order.getOrNull(currentIndex)?.let(id) != currentId) return null
return order.getOrNull(currentIndex - 1)
}
/** Steps back only when [previousId] is the item returned by [preceding]. */
fun retreat(currentId: String, previousId: String): Boolean {
if (preceding(currentId)?.let(id) != previousId) return false
currentIndex--
return true
}
/** Advances only when [nextId] is the next item returned by [following]. */ /** Advances only when [nextId] is the next item returned by [following]. */
fun advance(currentId: String, nextId: String): Boolean { fun advance(currentId: String, nextId: String): Boolean {
if (following(currentId)?.let(id) != nextId) return false if (following(currentId)?.let(id) != nextId) return false

View file

@ -16,24 +16,30 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import kotlin.math.PI import kotlin.math.PI
import kotlin.math.cos import kotlin.math.cos
import kotlin.math.exp import kotlin.math.exp
import kotlin.math.ln import kotlin.math.ln
import kotlin.math.max
import kotlin.math.sin import kotlin.math.sin
private class KaleidoFacet(val points:List<Offset>,val centroid:Offset,val color:Color,val angle:Float) private class ApertureFacet(val points:List<Offset>,val color:Color,val normal:Offset)
// Exact geometry and colors from brand_mark.xml, centered on its 64-unit viewport. // Exact geometry and colors from brand_mark.xml, centered on its 64-unit viewport.
// Each facet carries its centroid and the angle of its hexagon edge's outward normal. // Each facet carries the outward normal of its hexagon edge for the iris motion.
private val kaleidoFacets=listOf( private val apertureFacets=listOf(
floatArrayOf(33f,4f,55.5f,17f,42.5f,24.5f,33f,19f) to 0xFFC3E8D3, floatArrayOf(33f,4f,55.5f,17f,42.5f,24.5f,33f,19f) to 0xFFC3E8D3,
floatArrayOf(56.5f,19f,56.5f,45f,43.5f,37.5f,43.5f,26.5f) to 0xFF71B9B0, floatArrayOf(56.5f,19f,56.5f,45f,43.5f,37.5f,43.5f,26.5f) to 0xFF71B9B0,
floatArrayOf(55.5f,47f,33f,60f,33f,45f,42.5f,39.5f) to 0xFF3D7C7B, floatArrayOf(55.5f,47f,33f,60f,33f,45f,42.5f,39.5f) to 0xFF3D7C7B,
@ -41,65 +47,52 @@ private val kaleidoFacets=listOf(
floatArrayOf(7.5f,45f,7.5f,19f,20.5f,26.5f,20.5f,37.5f) to 0xFFE9D8AE, floatArrayOf(7.5f,45f,7.5f,19f,20.5f,26.5f,20.5f,37.5f) to 0xFFE9D8AE,
floatArrayOf(8.5f,17f,31f,4f,31f,19f,21.5f,24.5f) to 0xFFEEF2DD floatArrayOf(8.5f,17f,31f,4f,31f,19f,21.5f,24.5f) to 0xFFEEF2DD
).mapIndexed { index,(points,color) -> ).mapIndexed { index,(points,color) ->
val corners=points.toList().chunked(2){Offset(it[0]-32f,it[1]-32f)} val angle=(-60.0+60*index)*PI/180
val centroid=Offset(corners.sumOf{it.x.toDouble()}.toFloat()/4,corners.sumOf{it.y.toDouble()}.toFloat()/4) ApertureFacet(points.toList().chunked(2){Offset(it[0]-32f,it[1]-32f)},Color(color),Offset(cos(angle).toFloat(),sin(angle).toFloat()))
KaleidoFacet(corners,centroid,Color(color),rad(-60f+60*index))
} }
// Loose shards around each facet: angle from the facet's normal (degrees), starting radius (dp),
// size, palette offset and how far they tumble on the way in.
private class Shard(val angle:Float,val radius:Float,val scale:Float,val color:Int,val spin:Float)
private val shards=listOf(
Shard(20f,170f,.42f,2,1.2f),Shard(-20f,170f,.42f,4,-1.2f),
Shard(36f,320f,.3f,3,2.1f),Shard(-36f,320f,.3f,1,-2.1f),
Shard(8f,420f,.2f,5,3f),Shard(-8f,420f,.2f,5,-3f)
)
// Inner hexagon traced by the facets' inner edges: the aperture the exit flies through. // Inner hexagon traced by the facets' inner edges: the aperture the exit flies through.
private const val InnerRadius=13.6f private const val InnerRadius=13.6f
private const val MarkBox=140f private const val InnerApothem=11.8f
// Timeline in ms. The shard field fades in, still, until GatherEnd and holds there until startup is ready; the private const val IntroBox=132f
// gather then plays in motion time (timeline minus GatherEnd). Completion is reported at IntroEnd; the timeline // The settled lockup is the header Brand() scaled up, so it reads as the same mark.
// keeps running to TimelineEnd only so the mark stays alive while the exit plays or startup loads. private const val LockScale=2.75f
private const val LockBox=29f*LockScale
private const val LockGap=7f*LockScale
// Opening timeline in ms, paused at GatherEnd until startup is ready. Completion is reported at IntroEnd; the timeline keeps
// running to TimelineEnd only for the slow settle while the exit plays or startup loads.
private const val GatherEnd=260f private const val GatherEnd=260f
private const val IntroEnd=GatherEnd+1700f private const val IntroEnd=2260f
private const val TimelineEnd=GatherEnd+8000f private const val TimelineEnd=2900f
const val StartupExitMillis=640 const val StartupExitMillis=640
// The mark is larger than the old lockup, so it zooms less to end the flight at the same size.
private const val FlightZoom=30f
private val Emphasized=CubicBezierEasing(.2f,0f,0f,1f) private val Emphasized=CubicBezierEasing(.2f,0f,0f,1f)
private val EmphasizedDecelerate=CubicBezierEasing(.05f,.7f,.1f,1f) private val EmphasizedDecelerate=CubicBezierEasing(.05f,.7f,.1f,1f)
private val Standard=CubicBezierEasing(.4f,0f,.2f,1f) private val Standard=CubicBezierEasing(.4f,0f,.2f,1f)
private val InOut=CubicBezierEasing(.45f,0f,.55f,1f) private val InOut=CubicBezierEasing(.45f,0f,.55f,1f)
// A mechanical iris: the blades gather, snap open, and overshoot slightly as they lock.
private val IrisOpen=CubicBezierEasing(.55f,0f,.15f,1f)
private val IrisTwist=CubicBezierEasing(.5f,0f,.18f,1.1f)
// Applied in log space: a brief pull back, then an accelerating flight. // Applied in log space: a brief pull back, then an accelerating flight.
private val Flight=CubicBezierEasing(.55f,-.06f,.8f,.36f) private val Flight=CubicBezierEasing(.55f,-.06f,.8f,.36f)
private val SeaGlass=Color(0xFF71B9B0) private val SeaGlass=Color(0xFF71B9B0)
private val Light=Color(0xFFEEF2DD)
private fun rad(degrees:Float)=degrees*PI.toFloat()/180
private fun phase(time:Float,start:Float,end:Float)=((time-start)/(end-start)).coerceIn(0f,1f) private fun phase(time:Float,start:Float,end:Float)=((time-start)/(end-start)).coerceIn(0f,1f)
private fun mix(from:Float,to:Float,amount:Float)=from+(to-from)*amount private fun mix(from:Float,to:Float,amount:Float)=from+(to-from)*amount
/** A facet turned [rotation] about the mark center, shrunk and spun about its own centroid, then offset. */ private class Iris(val inward:Float,val theta:Float,val grow:Float)
private fun Path.facet(facet:KaleidoFacet,center:Offset,unit:Float,rotation:Float=0f,scale:Float=1f,spin:Float=0f,offset:Offset=Offset.Zero) { private fun irisAt(time:Float):Iris {
val cr=cos(rotation);val sr=sin(rotation);val cs=cos(spin);val ss=sin(spin) val progress=phase(time,140f,1180f)
facet.points.forEachIndexed { index,point -> return Iris(InnerApothem*(1f-IrisOpen.transform(progress)),(-44f*(1f-IrisTwist.transform(progress))*PI/180).toFloat(),
val rx=point.x-facet.centroid.x;val ry=point.y-facet.centroid.y mix(.64f,1f,Emphasized.transform(progress)))
val x=facet.centroid.x+(rx*cs-ry*ss)*scale;val y=facet.centroid.y+(rx*ss+ry*cs)*scale
val px=center.x+(x*cr-y*sr)*unit+offset.x;val py=center.y+(x*sr+y*cr)*unit+offset.y
if(index==0)moveTo(px,py)else lineTo(px,py)
}
close()
} }
/** A loose facet shape with its centroid at [position]. */ private fun Path.facet(facet:ApertureFacet,iris:Iris,unit:Float,center:Offset) {
private fun Path.shard(facet:KaleidoFacet,position:Offset,size:Float,angle:Float) { val c=cos(iris.theta);val s=sin(iris.theta);val k=unit*iris.grow
val c=cos(angle);val s=sin(angle)
facet.points.forEachIndexed { index,point -> facet.points.forEachIndexed { index,point ->
val x=point.x-facet.centroid.x;val y=point.y-facet.centroid.y val x=point.x-facet.normal.x*iris.inward;val y=point.y-facet.normal.y*iris.inward
val px=position.x+(x*c-y*s)*size;val py=position.y+(x*s+y*c)*size val px=center.x+(x*c-y*s)*k;val py=center.y+(x*s+y*c)*k
if(index==0)moveTo(px,py)else lineTo(px,py) if(index==0)moveTo(px,py)else lineTo(px,py)
} }
close() close()
@ -118,21 +111,21 @@ private fun Path.hexagon(center:Offset,radius:Float) {
fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(phase(exit,.25f,1f))) fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(phase(exit,.25f,1f)))
/** /**
* The cold-start brand sequence, the same as Kaleido Desktop: a kaleidoscope. A mirrored field of shards turns * The cold-start brand sequence: a closed iris lit from behind twists open once [ready], light catches
* and gathers into the mark's six facets once [ready]; small shards circle the mark if startup runs on. [exit] * the facets, and the wordmark slides out of the mark. [exit] (0–1, linear) then flies
* (0–1, linear) then flies the camera through the mark's open center, revealing the app drawn beneath. * the camera through the aperture's dark center, revealing the app drawn beneath.
*/ */
@Composable fun StartupSplash(exit:()->Float,ready:()->Boolean,onComplete:()->Unit) { @Composable fun StartupSplash(exit:()->Float,ready:()->Boolean,onComplete:()->Unit) {
val timeline=remember{Animatable(0f)} val timeline=remember{Animatable(0f)}
val complete by rememberUpdatedState(onComplete) val complete by rememberUpdatedState(onComplete)
LaunchedEffect(Unit){ LaunchedEffect(Unit){
// Animatable honors Android's animation duration scale, including animations off. // Animatable honors Android's animation duration scale, including animations off.
// The field fades in faint and still straight away, so the first cold-start frames // Light gathers on the closed iris straight away. It is nearly still, so the first
// can hitch there without being noticed. // cold-start frames can hitch there without being noticed.
timeline.animateTo(GatherEnd,tween(GatherEnd.toInt(),easing=LinearEasing)) timeline.animateTo(GatherEnd,tween(GatherEnd.toInt(),easing=LinearEasing))
// Startup data arriving composes the app beneath the splash in one long frame. Hold // Startup data arriving composes the app beneath the splash in one long frame. Hold
// until that has happened and frames arrive steadily again (at most 700 ms), so // until that has happened and frames arrive steadily again (at most 700 ms), so
// the gather, fastest at its start, never runs through it. // the iris never opens through it.
withTimeoutOrNull(700){ withTimeoutOrNull(700){
snapshotFlow{ready()}.first{it} snapshotFlow{ready()}.first{it}
awaitSteadyFrames(4) awaitSteadyFrames(4)
@ -143,23 +136,42 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
snapshotFlow{timeline.value>=IntroEnd}.first{it} snapshotFlow{timeline.value>=IntroEnd}.first{it}
complete() complete()
} }
val measurer=rememberTextMeasurer()
val density=LocalDensity.current
val style=TextStyle(color=Accent,fontSize=(19f*LockScale).sp,fontWeight=FontWeight.Bold)
val letters=remember(measurer,density){"KALEIDO".map{measurer.measure(it.toString(),style)}}
val letterX=remember(letters,density){
val tracking=with(density){(1.4f*LockScale).sp.toPx()}
letters.runningFold(0f){x,letter->x+letter.size.width+tracking}
}
val textWidth=letterX.last()-with(density){(1.4f*LockScale).sp.toPx()}
val capHeight=with(density){style.fontSize.toPx()}*.711f
val paths=remember{List(4){Path()}} val paths=remember{List(4){Path()}}
Canvas(Modifier.fillMaxSize().clearAndSetSemantics{contentDescription="Kaleido starting"}) { Canvas(Modifier.fillMaxSize().clearAndSetSemantics{contentDescription="Kaleido starting"}) {
val time=timeline.value val time=timeline.value
val motion=time-GatherEnd
val prelude=EmphasizedDecelerate.transform(phase(time,0f,GatherEnd))
val q=exit() val q=exit()
val dp=density val dp=density.density
val zoom=if(q>0f)exp(ln(FlightZoom)*Flight.transform(q))else 1f val lockup=Emphasized.transform(phase(time,1250f,2000f))
val unit=MarkBox*dp/64f*zoom val lockWidth=(LockBox+LockGap)*dp+textWidth
val origin=center var box=mix(IntroBox,LockBox,lockup)*dp
val gather=Emphasized.transform(phase(motion,0f,1450f)) // A slow push-in keeps the settled frame alive.
// The whole field turns a little less than half a revolution as it gathers. val drift=1f+.025f*InOut.transform(phase(time,1900f,2900f))
val field=rad(-150f)*(1f-Emphasized.transform(phase(motion,0f,1550f))) var cx=mix(center.x,center.x-lockWidth/2+LockBox*dp/2,lockup)
val (surface,aperture,shape,ring)=paths var cy=center.y
var zoom=1f;var textAlpha=1f;var textShift=0f;var hole=0f
if(q>0f) {
zoom=exp(ln(52f)*Flight.transform(q))
val recenter=Standard.transform((q/.75f).coerceAtMost(1f))
cx=mix(cx,center.x,recenter);cy=mix(cy,center.y,recenter)
textAlpha=1f-Standard.transform(phase(q,0f,.4f))
textShift=-14f*dp*Standard.transform(phase(q,0f,.4f))
hole=InOut.transform(phase(q,.12f,.5f))
}
val unit=box/64f*drift*zoom
val origin=Offset(cx,cy)
val (surface,aperture,facets,ray)=paths
// Splash surface: Ink everywhere, with the aperture's center cut away on exit. // Splash surface: Ink everywhere, with the aperture's center cut away on exit.
val hole=InOut.transform(phase(q,.12f,.5f))
if(hole<=0f)drawRect(Ink) if(hole<=0f)drawRect(Ink)
else { else {
surface.rewind();surface.fillType=PathFillType.EvenOdd surface.rewind();surface.fillType=PathFillType.EvenOdd
@ -168,66 +180,58 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
if(hole<1f){aperture.rewind();aperture.hexagon(origin,InnerRadius*unit);drawPath(aperture,Ink,alpha=1f-hole)} if(hole<1f){aperture.rewind();aperture.hexagon(origin,InnerRadius*unit);drawPath(aperture,Ink,alpha=1f-hole)}
} }
// The kaleidoscope's mirror lines, turning with the field. val iris=irisAt(time)
val lines=max(.5f*prelude,InOut.transform(phase(motion,0f,450f)))*(1f-Standard.transform(phase(motion,1100f,1700f))) val lightUp=EmphasizedDecelerate.transform(phase(time,0f,620f))
if(lines>0f) for(index in 0 until 6) { val light=lightUp*(1f-Standard.transform(phase(time,620f,1250f)))
val angle=field+rad(-90f+60*index) val ambient=.03f*InOut.transform(phase(time,300f,900f))*(1f-Standard.transform(phase(time,1500f,2300f)))
val end=origin+Offset(cos(angle),sin(angle))*(640f*dp) // Light behind the blades: a soft bloom, a hot core, and rays leaking through
drawLine(Brush.linearGradient(0f to Light.copy(alpha=.2f*lines),1f to Color.Transparent,start=origin,end=end),origin,end,dp) // the six gaps while the iris turns.
} if(light>.001f||ambient>.001f) {
val bloom=250f*dp
val bloom=.09f*InOut.transform(phase(motion,200f,1000f))*(1f-Standard.transform(phase(motion,1500f,2600f))) drawCircle(Brush.radialGradient(0f to SeaGlass.copy(alpha=.16f*light+ambient),.45f to SeaGlass.copy(alpha=.04f*light+ambient*.3f),
if(bloom>.001f) { 1f to Color.Transparent,center=origin,radius=bloom),bloom,origin,blendMode=BlendMode.Plus)
val radius=300f*dp val core=26f*unit/2.0625f*mix(.6f,1f,light)
drawCircle(Brush.radialGradient(0f to SeaGlass.copy(alpha=bloom),.45f to SeaGlass.copy(alpha=bloom*.3f),1f to Color.Transparent, if(light>.001f) {
center=origin,radius=radius),radius,origin,blendMode=BlendMode.Plus) drawCircle(Brush.radialGradient(0f to Color(1f,.98f,.925f,.95f*light),.35f to Color(0xFFEEF2DD).copy(alpha=.55f*light),
} 1f to Color.Transparent,center=origin,radius=core),core,origin,blendMode=BlendMode.Plus)
val rays=light*(IrisOpen.transform(phase(time,140f,1180f))*2.5f).coerceAtMost(1f)
// Shards spiral inward, faster than the field turns, and vanish into the center. for(index in 0 until 6) {
val inward=Emphasized.transform(phase(motion,0f,1350f)) val angle=((-90.0+60*index)*PI/180).toFloat()+iris.theta
kaleidoFacets.forEachIndexed { s,facet -> val length=mix(40f,250f,lightUp)*(.75f+.25f*sin(index*2.1f+1f))*dp
shards.forEachIndexed { j,shard -> ray.rewind();ray.moveTo(origin.x,origin.y)
val appear=max(.3f*prelude,Standard.transform(phase(motion,j*50f+s*25,j*50f+s*25+420))) ray.lineTo(origin.x+cos(angle-.014f)*length,origin.y+sin(angle-.014f)*length)
val vanish=Standard.transform(phase(motion,750f+j*45,1350f+j*45)) ray.lineTo(origin.x+cos(angle+.014f)*length,origin.y+sin(angle+.014f)*length);ray.close()
if(appear>0f&&vanish<1f) { drawPath(ray,Brush.linearGradient(0f to Color(1f,.973f,.902f,.42f*rays),.25f to Color(0xFFD6ECE2).copy(alpha=.12f*rays),
val angle=facet.angle+rad(shard.angle)+field*1.5f 1f to Color.Transparent,start=origin,end=Offset(origin.x+cos(angle)*length,origin.y+sin(angle)*length)),blendMode=BlendMode.Plus)
val radius=shard.radius*dp*(1f-.88f*inward)
shape.rewind()
shape.shard(facet,origin+Offset(cos(angle),sin(angle))*radius,unit*shard.scale*(1f-.6f*vanish),field*2+shard.spin*(1f-gather))
drawPath(shape,kaleidoFacets[(s+shard.color)%6].color,alpha=appear*(1f-vanish)*.9f,blendMode=BlendMode.Screen)
} }
} }
} }
// The six facets ride in from the field and lock into the mark. // Facets. Short echoes of earlier frames act as motion blur while the blades
kaleidoFacets.forEachIndexed { s,facet -> // turn; they disappear beneath the facets once the iris is still.
val radius=240f*dp*(1f-gather);val angle=facet.angle+field fun facetAlpha(index:Int)=EmphasizedDecelerate.transform(phase(time,40f+index*34,380f+index*34))
shape.rewind() if(time<1400f) for((delay,alpha) in listOf(84f to .07f,56f to .12f,28f to .2f)) {
shape.facet(facet,origin,unit,field,mix(.55f,1f,gather),rad(-60f)*(1f-gather),Offset(cos(angle),sin(angle))*radius) val echo=irisAt(time-delay)
drawPath(shape,facet.color,alpha=max(.3f*prelude,Standard.transform(phase(motion,s*25f,s*25f+420)))) apertureFacets.forEachIndexed { index,facet ->
facets.rewind();facets.facet(facet,echo,unit,origin);drawPath(facets,facet.color,alpha=alpha*facetAlpha(index))
}
}
apertureFacets.forEachIndexed { index,facet ->
facets.rewind();facets.facet(facet,iris,unit,origin);drawPath(facets,facet.color,alpha=facetAlpha(index))
} }
// A ring pulses out as the facets lock. val sheen=phase(time,980f,1560f)
val pulse=phase(motion,1380f,2050f) if(light>.01f||(sheen>0f&&sheen<1f)) {
if(pulse>0f&&pulse<1f) { facets.rewind();apertureFacets.forEach{facets.facet(it,iris,unit,origin)}
ring.rewind();ring.hexagon(origin,(30f+24f*EmphasizedDecelerate.transform(pulse))*unit) clipPath(facets) {
drawPath(ring,SeaGlass,alpha=.45f*(1f-pulse),style=Stroke(1.5f*dp)) // Backlight tints the blades while the core is hot, so they read as glass.
if(light>.01f) {
val radius=36f*unit/2.0625f
drawCircle(Brush.radialGradient(0f to Color(1f,.988f,.94f,.26f*light),1f to Color.Transparent,center=origin,radius=radius),radius,origin)
} }
// One diagonal band of light crosses the settled mark.
// Still starting: small shards keep circling the mark. if(sheen>0f&&sheen<1f) {
val idle=Standard.transform(phase(motion,2300f,2900f))*(1f-phase(q,0f,.25f)) val reach=34f*unit;val angle=36f*PI.toFloat()/180;val direction=Offset(cos(angle),sin(angle))
if(idle>0f) for(s in 0 until 6) for(side in intArrayOf(-1,1)) {
val angle=rad(-60f+60*s)+side*rad(11f)+(motion-2300f)*.00032f
shape.rewind();shape.shard(kaleidoFacets[s],origin+Offset(cos(angle),sin(angle))*(50f*unit),unit*.16f,angle*2)
drawPath(shape,kaleidoFacets[(s+if(side>0)2 else 4)%6].color,alpha=.4f*idle,blendMode=BlendMode.Screen)
}
// A band of light crosses the settled mark, then again every few seconds while it waits.
val sheen=if(motion<1500f)0f else ((motion-1500f)%3600f)/900f
if(q==0f&&sheen>0f&&sheen<1f) {
shape.rewind();kaleidoFacets.forEach{shape.facet(it,origin,unit)}
clipPath(shape) {
val reach=40f*unit;val angle=rad(36f);val direction=Offset(cos(angle),sin(angle))
val position=mix(-1.25f,1.25f,InOut.transform(sheen))*reach;val width=10f*unit val position=mix(-1.25f,1.25f,InOut.transform(sheen))*reach;val width=10f*unit
val peak=.42f*sin((sheen*1.1f).coerceAtMost(1f)*PI.toFloat()) val peak=.42f*sin((sheen*1.1f).coerceAtMost(1f)*PI.toFloat())
drawRect(Brush.linearGradient(0f to Color.Transparent,.5f to Color.White.copy(alpha=peak),1f to Color.Transparent, drawRect(Brush.linearGradient(0f to Color.Transparent,.5f to Color.White.copy(alpha=peak),1f to Color.Transparent,
@ -235,4 +239,23 @@ fun startupArrivalScale(exit:Float)=mix(1.14f,1f,EmphasizedDecelerate.transform(
} }
} }
} }
// The wordmark slides out from behind the mark as it moves into the lockup.
if(time>=1400f&&textAlpha>0f) {
val scale=box/(LockBox*dp)*drift
val textLeft=cx-box*drift/2+(LockBox+LockGap)*dp*scale
val slide=EmphasizedDecelerate.transform(phase(time,1400f,2050f))
val baseline=cy+capHeight/2*scale
clipRect(left=cx+24.5f*unit+2f*dp*scale) {
letters.forEachIndexed { index,letter ->
val start=1460f+index*45
val reveal=Standard.transform(phase(time,start,start+320f))
if(reveal>0f) withTransform({
translate(textLeft+(letterX[index]-(1f-slide)*textWidth*.42f)*scale+textShift,baseline-letter.firstBaseline*scale)
scale(scale,scale,pivot=Offset.Zero)
}) {drawText(letter,alpha=reveal*textAlpha)}
}
}
}
}
} }

View file

@ -233,7 +233,6 @@ internal fun nextUp(episodes:List<Title>,watchedPercent:Int)=episodes.firstOrNul
@Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,entry:FocusRequester) { @Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,entry:FocusRequester) {
val initial=remember(item.id){item.castMembers.indexOfFirst{"cast:${item.id}:${it.id.ifBlank{it.name}}"==vm.focusId}.coerceAtLeast(0)} val initial=remember(item.id){item.castMembers.indexOfFirst{"cast:${item.id}:${it.id.ifBlank{it.name}}"==vm.focusId}.coerceAtLeast(0)}
val row=rememberLazyListState(initialFirstVisibleItemIndex=initial) val row=rememberLazyListState(initialFirstVisibleItemIndex=initial)
val entryIndex by rememberRowEntry(row,0)
Column { Column {
Text("Cast",color=Accent,fontSize=17.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=10.dp)) Text("Cast",color=Accent,fontSize=17.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=10.dp))
LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entry)) { LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entry)) {
@ -242,7 +241,7 @@ internal fun nextUp(episodes:List<Title>,watchedPercent:Int)=episodes.firstOrNul
var focused by remember{mutableStateOf(false)} var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()} val requester=remember{FocusRequester()}
LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}} LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}}
Column(Modifier.width(108.dp).then(if(index==entryIndex)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).focusProperties{if(item.type!="collection"&&vm.children.isEmpty())up=actionFocus}.navigationSound().onFocusChanged{ Column(Modifier.width(108.dp).then(if(index==0)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).focusProperties{if(item.type!="collection"&&vm.children.isEmpty())up=actionFocus}.navigationSound().onFocusChanged{
focused=it.isFocused;if(it.isFocused)vm.focusId=key focused=it.isFocused;if(it.isFocused)vm.focusId=key
}.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{ }.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{
contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ") contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ")

View file

@ -0,0 +1,29 @@
package tv.kaleido.app
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor.AudioFormat
import androidx.media3.common.audio.AudioProcessor.UnhandledAudioFormatException
import androidx.media3.common.audio.BaseAudioProcessor
import java.nio.ByteBuffer
import kotlin.math.pow
import kotlin.math.roundToInt
/** Applied after decoding, for every channel and delivery mode; passthrough is disabled when on. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
internal class VolumeBoostProcessor(db:Int,private val onProcessing:(()->Unit)?=null):BaseAudioProcessor() {
private val gain=boostGain(db)
private var reported=false
override fun onConfigure(inputAudioFormat:AudioFormat):AudioFormat {
if(inputAudioFormat.encoding!=C.ENCODING_PCM_16BIT)throw UnhandledAudioFormatException(inputAudioFormat)
return if(gain>1.0)inputAudioFormat else AudioFormat.NOT_SET
}
override fun queueInput(inputBuffer:ByteBuffer) {
if(!reported&&inputBuffer.hasRemaining()) { reported=true;onProcessing?.invoke() }
val output=replaceOutputBuffer(inputBuffer.remaining())
while(inputBuffer.remaining()>=2)output.putShort(boostSample(inputBuffer.short,gain))
output.flip()
}
}
internal fun boostGain(db:Int):Double=10.0.pow(db.coerceIn(0,12)/20.0)
internal fun boostSample(sample:Short,gain:Double):Short=(sample*gain).roundToInt().coerceIn(Short.MIN_VALUE.toInt(),Short.MAX_VALUE.toInt()).toShort()

View file

@ -2,8 +2,31 @@ package tv.kaleido.app
import org.junit.Assert.* import org.junit.Assert.*
import org.junit.Test import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor.AudioFormat
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
class AudioPreferencesTest { class AudioPreferencesTest {
@Test fun boostProcessesEveryChannelAndSaturatesWithoutWrapping() {
val processor=VolumeBoostProcessor(6)
processor.configure(AudioFormat(48000,2,C.ENCODING_PCM_16BIT))
val input=ByteBuffer.allocateDirect(12).order(ByteOrder.nativeOrder())
listOf(1000,-1000,30000,-30000,0,Short.MIN_VALUE.toInt()).forEach { input.putShort(it.toShort()) }
input.flip();processor.queueInput(input)
val output=processor.output.order(ByteOrder.nativeOrder())
val samples=generateSequence { if(output.remaining()>=2)output.short.toInt()else null }.toList()
assertEquals(listOf(1995,-1995,32767,-32768,0,-32768),samples)
assertFalse(input.hasRemaining())
}
@Test fun boostOffPreservesSamplesAndBoundsGain() {
assertEquals(1.0,boostGain(0),0.0)
assertEquals(1.0,boostGain(-30),0.0)
assertEquals(boostGain(12),boostGain(99),0.0)
assertEquals(1234.toShort(),boostSample(1234,boostGain(0)))
assertEquals((-1234).toShort(),boostSample(-1234,boostGain(0)))
}
@Test fun themesUseOnlyServerRelativePaths() { @Test fun themesUseOnlyServerRelativePaths() {
assertEquals("/library/metadata/6115/theme/1",safeThemePath("/library/metadata/6115/theme/1")) assertEquals("/library/metadata/6115/theme/1",safeThemePath("/library/metadata/6115/theme/1"))
assertEquals("",safeThemePath("https://elsewhere.example/theme.mp3")) assertEquals("",safeThemePath("https://elsewhere.example/theme.mp3"))

View file

@ -1,13 +0,0 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Test
class PlaybackTerminationTest {
@Test fun serverReasonFollowsTheExplanation() {
assertEquals("The server stopped this stream.\n\nMaintenance tonight",PlaybackTermination(2006," Maintenance tonight ").message)
}
@Test fun blankReasonLeavesOnlyTheExplanation() {
assertEquals("The server stopped this stream.",PlaybackTermination(2006,"").message)
}
}

View file

@ -1,32 +0,0 @@
package tv.kaleido.app
import androidx.compose.foundation.lazy.LazyListItemInfo
import org.junit.Assert.assertEquals
import org.junit.Test
class RowEntryTest {
private fun card(index:Int,offset:Int)=object:LazyListItemInfo {
override val index=index
override val key:Any=index
override val offset=offset
override val size=264
}
// A 264 px card plus 24 px spacing; the row's start padding is 88 px (viewportStart -88).
private fun row(first:Int,firstOffset:Int,count:Int)=List(count){card(first+it,firstOffset+it*288)}
@Test fun keepsThePreferredCardWhileItIsInView() {
assertEquals(0,rowEntryIndex(0,row(0,0,7),-88))
assertEquals(3,rowEntryIndex(3,row(1,-100,7),-88))
}
@Test fun scrolledAwayRowEntersAtTheFirstFullyVisibleCard() {
// Seasons row restored to its end: Season 6 (index 5) is clipped, Season 7 is the first whole card.
assertEquals(6,rowEntryIndex(0,row(5,-167,7),-88))
// A card resting in the start padding is still wholly on screen.
assertEquals(4,rowEntryIndex(0,row(4,-60,7),-88))
}
@Test fun emptyLayoutKeepsThePreferredCard() {
assertEquals(2,rowEntryIndex(2,emptyList(),-88))
}
}

View file

@ -9,19 +9,6 @@ import org.junit.Test
import kotlin.random.Random import kotlin.random.Random
class ShuffleEpisodesTest { class ShuffleEpisodesTest {
@Test fun previousEpisodeReturnsToTheEarlierPickOnly() {
val shuffle=ShuffleEpisodes(listOf("e1","e2","e3","e4"),{it},Random(7))
val first=shuffle.first!!
assertNull(shuffle.preceding(first))
val second=shuffle.following(first)!!
assertTrue(shuffle.advance(first,second))
assertEquals(first,shuffle.preceding(second))
assertTrue(!shuffle.retreat(second,"not-played"))
assertTrue(shuffle.retreat(second,first))
// Stepping back keeps the bag: the same episode follows again.
assertEquals(second,shuffle.following(first))
assertNull(shuffle.preceding(second))
}
@Test fun eachBagContainsEveryEpisodeOnceAndBoundaryDoesNotRepeat() { @Test fun eachBagContainsEveryEpisodeOnceAndBoundaryDoesNotRepeat() {
val episodes=listOf("e1","e2","e3","e4","e5") val episodes=listOf("e1","e2","e3","e4","e5")
val shuffle=ShuffleEpisodes(episodes,{it},Random(42)) val shuffle=ShuffleEpisodes(episodes,{it},Random(42))

Binary file not shown.

View file

@ -1 +1 @@
2fd832eb90633d1519c15abccc122970a3c5ef51933da35634b8a5b1429d5bc3 Kaleido.apk 03d49e2eef090d40f3a946446ace70f908b86ba26c656862f468a59f764748ec Kaleido.apk

View file

@ -1,7 +1,7 @@
{ {
"version": "0.8.1", "version": "0.6.1",
"versionCode": 25, "versionCode": 21,
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.8.1/distribution/Kaleido.apk", "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.6.1/distribution/Kaleido.apk",
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.8.1/distribution/Kaleido.apk.sha256", "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.6.1/distribution/Kaleido.apk.sha256",
"notes": "- Fix a title page where Down from the buttons did nothing, leaving you stuck at the top. This happened when the Seasons, Cast or another row below had been scrolled away from its first card, for example by reopening a show from Continue Watching. Down now moves to a card in view." "notes": "- Make browsing noticeably smoother on Android TV hardware. Switching between Home, Movies and TV no longer rebuilds each section, returning to the hero or from a title page no longer redraws Home, and moving between rows prepares the next cards ahead of time instead of mid-scroll.\n- Reduce the work done for accessibility services while browsing, which was the largest cost on devices running one (for example a Home-button remapper or TalkBack).\n- Apply background library updates only after the remote has been still for a moment, so they no longer interrupt a move, and keep focus on a card when an update replaces it."
} }

View file

@ -5,7 +5,7 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
## Layout and typography ## Layout and typography
- Horizontal safe gutter: 44 dp. Navigation: 62 dp, with centered text destinations and independent search/settings icons. - Horizontal safe gutter: 44 dp. Navigation: 62 dp, with centered text destinations and independent search/settings icons.
- Home retains a large cinematic feature: an 80 percent stage with original title artwork, synopsis, playback and information actions, with Continue Watching peeking below. Entering the rows compacts it into a Silo-style preview of the focused card instead of scrolling it away: the hero lifts and fades as the rows slide up beneath a bottom-anchored block (64 dp title art, content-rating badge, year/episode, genre, runtime or time left, ratings, three synopsis lines, three cast names and 4K/HDR/Atmos format badges). The card's own image (an episode's still, not its show's art) is scaled whole into a top-right box of 72 × 78 percent of the screen, baked off-thread to fade into the page toward its left and bottom edges. Movies and TV use the same preview (56 dp title art) beneath their Discover/Library/Categories line, with rows starting 300 dp down; their row content stays distinct. With Settings › Interface › Artwork colour wash (default On), the page beneath carries the artwork's average colour normalized to 0.22 luminance, diagonally from the top-right (full) to the bottom-left (18 percent), as Silo does. It is baked into the same cached 960 × 540 frame, so it costs nothing per frame and changes through the artwork crossfade. A 1280 × 720 frame was tried for sharper art and raised Movies' horizontal p95 from about 31 to 36 ms through larger texture uploads, so it was not kept. The preview stays composed, invisible, under the hero with the first row's first card, so entering the rows is only a fade. Up from the first row or Back restores the hero. Features interleave recently released, highly rated unwatched, and Plex-suggested movies/shows, excluding Continue Watching, without a label naming the source. They shuffle per refresh and rotate every 12 seconds while the hero is active, pausing during row browsing. - Home retains a large cinematic feature: an 80 percent stage with original title artwork, synopsis, playback and information actions, with Continue Watching peeking below. Entering the rows compacts it into a Silo-style preview of the focused card instead of scrolling it away: the hero lifts and fades as the rows slide up beneath a bottom-anchored block (64 dp title art, content-rating badge, year/episode, genre, runtime or time left, ratings, three synopsis lines, three cast names and 4K/HDR/Atmos format badges). The card's own image (an episode's still, not its show's art) is scaled whole into a top-right box of 72 × 78 percent of the screen, baked off-thread to fade into the page toward its left and bottom edges. Movies and TV use the same preview (56 dp title art) beneath their Discover/Library/Categories line, with rows starting 300 dp down; their row content stays distinct. With Settings › Interface › Artwork colour wash (default On), the page beneath carries the artwork's average colour normalized to 0.22 luminance, diagonally from the top-right (full) to the bottom-left (18 percent), as Silo does. It is baked into the same cached 960 × 540 frame, so it costs nothing per frame and changes through the artwork crossfade. A 1280 × 720 frame was tried for sharper art and raised Movies' horizontal p95 from about 31 to 36 ms through larger texture uploads, so it was not kept. The preview stays composed, invisible, under the hero with the first row's first card, so entering the rows is only a fade. Up from the first row or Back restores the hero. Features interleave recently released, highly rated unwatched, and Plex-suggested movies/shows, excluding Continue Watching. They shuffle per refresh and rotate every 12 seconds while the hero is active, pausing during row browsing.
- Movies uses a compact fixed preview above poster rows, with the backdrop and synopsis following focused titles. Recently released films and movie recommendations lead. TV uses a shorter preview, larger episode thumbnails, next episodes, newly added seasons, and then new episodes and show recommendations. Redundant TV hubs are omitted when their episode lists match exactly. These are deliberately different compositions. - Movies uses a compact fixed preview above poster rows, with the backdrop and synopsis following focused titles. Recently released films and movie recommendations lead. TV uses a shorter preview, larger episode thumbnails, next episodes, newly added seasons, and then new episodes and show recommendations. Redundant TV hubs are omitted when their episode lists match exactly. These are deliberately different compositions.
- Library: title and discovery/full-library navigation share a 64 dp header. A 43 dp filter row sits immediately above the six-column poster grid. - Library: title and discovery/full-library navigation share a 64 dp header. A 43 dp filter row sits immediately above the six-column poster grid.
- Browsing card widths: landscape 214 dp, TV episodes 264 dp, posters 120 dp. Landscape artwork uses 16:9; posters use 2:3. The full grid scales six columns to available width. Captions reserve a fixed height. - Browsing card widths: landscape 214 dp, TV episodes 264 dp, posters 120 dp. Landscape artwork uses 16:9; posters use 2:3. The full grid scales six columns to available width. Captions reserve a fixed height.
@ -27,7 +27,7 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
- Navigation contrast comes from a gradient extending past the controls and fading to transparent. Home/Movies/TV activate on focus. Explicit row and column links prevent beyond-bounds focus searches when holding a remote direction. - Navigation contrast comes from a gradient extending past the controls and fading to transparent. Home/Movies/TV activate on focus. Explicit row and column links prevent beyond-bounds focus searches when holding a remote direction.
- A spaced D-pad move predicts the actual row/column destination before starting its scroll or focus change. The target backdrop is fetched and contrast-processed through the same Coil request/cache as the visible scene. Speculative artwork uses one low-priority worker so it cannot flood normal decode workers during a burst of input. Metadata starts in parallel; the visible preview and details page share that in-flight request. Rapid horizontal input settles to the latest target before starting speculative work. Full metadata uses a 64-item LRU with a 30-second lifetime, cleared on account/server changes and refreshed after watched updates. Neutral library/search grids prefetch metadata without fetching an unused full-screen backdrop. - A spaced D-pad move predicts the actual row/column destination before starting its scroll or focus change. The target backdrop is fetched and contrast-processed through the same Coil request/cache as the visible scene. Speculative artwork uses one low-priority worker so it cannot flood normal decode workers during a burst of input. Metadata starts in parallel; the visible preview and details page share that in-flight request. Rapid horizontal input settles to the latest target before starting speculative work. Full metadata uses a 64-item LRU with a 30-second lifetime, cleared on account/server changes and refreshed after watched updates. Neutral library/search grids prefetch metadata without fetching an unused full-screen backdrop.
- Home's vertical list prepares content within one viewport ahead and retains one viewport behind, using Compose's bounded lazy-layout cache window. This keeps the hero and nearby rows ready when moving between them, rather than repeatedly composing and measuring the exposed image cards during the animation. Movies/TV use the same window. The window only fills ahead after the list has scrolled, so once a section settles it is nudged 1 px and back, letting the next rows compose in idle frames instead of during the first move down. Card sizes, row targets and the large cinematic Home layout are unchanged. - Home's vertical list prepares content within one viewport ahead and retains one viewport behind, using Compose's bounded lazy-layout cache window. This keeps the hero and nearby rows ready when moving between them, rather than repeatedly composing and measuring the exposed image cards during the animation. Movies/TV use the same window. The window only fills ahead after the list has scrolled, so once a section settles it is nudged 1 px and back, letting the next rows compose in idle frames instead of during the first move down. Card sizes, row targets and the large cinematic Home layout are unchanged.
- Home, Movies and TV previews follow focus once it rests for 110 ms and retain previous artwork until replacement data is ready. New artwork fades in over the old for 320 ms, including cache hits; the outgoing title and synopsis lift slightly as they fade while the new ones rise 12 dp into place (380 ms). Hero recommendation changes use the same artwork and copy transitions, holding the copy up to 700 ms for the new artwork to decode. These fades, and the hero/preview exchange, are single animations read only in graphics layers, so they add no per-frame composition or layout. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms, using per-draw alpha rather than an offscreen layer, and start once the new section's composition frames have passed (at most 300 ms). While a section enters, its cards lay out at their fixed size first and fill in artwork and titles three per frame under the fade, so the section's first frame stays short. Focusing a top tab lets its highlight draw before the section switches. The cold-start sequence is a kaleidoscope, the same as Kaleido Desktop's, and lasts about 2.6 seconds. A faint mirrored field of shards fades in, still, for 260 ms and holds there (at most 700 ms) until startup data has arrived and frames are steady, so cold-start hitches never interrupt the motion. The field then turns 150° while the shards spiral inward and vanish and the six exact facets ride in from it and lock into the mark (1.7 s), a hexagonal ring pulses out and a sheen crosses the settled mark. Once loading finishes (up to 600 ms extra; small shards begin circling the mark if it runs long) the camera flies through the mark's open center over 640 ms, revealing the app beneath as it settles from 114 percent scale. The completed mark itself is never redesigned. Android animation duration scale is honored, including animations off. It does not replay when returning from background. - Home, Movies and TV previews follow focus once it rests for 110 ms and retain previous artwork until replacement data is ready. New artwork fades in over the old for 320 ms, including cache hits; the outgoing title and synopsis lift slightly as they fade while the new ones rise 12 dp into place (380 ms). Hero recommendation changes use the same artwork and copy transitions, holding the copy up to 700 ms for the new artwork to decode. These fades, and the hero/preview exchange, are single animations read only in graphics layers, so they add no per-frame composition or layout. Contrast gradients are baked into a cached bitmap on a worker thread, reducing GPU overdraw. Rotation pauses on the information/next controls and preserves their focus. Vertical row changes animate to explicit row/column targets; page entrances fade and slide 28 dp over 280 ms, using per-draw alpha rather than an offscreen layer, and start once the new section's composition frames have passed (at most 300 ms). While a section enters, its cards lay out at their fixed size first and fill in artwork and titles three per frame under the fade, so the section's first frame stays short. Focusing a top tab lets its highlight draw before the section switches. The cold-start sequence lasts 2.9 seconds. The six exact facets begin as a closed, overlapping iris lit from behind; it holds there (at most 700 ms) until startup data has arrived and frames are steady, so cold-start hitches never interrupt the motion. The iris then twists 44° open and locks with a slight overshoot while light leaks through the six gaps, a single sheen crosses the settled mark, and the mark shrinks into a lockup scaled from the header brand as KALEIDO slides out from behind it. Once loading finishes (up to 600 ms extra) the camera flies through the aperture's dark center over 640 ms, revealing the app beneath as it settles from 114 percent scale. The completed mark itself is never redesigned. Android animation duration scale is honored, including animations off. It does not replay when returning from background.
- Returning from details restores the library's mode, scroll position, and previously focused title. - Returning from details restores the library's mode, scroll position, and previously focused title.
- Entering Movies/TV from the top bar focuses the fixed Discover control immediately. Down from Discover explicitly reveals the first catalog card; focus on already-visible targets changes before scrolling. A quick tab/Down sequence queues entry for the new destination, and focused tabs never repeat their delayed initial-focus request. - Entering Movies/TV from the top bar focuses the fixed Discover control immediately. Down from Discover explicitly reveals the first catalog card; focus on already-visible targets changes before scrolling. A quick tab/Down sequence queues entry for the new destination, and focused tabs never repeat their delayed initial-focus request.
- Offscreen card navigation requests the next lazy layout instead of forcing synchronous composition between key events. Up at the top bar is consumed because there is no destination above it; it must not start a lazy-list focus search. - Offscreen card navigation requests the next lazy layout instead of forcing synchronous composition between key events. Up at the top bar is consumed because there is no destination above it; it must not start a lazy-list focus search.
@ -41,7 +41,7 @@ Controls occupy a bottom gradient. The title uses the same original title art (2
The controls fade and slide away after five seconds during playback. While they are hidden, a Left/Right tap skips 10 seconds without revealing anything (quick taps add up into one seek), and holding Left/Right reveals the focused timeline for scrubbing. OK and Down reveal them; Back hides them before exiting. Audio and subtitle panels open above their icons and restore focus when dismissed. A gear exposes quality, audio, subtitles, speed, and chapters. Quality is one list shared with Settings: Original quality (the default, direct stream of the source video), then 4K, 1080p, 720p and 480p conversions. The timeline includes buffered progress and server-generated video/chapter previews. Skip actions have opaque contrast surfaces. The controls fade and slide away after five seconds during playback. While they are hidden, a Left/Right tap skips 10 seconds without revealing anything (quick taps add up into one seek), and holding Left/Right reveals the focused timeline for scrubbing. OK and Down reveal them; Back hides them before exiting. Audio and subtitle panels open above their icons and restore focus when dismissed. A gear exposes quality, audio, subtitles, speed, and chapters. Quality is one list shared with Settings: Original quality (the default, direct stream of the source video), then 4K, 1080p, 720p and 480p conversions. The timeline includes buffered progress and server-generated video/chapter previews. Skip actions have opaque contrast surfaces.
Credits (automatically, or through Skip credits) and episode endings open Up Next: the playing video shrinks to a 352 × 198 dp frame at the top left and keeps playing, beside the next episode's still (top right, fading into the page), title art, episode title, facts line and three-line synopsis, with the season and related shows below. The page is drawn beneath the PlayerView so its SurfaceView shows through. Play next episode carries the only countdown (Settings › Autoplay next episode) as a sweeping fill; any remote press stops it. Left from Play next focuses the video; selecting it, or Back, returns to the full-screen credits. Each player session has a unique Media3 session ID so overlapping Compose disposal and next-episode creation cannot collide. Episode endings and Skip credits open a five-second, cancellable next-episode countdown with season episodes and related shows. Each player session has a unique Media3 session ID so overlapping Compose disposal and next-episode creation cannot collide.
Settings includes a persistent watched percentage. Timeline reporting scrobbles the item in Plex once the selected percentage is reached, retries a failed write, and avoids repeated scrobbles within the same player session. This preference belongs to Kaleido and does not change the Plex server's global settings. Explicit watched changes refresh the title and parent episode counts across browsing caches. Settings includes a persistent watched percentage. Timeline reporting scrobbles the item in Plex once the selected percentage is reached, retries a failed write, and avoids repeated scrobbles within the same player session. This preference belongs to Kaleido and does not change the Plex server's global settings. Explicit watched changes refresh the title and parent episode counts across browsing caches.

View file

@ -22,7 +22,7 @@ Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Setting
D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex. D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex.
Original quality is the default, requesting the source video and remuxing where supported, with a 1080p conversion fallback. The player gear exposes the same quality preference as Settings, along with audio, subtitles, speed and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Credits and episode endings open Up Next: the video keeps playing in a corner beside the next episode, its single countdown, the season and related shows. Original quality is the default, requesting the source video and remuxing where supported, with a 1080p conversion fallback. The player gear exposes the same quality preference as Settings, along with audio, subtitles, speed and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Episode endings and Skip credits show a cancellable five-second next-episode countdown, season episodes, and related shows.
## Updates and releases ## Updates and releases

View file

@ -259,9 +259,3 @@ The actual non-debuggable release was also opened through Search and title detai
## Silo-style browse and details redesign - 2026-10-28 ## Silo-style browse and details redesign - 2026-10-28
Verified on the onn with the profiled release (baseline profile installed, `speed-profile` compiled). The first Home version used AnimatedVisibility/AnimatedContent and read the hero mode in the catalog's composition; `profile_home.py` failed at p95 39.9 ms, and atrace showed recomposition and layout on nearly every frame plus one 44 ms frame on entry. Driving the header, copy and artwork fades from single animations read only in graphics layers, and keeping the invisible preview composed under the hero, brought five hero → Continue Watching transitions to median 16.9 ms, p95 25.1 ms and none above 33.34 ms (the pre-redesign baseline was p95 28.6 ms). `repro_runtime.py browse` passed at Movies p95 31–34 ms; a 1280 × 720 preview frame raised it to 36 ms through larger texture uploads and was not kept. Moving along a season's episode row measured p95 32 ms. `verify_ui.py browse` (8 checks), `repro_runtime.py sections`, `verify_settings.py`, `verify_details_layout.py` and `verify_movie_details.py` passed. The last two needed their library navigation updated for the genre/sort filter row; titles shown as title art are now read from their content description. `verify_details.py` and the live playback suites were not run: they change Plex state, and `verify_details.py` still expects Mark watched directly after Watch next on shows. The player title area was observed during a brief accidental playback, which Plex did not record as progress. Verified on the onn with the profiled release (baseline profile installed, `speed-profile` compiled). The first Home version used AnimatedVisibility/AnimatedContent and read the hero mode in the catalog's composition; `profile_home.py` failed at p95 39.9 ms, and atrace showed recomposition and layout on nearly every frame plus one 44 ms frame on entry. Driving the header, copy and artwork fades from single animations read only in graphics layers, and keeping the invisible preview composed under the hero, brought five hero → Continue Watching transitions to median 16.9 ms, p95 25.1 ms and none above 33.34 ms (the pre-redesign baseline was p95 28.6 ms). `repro_runtime.py browse` passed at Movies p95 31–34 ms; a 1280 × 720 preview frame raised it to 36 ms through larger texture uploads and was not kept. Moving along a season's episode row measured p95 32 ms. `verify_ui.py browse` (8 checks), `repro_runtime.py sections`, `verify_settings.py`, `verify_details_layout.py` and `verify_movie_details.py` passed. The last two needed their library navigation updated for the genre/sort filter row; titles shown as title art are now read from their content description. `verify_details.py` and the live playback suites were not run: they change Plex state, and `verify_details.py` still expects Mark watched directly after Watch next on shows. The player title area was observed during a brief accidental playback, which Plex did not record as progress.
## Kaleidoscope startup animation - 2026-10-31
The iris was replaced with Kaleido Desktop's kaleidoscope (approved there from a canvas prototype): a mirrored field of shards turns and gathers into the six facets, then the existing fly-through exit, zoomed 30× instead of 52× because the mark is larger than the old lockup. The gather is fastest at its start, so the TV keeps the iris's safeguard: a 260 ms still, faint shard field that holds (at most 700 ms) until `busy` clears and four steady frames arrive. The Compose port draws only paths and gradients (Screen and Plus blend modes); there is no blur.
On the onn with the profiled release, a screen recording of a cold start (ignored `evidence/private/splash-kaleidoscope/`) showed the still field for about 0.8 s, the gather, the settled mark and the reveal into Home. Framestats from three cold starts, bucketed per 250 ms: the 75–190 ms frames fall in the first 0.75 s, inside the hold; during the gather runs 1–2 completed every frame within 26 ms at 15 frames per bucket, and run 3 had a few 30–41 ms frames with 13–15 frames per bucket. Frames from about 2.25 s include Home appearing beneath and reach 42–69 ms, as with the iris. GPU time stayed below 12 ms at p99. These are device samples, not a guarantee; the Fire TV and TCL were not measured. `Build.ps1 -Release -Test` and `repro_runtime.py sections` passed, and the optimized release was left on Home.

View file

@ -4,9 +4,6 @@ ROOT=pathlib.Path(__file__).resolve().parents[1]
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l) version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l)
apk=ROOT/'app/build/outputs/apk/release/app-release.apk' apk=ROOT/'app/build/outputs/apk/release/app-release.apk'
if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.') if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.')
# The APK left by an earlier build must not be published under this version's name.
from verify_distribution import check_apk
check_apk(apk,version['versionName'],int(version['versionCode']))
out=ROOT/'distribution';out.mkdir(exist_ok=True) out=ROOT/'distribution';out.mkdir(exist_ok=True)
shutil.copyfile(apk,out/'Kaleido.apk') shutil.copyfile(apk,out/'Kaleido.apk')
digest=hashlib.sha256(apk.read_bytes()).hexdigest() digest=hashlib.sha256(apk.read_bytes()).hexdigest()

View file

@ -105,28 +105,24 @@ def credits():
marker=next(m for m in item['Marker'] if m['type']=='credits') marker=next(m for m in item['Marker'] if m['type']=='credits')
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c') adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2','--ez','testValidation','true') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2','--ez','testValidation','true')
await_ready(7599) await_ready(7599);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits')
def log():return adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
# Automatic credits open Up Next at once; with "Show button" the Skip credits button opens it.
deadline=time.monotonic()+4
while time.monotonic()<deadline and 'POSTPLAY focus=play' not in log():time.sleep(.2)
if 'POSTPLAY focus=play' not in log():
key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits')
screenshot('skip-credits-contrast');key(23) screenshot('skip-credits-contrast');key(23)
deadline=time.monotonic()+8 deadline=time.monotonic()+8
while time.monotonic()<deadline and 'POSTPLAY focus=play' not in log():time.sleep(.1) while time.monotonic()<deadline:
assert 'POSTPLAY focus=play' in log(),'Up Next initial action never received focus' time.sleep(.1)
screenshot('up-next') ready=adb('logcat','-d','-s','KaleidoPlayback:I','*:S').decode(errors='replace')
key(20) # any press stops the countdown if 'POSTPLAY focus=play' in ready:break
time.sleep(6);root=snapshot();found=labels(root) assert 'POSTPLAY focus=play' in ready,'Postplay initial action never received focus'
assert 'Up next' in found or 'UP NEXT' in found,'Cancellation failed to keep Up Next open' key(22);key(23)
assert any(l.startswith('Season ') for l in found),'Season episodes absent' wait(lambda r:'Autoplay off' in labels(r),'Autoplay cancellation')
assert 'Related shows' in found,'Related shows absent' screenshot('postplay-season-and-related');time.sleep(6)
logs=log() root=snapshot();assert 'Up next' in labels(root),'Cancellation failed to keep postplay open'
assert 'AUTOPLAY cancelled' in logs and 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced' assert 'Episodes in this season' in labels(root),'Season episodes absent'
key(4);time.sleep(1) assert 'Related shows' in labels(root),'Related shows absent'
assert 'POSTPLAY closed' in log(),'Back did not return to the video' logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
(OUT/'postplay-cancel.log').write_text(log()) assert 'reason=skip-credits' in logs,'Skip credits did not open postplay'
print('PASS credits -> Up Next, episode/related rows, any press stops autoplay, Back returns to video') assert 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced'
(OUT/'postplay-cancel.log').write_text(logs)
print('PASS skip credits -> postplay, episode/related rows, cancellable autoplay')
if __name__=='__main__':globals()[sys.argv[1]]() if __name__=='__main__':globals()[sys.argv[1]]()

View file

@ -1,4 +1,4 @@
"""Validate optional themes and the normal audio path on the authorized onn; restore the prior audio preferences.""" """Validate optional themes and PCM boost on the authorized onn; restore the prior audio preferences."""
import re,time,sys,xml.etree.ElementTree as ET import re,time,sys,xml.etree.ElementTree as ET
from device import adb,OUT,screenshot from device import adb,OUT,screenshot
from verify_ui import launch,key,text,focused,focus,snapshot,labels,wait,passed from verify_ui import launch,key,text,focused,focus,snapshot,labels,wait,passed
@ -38,7 +38,7 @@ if __name__=='__main__':
original_xml=adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml') original_xml=adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')
(OUT/'030-audio-original-preferences.xml').write_bytes(original_xml) (OUT/'030-audio-original-preferences.xml').write_bytes(original_xml)
tree=ET.fromstring(original_xml) tree=ET.fromstring(original_xml)
for name,kind,value in [('themeMusic','boolean','true'),('themeVolume','int','20')]: for name,kind,value in [('themeMusic','boolean','true'),('themeVolume','int','20'),('volumeBoostDb','int','6')]:
node=next((n for n in tree if n.get('name')==name),None) node=next((n for n in tree if n.get('name')==name),None)
if node is None:node=ET.SubElement(tree,kind,{'name':name}) if node is None:node=ET.SubElement(tree,kind,{'name':name})
node.set('value',value) node.set('value',value)
@ -51,10 +51,14 @@ if __name__=='__main__':
key(20);focused('Theme music volume') key(20);focused('Theme music volume')
original_volume=re.search(r'(\d+)%$',focus(snapshot())).group(1)+'%' original_volume=re.search(r'(\d+)%$',focus(snapshot())).group(1)+'%'
choose([str(n)+'%' for n in range(10,101,10)],'20%');focused('Theme music volume') choose([str(n)+'%' for n in range(10,101,10)],'20%');focused('Theme music volume')
settings(1);focused('Playback quality');key(20,6);focused('Volume boost')
current=focus(snapshot());original_boost='Off (+0 dB)' if current.endswith('Off (+0 dB)') else re.search(r'\+\d+ dB$',current).group()
choose(['Off (+0 dB)','+3 dB','+6 dB','+9 dB','+12 dB'],'+6 dB');focused('Volume boost')
screenshot('030-volume-boost')
settings(3);key(20);focused('Theme music');assert focus(snapshot()).endswith('On') settings(3);key(20);focused('Theme music');assert focus(snapshot()).endswith('On')
key(20);focused('Theme music volume');assert focus(snapshot()).endswith('20%') key(20);focused('Theme music volume');assert focus(snapshot()).endswith('20%')
screenshot('030-theme-settings') screenshot('030-theme-settings')
passed('Theme toggle and theme volume persist through cold starts; dialogs restore focus') passed('Theme toggle, theme volume and boost persist through cold starts; dialogs restore focus')
try: try:
adb('logcat','-c');open_silo();wait_log('KaleidoTheme: READY volume=20%') adb('logcat','-c');open_silo();wait_log('KaleidoTheme: READY volume=20%')
screenshot('030-silo-theme') screenshot('030-silo-theme')
@ -72,24 +76,24 @@ if __name__=='__main__':
# Actual video uses validation mode, which avoids changing Plex progress. # Actual video uses validation mode, which avoids changing Plex progress.
adb('logcat','-c') adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','0','--ez','testValidation','true') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','0','--ez','testValidation','true')
wait_log('STOP');wait_log('READY item=7599') wait_log('STOP');wait_log('BOOST processing PCM db=6');wait_log('READY item=7599')
time.sleep(4) time.sleep(4)
audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl') audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl')
(OUT/'030-audio-validation.jsonl').write_bytes(audit) (OUT/'030-boost-validation.jsonl').write_bytes(audit)
import json import json
events=[json.loads(line) for line in audit.decode().splitlines()] events=[json.loads(line) for line in audit.decode().splitlines()]
assert any(e.get('event')=='audioAdvancing' for e in events),'Decoded audio must advance' assert any(e.get('event')=='audioAdvancing' for e in events),'Decoded audio must advance'
assert any(e.get('event')=='firstFrame' for e in events),'Video must render' assert any(e.get('event')=='firstFrame' for e in events),'Video must render'
passed('Theme stops for actual video; audio and video advance') passed('Theme stops for actual video; +6 dB processor receives decoded PCM and audio/video advance')
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c') adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true')
wait_log('READY item=9776');time.sleep(4) wait_log('BOOST processing PCM db=6');wait_log('READY item=9776');time.sleep(4)
movie_audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl') movie_audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl')
(OUT/'030-audio-movie-validation.jsonl').write_bytes(movie_audit) (OUT/'030-boost-movie-validation.jsonl').write_bytes(movie_audit)
movie_events=[json.loads(line) for line in movie_audit.decode().splitlines()] movie_events=[json.loads(line) for line in movie_audit.decode().splitlines()]
assert any(e.get('event')=='audioAdvancing' for e in movie_events) assert any(e.get('event')=='audioAdvancing' for e in movie_events)
assert any(e.get('event')=='firstFrame' for e in movie_events) assert any(e.get('event')=='firstFrame' for e in movie_events)
passed('A real Plex-converted movie renders audio and video') passed('Volume boost also processes a real Plex-converted movie with rendered audio/video')
adb('shell','am','force-stop','tv.kaleido.app') adb('shell','am','force-stop','tv.kaleido.app')
finally: finally:
if playback_only: if playback_only:
@ -97,9 +101,11 @@ if __name__=='__main__':
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=original_xml) adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=original_xml)
assert adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')==original_xml assert adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')==original_xml
else: else:
settings(1);key(20,6);focused('Volume boost')
choose(['Off (+0 dB)','+3 dB','+6 dB','+9 dB','+12 dB'],original_boost)
settings(3);key(20);focused('Theme music') settings(3);key(20);focused('Theme music')
if focus(snapshot()).endswith('On')!=original_on:key(23) if focus(snapshot()).endswith('On')!=original_on:key(23)
key(20);focused('Theme music volume');choose([str(n)+'%' for n in range(10,101,10)],original_volume) key(20);focused('Theme music volume');choose([str(n)+'%' for n in range(10,101,10)],original_volume)
launch() launch()
(OUT/'030-audio.log').write_text(logs()) (OUT/'030-audio.log').write_text(logs())
passed('Prior theme preferences restored; device returned to Home') passed('Prior theme and boost preferences restored; device returned to Home')

View file

@ -45,7 +45,7 @@ def main():
screenshot('details-cast-restored') screenshot('details-cast-restored')
results.append('Actor titles match both Plex libraries; title and cast focus restore');print('PASS '+results[-1],flush=True) results.append('Actor titles match both Plex libraries; title and cast focus restore');print('PASS '+results[-1],flush=True)
key(4);key(4);focused('Home');key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23) key(4);key(4);focused('Home');key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Show library filters loaded');focused('Library');key(20) wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Show library filters loaded');focused('Library');key(20)
if show['title'] not in focus(snapshot()):key(21) if show['title'] not in focus(snapshot()):key(21)
focused(show['title']);key(23) focused(show['title']);key(23)
text('Seasons');focused('Watch next');text('Mark watched');key(22);focused('Mark watched');touched.add(SHOW);key(23);focused('Mark unwatched') text('Seasons');focused('Watch next');text('Mark watched');key(22);focused('Mark watched');touched.add(SHOW);key(23);focused('Mark unwatched')

View file

@ -4,9 +4,9 @@ from device import screenshot
from verify_ui import launch,key,focused,wait,focus,labels,snapshot from verify_ui import launch,key,focused,wait,focus,labels,snapshot
launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23) launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Show library loaded');focused('Library');key(20) wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Show library loaded');focused('Library');key(20)
# The genre/sort filters sit between the section tabs and the grid. # The genre/sort filters sit between the section tabs and the grid.
if focus(snapshot()).startswith('Unwatched'):key(20) if 'All genres' in focus(snapshot()):key(20)
# The grid is entered beneath the filter that held focus; walk back to the first column. # The grid is entered beneath the filter that held focus; walk back to the first column.
for _ in range(6): for _ in range(6):
if '3 Body Problem' in focus(snapshot()):break if '3 Body Problem' in focus(snapshot()):break

View file

@ -1,56 +0,0 @@
"""Check that an APK really is the release it is published as.
Used by package_release.py before staging, and by CI against the checked-in distribution:
a stale or debug APK must not pass because its checksum and manifest were regenerated around it.
"""
import argparse, hashlib, json, os, pathlib, re, shutil, subprocess, sys
ROOT=pathlib.Path(__file__).resolve().parents[1]
PACKAGE='tv.kaleido.app'
def properties():
return dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l)
def aapt2():
names=['aapt2.exe','aapt2'] if os.name=='nt' else ['aapt2']
roots=[ROOT/'.tools/sdk']+[pathlib.Path(os.environ[k]) for k in ('ANDROID_HOME','ANDROID_SDK_ROOT') if os.environ.get(k)]
for root in roots:
tools=sorted((root/'build-tools').glob('*'),key=lambda p:[int(x) if x.isdigit() else 0 for x in p.name.split('.')],reverse=True) if (root/'build-tools').is_dir() else []
for folder in tools:
for name in names:
if (folder/name).is_file():return str(folder/name)
found=shutil.which('aapt2')
if found:return found
raise SystemExit('aapt2 was not found. Install Android build-tools or set ANDROID_HOME.')
def badging(apk):
"""(package, versionName, versionCode, debuggable) from the APK's own manifest."""
out=subprocess.run([aapt2(),'dump','badging',str(apk)],capture_output=True,text=True,check=True).stdout
m=re.search(r"^package: name='([^']+)' versionCode='(\d+)' versionName='([^']+)'",out,re.M)
if not m:raise SystemExit(f'Could not read the version of {apk}.')
return m.group(1),m.group(3),int(m.group(2)),'application-debuggable' in out
def check_apk(apk,version_name,version_code):
package,name,code,debuggable=badging(apk)
problems=[]
if package!=PACKAGE:problems.append(f'package is {package}, expected {PACKAGE}')
if (name,code)!=(version_name,version_code):problems.append(f'APK is {name} ({code}), expected {version_name} ({version_code}); rebuild it')
if debuggable:problems.append('APK is a debuggable build, not the release')
if problems:raise SystemExit(f'{apk}: '+'; '.join(problems)+'.')
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--release',action='store_true',help='also require the distribution to match version.properties (tag builds)')
args=parser.parse_args()
out=ROOT/'distribution';apk=out/'Kaleido.apk'
if not apk.exists():print('No distribution to verify.');return
digest=hashlib.sha256(apk.read_bytes()).hexdigest()
if (out/'Kaleido.apk.sha256').read_text().split()[0]!=digest:raise SystemExit('Kaleido.apk does not match Kaleido.apk.sha256.')
manifest=json.loads((out/'latest.json').read_text(encoding='utf-8'))
check_apk(apk,manifest['version'],int(manifest['versionCode']))
if args.release:
version=properties()
if (manifest['version'],int(manifest['versionCode']))!=(version['versionName'],int(version['versionCode'])):
raise SystemExit('distribution/latest.json does not match version.properties; run scripts/package_release.py.')
print('Distribution verified:',manifest['version'],f"({manifest['versionCode']})",'SHA-256',digest)
if __name__=='__main__':main()

View file

@ -58,7 +58,7 @@ def section_check(tab,media_type):
for _ in range(8): for _ in range(8):
if focus(snapshot())=='Animation':break if focus(snapshot())=='Animation':break
key(22) key(22)
focused('Animation');key(23);text('Z') focused('Animation');key(23);text('Animation ⌄');text('Z')
expected,offset=first_at_letter('',media_type,'S','Animation') expected,offset=first_at_letter('',media_type,'S','Animation')
jump('S',expected) jump('S',expected)
screenshot('030-'+media_type+'-animation-jump') screenshot('030-'+media_type+'-animation-jump')

View file

@ -4,11 +4,11 @@ from device import screenshot
from verify_ui import launch,key,focused,wait,focus,labels,snapshot from verify_ui import launch,key,focused,wait,focus,labels,snapshot
launch();key(22);focused('Movies');key(20);focused('Discover');key(22);focused('Library');key(23) launch();key(22);focused('Movies');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Movie library loaded') wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Movie library loaded')
key(20) key(20)
# The genre/sort filters sit between the section tabs and the grid. # The genre/sort filters sit between the section tabs and the grid.
if focus(snapshot()).startswith('Unwatched'):key(20) if 'All genres' in focus(snapshot()):key(20)
wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and not focus(r).startswith('Unwatched'),'Movie card focus') wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and 'All genres' not in focus(r),'Movie card focus')
selected=focus(snapshot());key(23) selected=focus(snapshot());key(23)
wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action') wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action')
root=snapshot();screenshot('movie-details-0.1.11') root=snapshot();screenshot('movie-details-0.1.11')

View file

@ -1,132 +0,0 @@
"""Previous episode, timed auto-skip with remote cancellation, server-picker Back and resume refresh.
Requires the **debug** build (test intents and run-as). Playback runs as validation, so it reports no
Plex progress. The refresh check moves one Continue Watching offset and restores it; the auto-skip
preferences are restored as found.
"""
import json,pathlib,re,sys,time,urllib.request,urllib.parse
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from device import adb,ROOT,screenshot
from verify_ui import key,snapshot,focus,labels,wait,focused,text,launch
from repro_runtime import await_ready
PREFS='shared_prefs/preferences.xml'
INTRO_EPISODE=11621 # The Big Bang Theory 10x24: intro marker 117.4-146.7 s
SILO_FIRST,SILO_SECOND=7599,8594
def logs(tag='KaleidoPlayback'):return adb('logcat','-d','-s',f'{tag}:I','AndroidRuntime:E','*:S').decode(errors='replace')
def wait_log(needle,timeout=30,tag='KaleidoPlayback'):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
if needle in logs(tag):return
time.sleep(.3)
raise AssertionError(f'Log never showed {needle!r}')
def start(item,offset):
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item),'--el','testOffset',str(offset),'--ei','testMode','1','--ez','testValidation','true')
await_ready(item)
def read_prefs():return adb('shell','run-as','tv.kaleido.app','cat',PREFS).decode()
def write_prefs(xml):
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > '+PREFS+'"',data=xml.encode())
def with_int(xml,name,value):
entry=f'<int name="{name}" value="{value}" />'
pattern=re.compile(r'<int name="'+name+r'" value="-?\d+" />')
return pattern.sub(entry,xml) if pattern.search(xml) else xml.replace('</map>',f' {entry}\n</map>')
def auto_skip():
start(INTRO_EPISODE,112000)
wait_log('AUTOSKIP countdown intro seconds=5')
root=wait(lambda r:'Skipping intro' in labels(r),'Pending skip reads "Skipping intro", without a number')
assert not any(re.search(r'Skip(ping)? intro.*\d',l) for l in labels(root)),'Skip button shows a numeric countdown'
screenshot('auto-skip-pending')
wait_log(f'AUTOSKIP intro item={INTRO_EPISODE}',timeout=15)
assert 'AUTOSKIP cancelled' not in logs()
print('PASS intro skips itself after the countdown, shown as a fill rather than a number',flush=True)
for code,name in ((20,'Down'),(4,'Back')):
start(INTRO_EPISODE,112000)
wait_log('AUTOSKIP countdown intro')
key(code);wait_log('AUTOSKIP cancelled intro',timeout=5)
time.sleep(7)
assert f'AUTOSKIP intro item={INTRO_EPISODE}' not in logs(),f'{name} did not cancel the automatic skip'
root=wait(lambda r:'Skip intro' in labels(r),'Manual Skip intro stays available after cancelling')
assert adb('shell','pidof','tv.kaleido.app').strip(),'Player process exited'
assert 'Skipping intro' not in labels(root)
print(f'PASS {name} cancels the automatic skip and leaves the player open',flush=True)
screenshot('auto-skip-cancelled')
key(4);key(4)
def previous_episode():
start(SILO_SECOND,90000)
key(127);focused('Play');screenshot('player-bar-episode')
key(21);focused('Back 10 seconds');key(21);focused('Previous episode');key(23)
await_ready(SILO_FIRST)
assert 'FATAL EXCEPTION' not in logs(),'Previous episode crashed'
print('PASS Previous episode replaced the player with the earlier episode',flush=True)
time.sleep(2);key(127);focused('Play')
# The series' first episode has no previous one once its season list has loaded.
wait(lambda r:'Next episode' in labels(r) and 'Previous episode' not in labels(r),'No Previous episode on the first episode')
key(21);focused('Back 10 seconds');key(21)
assert 'Back 10 seconds' in focus(snapshot()) or 'Exit playback' in focus(snapshot())
print('PASS first episode offers Next but not Previous',flush=True)
key(4);key(4)
def server_picker():
launch();key(22,4);focused('Settings');key(23);focused('Switch account');key(22)
if 'Choose server' not in focus(snapshot()):print('SKIP no account-linked server list (server-token session)');key(4);return
key(23);text('Choose your Plex server');screenshot('server-picker')
key(4)
wait(lambda r:'Choose your Plex server' not in labels(r) and 'Choose server' in labels(r),'Back closes the server picker over Settings')
assert adb('shell','pidof','tv.kaleido.app').strip()
key(22) # Choose server again, now via the Cancel button
if 'Choose server' not in focus(snapshot()):key(21)
focused('Choose server');key(23);text('Choose your Plex server')
for _ in range(12):
if focus(snapshot())=='Cancel':break
key(20)
focused('Cancel');key(23)
wait(lambda r:'Choose your Plex server' not in labels(r) and 'Choose server' in labels(r),'Cancel closes the server picker')
print('PASS Back and Cancel close Settings > Choose server',flush=True)
key(4)
def plex(path,params):
env=dict(l.strip().split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#'))
url=env['PLEX_SERVER_URL'].strip('"\'').rstrip('/')+path+'?'+urllib.parse.urlencode(params)
req=urllib.request.Request(url,headers={'X-Plex-Token':env['PLEX_TOKEN'].strip('"\''),'Accept':'application/json','X-Plex-Client-Identifier':'kaleido-development','X-Plex-Product':'Kaleido'})
with urllib.request.urlopen(req,timeout=20) as r:return r.read()
def offset(item,field='viewOffset'):
from inspect_server import get
return int(get(f'/library/metadata/{item}')['Metadata'][0].get(field,0))
def set_offset(item,ms):plex('/:/progress',{'key':str(item),'identifier':'com.plexapp.plugins.library','time':str(ms),'state':'stopped'})
def refresh():
original=offset(SILO_FIRST)
# Continue Watching progress is compared in 5% steps; move by more than one step each time.
step=offset(SILO_FIRST,'duration')*6//100
try:
launch();time.sleep(4);adb('logcat','-c')
# Watched elsewhere while Kaleido is in the background: shown promptly on return.
key('KEYCODE_HOME');time.sleep(3)
set_offset(SILO_FIRST,original+step)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
began=time.monotonic();wait_log('APPLIED',timeout=10,tag='KaleidoSync')
print(f'PASS returning to Kaleido applied Continue Watching changes in {time.monotonic()-began:.1f}s',flush=True)
# Watched elsewhere while Kaleido stays open: the background poll picks it up.
time.sleep(3);adb('logcat','-c');set_offset(SILO_FIRST,original+2*step);began=time.monotonic()
wait_log('APPLIED',timeout=25,tag='KaleidoSync')
print(f'PASS open Kaleido applied a progress change from another device in {time.monotonic()-began:.1f}s',flush=True)
finally:
set_offset(SILO_FIRST,original)
assert offset(SILO_FIRST)==original,'Fixture progress was not restored'
if __name__=='__main__':
phases=sys.argv[1:] or ['previous_episode','auto_skip','server_picker','refresh']
original=read_prefs()
try:
if 'auto_skip' in phases:
write_prefs(with_int(with_int(original,'autoSkipIntroSeconds',5),'autoSkipCreditsSeconds',0))
for phase in phases:globals()[phase]()
finally:
write_prefs(original)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')

View file

@ -10,10 +10,7 @@ key(20);focused('Remote quality');key(23)
wait(lambda r:any(q in focus(r) for q in ('Original quality','4K','1080p','720p','480p')),'Remote quality choices');key(4);focused('Remote quality') wait(lambda r:any(q in focus(r) for q in ('Original quality','4K','1080p','720p','480p')),'Remote quality choices');key(4);focused('Remote quality')
key(20);focused('Watched status');key(23);focused('80%');key(4);focused('Watched status') key(20);focused('Watched status');key(23);focused('80%');key(4);focused('Watched status')
key(20);focused('Autoplay next episode');key(23);focused('After 5 seconds');key(4);focused('Autoplay next episode') key(20);focused('Autoplay next episode');key(23);focused('After 5 seconds');key(4);focused('Autoplay next episode')
key(20);focused('Skip intros');key(23) key(20);focused('Skip intros');key(20);focused('Skip credits')
wait(lambda r:any(q in focus(r) for q in ('Show button','Automatically after')),'Skip intro delay choices');key(4);focused('Skip intros')
key(20);focused('Skip credits');key(23)
wait(lambda r:any(q in focus(r) for q in ('Show button','Automatically after')),'Skip credits delay choices');key(4);focused('Skip credits')
print('PASS playback dialogs cancel back to their controls',flush=True) print('PASS playback dialogs cancel back to their controls',flush=True)
screenshot('settings-playback-current') screenshot('settings-playback-current')
key(21);focused('Playback');key(20);focused('Subtitles');key(22);focused('Size');key(23);focused('Normal');key(4);focused('Size') key(21);focused('Playback');key(20);focused('Subtitles');key(22);focused('Size');key(23);focused('Normal');key(4);focused('Size')

View file

@ -47,7 +47,7 @@ def browse():
key(4);focused(selected);passed('Discovery details returns to the same focused card') key(4);focused(selected);passed('Discovery details returns to the same focused card')
key(19);wait(lambda r:focus(r) in ('Play','Resume'),'Return to Home hero');key(19);focused('Home');key(22);text('Recently released');focused('Movies') key(19);wait(lambda r:focus(r) in ('Play','Resume'),'Return to Home hero');key(19);focused('Home');key(22);text('Recently released');focused('Movies')
capture('movies-discover');key(20);focused('Discover');key(22);focused('Library');key(23) capture('movies-discover');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Library filters');focused('Library');capture('movies-library') text('All genres ⌄');focused('Library');capture('movies-library')
passed('Movies prioritizes recent releases and retains a separate filtered A-Z grid') passed('Movies prioritizes recent releases and retains a separate filtered A-Z grid')
key(20);wait(lambda r:bool(focus(r)) and 'Library' not in focus(r),'Library content or filter focus') key(20);wait(lambda r:bool(focus(r)) and 'Library' not in focus(r),'Library content or filter focus')
key(4);focused('Discover');key(19);focused('Movies');key(22) key(4);focused('Discover');key(19);focused('Movies');key(22)

View file

@ -1,2 +1,2 @@
versionName=0.8.1 versionName=0.6.1
versionCode=25 versionCode=21