Remove volume boost, honour server-stopped streams, drop the Library genre filter

Work already pending in the tree before the bug-fix pass, committed on its own:
- Remove Volume boost (it degraded audio) and its setting; keep passthrough.
- Leave playback with the server's reason when Plex stops a session
  (timeline terminationCode/terminationText); never fall back or reconnect after.
- Genre filtering lives in Categories; the Library grid lists the whole section.
- Update UI verification scripts and AGENTS.md accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-04 22:52:52 -07:00
parent 0ee43ffa76
commit 4780bdcdb2
17 changed files with 89 additions and 127 deletions

View file

@ -58,7 +58,7 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan
| `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_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:
@ -84,7 +84,8 @@ These require the private test session. Playback test intents (`testTitleId`, `t
- 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. - 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 processes decoded PCM; Off must preserve 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 was removed because it degraded audio; keep 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

@ -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 genre, watched-status and sorting controls. 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 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.
- **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

@ -158,7 +158,6 @@ 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()}
@ -207,8 +206,7 @@ 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.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",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus},selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
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()
@ -249,7 +247,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 genre or watch filter.")} if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another category 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)})
@ -257,7 +255,6 @@ 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,13 +9,7 @@ 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,private val decodedOnly:Boolean=false):ForwardingAudioSink(sink) { internal class CompatibleAudioSink(sink:AudioSink):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

@ -134,7 +134,6 @@ 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
@ -168,6 +167,8 @@ 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")
@ -453,7 +454,11 @@ 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){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;libraryJumpIndex=-1;libraryJumpLetter=null} fun setAll(value: Boolean){
// 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
@ -539,7 +544,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,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()} fun filter(sortValue: String=sort,unwatchedValue: Boolean=unwatched){sort=sortValue;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
@ -680,6 +685,11 @@ 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)}
}
fun stopPlayback(){ fun stopPlayback(){
val finished=playing val finished=playing
shuffleEpisodes=null shuffleEpisodes=null
@ -712,7 +722,6 @@ 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

@ -54,10 +54,9 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
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)
.setAudioProcessors(if(vm.volumeBoostDb>0)arrayOf(VolumeBoostProcessor(vm.volumeBoostDb){Log.i("KaleidoPlayback","BOOST processing PCM db=${vm.volumeBoostDb}")})else emptyArray()) .setEnableFloatOutput(enableFloatOutput)
.setEnableFloatOutput(enableFloatOutput&&vm.volumeBoostDb==0)
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams) .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
.build(),decodedOnly=vm.volumeBoostDb>0) .build())
}.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)
@ -109,13 +108,16 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
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);withContext(Dispatchers.Main){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)}.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")}
} }
@ -127,7 +129,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
// 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 boost=${vm.volumeBoostDb}") Log.w("KaleidoAudio","UNDERRUN item=${item.id} position=${t.eventPlaybackPositionMs} bufferMs=$duration sinceFeedMs=$elapsed mode=$mode")
} }
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}")
@ -166,23 +168,39 @@ 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(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(serverStopped)return
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&&!preparing&&!ended)report(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&&!ended)report(if(preparing||loading)"buffering"else 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)}.getOrNull()} ?: return false
stoppedByServer(termination);return true
}
private fun fallback(reason:String) { private fun fallback(reason:String) {
if(closed||mode>=2||localValidationFile!=null||fallbackPending)return if(closed||serverStopped||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) { if(!closed&&session==streamSession&&!checkServerStopped(offset)) {
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)
} }
@ -191,7 +209,7 @@ 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)return if(closed||serverStopped)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.

View file

@ -15,6 +15,10 @@ 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
@ -128,8 +132,10 @@ 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) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) } suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String) { /** Reports progress; a stream the server stopped (Plex dashboard "Stop", or shutdown) comes back as a termination. */
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)) suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String): PlaybackTermination? {
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))
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")

View file

@ -47,7 +47,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
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() }
@ -56,7 +55,6 @@ 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() } }
@ -75,7 +73,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
runCatching { entryFocus[selectedCategory].requestFocus() } runCatching { entryFocus[selectedCategory].requestFocus() }
} }
val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog || val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog ||
subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog || volumeBoostDialog subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog
LaunchedEffect(anyDialogOpen, dialogRestoreFocus) { LaunchedEffect(anyDialogOpen, dialogRestoreFocus) {
if (!anyDialogOpen) { if (!anyDialogOpen) {
dialogRestoreFocus?.let { requester -> dialogRestoreFocus?.let { requester ->
@ -258,14 +256,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
leftTarget = categoryFocus[1], leftTarget = categoryFocus[1],
onClick = { vm.chooseAutoSkipCredits(!vm.autoSkipCredits) } 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.",
color = Cinema.quiet, color = Cinema.quiet,
@ -447,17 +437,9 @@ 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"
private fun volumeBoostLabel(db: Int) = if (db == 0) "Off (+0 dB)" else "+$db dB"
/** 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

@ -1,29 +0,0 @@
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,31 +2,8 @@ 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

@ -0,0 +1,13 @@
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,4 +1,4 @@
"""Validate optional themes and PCM boost on the authorized onn; restore the prior audio preferences.""" """Validate optional themes and the normal audio path 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'),('volumeBoostDb','int','6')]: for name,kind,value in [('themeMusic','boolean','true'),('themeVolume','int','20')]:
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,14 +51,10 @@ 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, theme volume and boost persist through cold starts; dialogs restore focus') passed('Theme toggle and theme volume 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')
@ -76,24 +72,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('BOOST processing PCM db=6');wait_log('READY item=7599') wait_log('STOP');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-boost-validation.jsonl').write_bytes(audit) (OUT/'030-audio-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; +6 dB processor receives decoded PCM and audio/video advance') passed('Theme stops for actual video; audio and 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('BOOST processing PCM db=6');wait_log('READY item=9776');time.sleep(4) 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-boost-movie-validation.jsonl').write_bytes(movie_audit) (OUT/'030-audio-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('Volume boost also processes a real Plex-converted movie with rendered audio/video') passed('A real Plex-converted movie renders audio and 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:
@ -101,11 +97,9 @@ 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 and boost preferences restored; device returned to Home') passed('Prior theme 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('All genres') for x in labels(r)),'Show library filters loaded');focused('Library');key(20) wait(lambda r:any(x.startswith('Unwatched') 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('All genres') for x in labels(r)),'Show library loaded');focused('Library');key(20) wait(lambda r:any(x.startswith('Unwatched') 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 'All genres' in focus(snapshot()):key(20) if focus(snapshot()).startswith('Unwatched'):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

@ -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('Animation ⌄');text('Z') focused('Animation');key(23);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('All genres') for x in labels(r)),'Movie library loaded') wait(lambda r:any(x.startswith('Unwatched') 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 'All genres' in focus(snapshot()):key(20) if focus(snapshot()).startswith('Unwatched'):key(20)
wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and 'All genres' not in focus(r),'Movie card focus') wait(lambda r:bool(focus(r)) and focus(r) not in ('Library','Discover') and not focus(r).startswith('Unwatched'),'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

@ -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)
text('All genres ⌄');focused('Library');capture('movies-library') wait(lambda r:any(x.startswith('Unwatched') for x in labels(r)),'Library filters');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)