From 4780bdcdb241038d5e61b0224950b96e28f8de67 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 22:52:52 -0700 Subject: [PATCH] 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 --- AGENTS.md | 5 ++- README.md | 2 +- .../main/java/tv/kaleido/app/BrowseScreens.kt | 7 +--- .../tv/kaleido/app/CompatibleAudioSink.kt | 8 +--- .../java/tv/kaleido/app/KaleidoViewModel.kt | 17 ++++++-- app/src/main/java/tv/kaleido/app/Playback.kt | 40 ++++++++++++++----- app/src/main/java/tv/kaleido/app/PlexApi.kt | 10 ++++- .../java/tv/kaleido/app/SettingsScreen.kt | 20 +--------- .../main/java/tv/kaleido/app/VolumeBoost.kt | 29 -------------- .../tv/kaleido/app/AudioPreferencesTest.kt | 23 ----------- .../tv/kaleido/app/PlaybackTerminationTest.kt | 13 ++++++ scripts/verify_audio_preferences.py | 26 +++++------- scripts/verify_details.py | 2 +- scripts/verify_details_layout.py | 4 +- scripts/verify_library_jump.py | 2 +- scripts/verify_movie_details.py | 6 +-- scripts/verify_ui.py | 2 +- 17 files changed, 89 insertions(+), 127 deletions(-) delete mode 100644 app/src/main/java/tv/kaleido/app/VolumeBoost.kt create mode 100644 app/src/test/java/tv/kaleido/app/PlaybackTerminationTest.kt diff --git a/AGENTS.md b/AGENTS.md index 32b685d..2115e06 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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_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_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: @@ -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. - **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. -- 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 diff --git a/README.md b/README.md index 42a9272..8158598 100644 --- a/README.md +++ b/README.md @@ -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. - **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. - **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. diff --git a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt index af81101..b594f7e 100644 --- a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt +++ b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt @@ -158,7 +158,6 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List,index:Int, val name=if(vm.page.kind=="movies")"Movies"else "TV Shows" LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()} var sortMenu by remember{mutableStateOf(false)} - var genreMenu by remember{mutableStateOf(false)} var sectionMenu by remember{mutableStateOf(false)} 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()} @@ -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)) { Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp) 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",selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)} + TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus},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} } 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 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()}} } 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(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}} } diff --git a/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt b/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt index 93be599..51a537a 100644 --- a/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt +++ b/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt @@ -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. */ @androidx.annotation.OptIn(UnstableApi::class) -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) +internal class CompatibleAudioSink(sink:AudioSink):ForwardingAudioSink(sink) { @Suppress("DEPRECATION") override fun configure(config:AudioSink.AudioSinkConfig) { val format=compatiblePcmFormat(config.format) diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt index 26c22f2..c9fef64 100644 --- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -134,7 +134,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { var colourWash by mutableStateOf(preferences.getBoolean("colourWash",true)); 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 volumeBoostDb by mutableIntStateOf(preferences.getInt("volumeBoostDb",0).coerceIn(0,12)); private set var episodeQueue by mutableStateOf(emptyList<Title>());private set var relatedShows by mutableStateOf(emptyList<Title>());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} }.asCoroutineDispatcher() 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. if(BuildConfig.DEBUG) { 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) 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 loadCategoryArtworks() { 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 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() { val selectedSection=section ?: return 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} } } + /** 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(){ val finished=playing 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 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 chooseVolumeBoostDb(value:Int){volumeBoostDb=value.coerceIn(0,12);preferences.edit().putInt("volumeBoostDb",volumeBoostDb).apply()} fun checkUpdate(manual: Boolean=true){viewModelScope.launch { if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch updateStatus="Checking for updates…" diff --git a/app/src/main/java/tv/kaleido/app/Playback.kt b/app/src/main/java/tv/kaleido/app/Playback.kt index 9670a0d..a7ec7e6 100644 --- a/app/src/main/java/tv/kaleido/app/Playback.kt +++ b/app/src/main/java/tv/kaleido/app/Playback.kt @@ -54,10 +54,9 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { private val renderers=object:DefaultRenderersFactory(app) { override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink = 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&&vm.volumeBoostDb==0) + .setEnableFloatOutput(enableFloatOutput) .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams) - .build(),decodedOnly=vm.volumeBoostDb>0) + .build()) }.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing() 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) @@ -109,13 +108,16 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { private var fallbackPending=false private var nativeSelectionApplied=false 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 { 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) { if(synced) { 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)} .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. player.addAnalyticsListener(object:androidx.media3.exoplayer.analytics.AnalyticsListener { 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) { 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) { 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)} 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. */ 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 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) { - if(closed||mode>=2||localValidationFile!=null||fallbackPending)return + if(closed||serverStopped||mode>=2||localValidationFile!=null||fallbackPending)return fallbackPending=true val session=streamSession;val offset=if(preparing)position else currentPosition();val resume=player.playWhenReady scope.launch { 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)) 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)} 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 serverConverting=false;serverAudioConverting=false // Empty track events from stop must not be mistaken for a missing video track. diff --git a/app/src/main/java/tv/kaleido/app/PlexApi.kt b/app/src/main/java/tv/kaleido/app/PlexApi.kt index 35608ad..54ad770 100644 --- a/app/src/main/java/tv/kaleido/app/PlexApi.kt +++ b/app/src/main/java/tv/kaleido/app/PlexApi.kt @@ -15,6 +15,10 @@ import java.io.IOException import java.util.concurrent.TimeUnit 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) { 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 @@ -128,8 +132,10 @@ class PlexApi(val clientId: String) { /** 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 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) { - 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)) + /** 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): 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) { request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT") diff --git a/app/src/main/java/tv/kaleido/app/SettingsScreen.kt b/app/src/main/java/tv/kaleido/app/SettingsScreen.kt index a01a911..70691da 100644 --- a/app/src/main/java/tv/kaleido/app/SettingsScreen.kt +++ b/app/src/main/java/tv/kaleido/app/SettingsScreen.kt @@ -47,7 +47,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { var subtitleSizeDialog by remember { mutableStateOf(false) } var subtitleStyleDialog by remember { mutableStateOf(false) } var themeVolumeDialog by remember { mutableStateOf(false) } - var volumeBoostDialog by remember { mutableStateOf(false) } val remoteFocus = remember { FocusRequester() } val autoplayFocus = remember { FocusRequester() } val introFocus = remember { FocusRequester() } @@ -56,7 +55,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { val themeMusicFocus = remember { FocusRequester() } val colourWashFocus = remember { FocusRequester() } val themeVolumeFocus = remember { FocusRequester() } - val volumeBoostFocus = remember { FocusRequester() } val categoryFocus = 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() } } val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog || - subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog || volumeBoostDialog + subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog LaunchedEffect(anyDialogOpen, dialogRestoreFocus) { if (!anyDialogOpen) { dialogRestoreFocus?.let { requester -> @@ -258,14 +256,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { leftTarget = categoryFocus[1], 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( "Completed titles keep their Plex watched status.", color = Cinema.quiet, @@ -447,17 +437,9 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { 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 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. */ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) diff --git a/app/src/main/java/tv/kaleido/app/VolumeBoost.kt b/app/src/main/java/tv/kaleido/app/VolumeBoost.kt deleted file mode 100644 index e058028..0000000 --- a/app/src/main/java/tv/kaleido/app/VolumeBoost.kt +++ /dev/null @@ -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() diff --git a/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt b/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt index fcbf68c..5613795 100644 --- a/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt +++ b/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt @@ -2,31 +2,8 @@ package tv.kaleido.app import org.junit.Assert.* 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 { - @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() { assertEquals("/library/metadata/6115/theme/1",safeThemePath("/library/metadata/6115/theme/1")) assertEquals("",safeThemePath("https://elsewhere.example/theme.mp3")) diff --git a/app/src/test/java/tv/kaleido/app/PlaybackTerminationTest.kt b/app/src/test/java/tv/kaleido/app/PlaybackTerminationTest.kt new file mode 100644 index 0000000..dd76ff8 --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/PlaybackTerminationTest.kt @@ -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) + } +} diff --git a/scripts/verify_audio_preferences.py b/scripts/verify_audio_preferences.py index f59ec3b..924fa5b 100644 --- a/scripts/verify_audio_preferences.py +++ b/scripts/verify_audio_preferences.py @@ -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 from device import adb,OUT,screenshot 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') (OUT/'030-audio-original-preferences.xml').write_bytes(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) if node is None:node=ET.SubElement(tree,kind,{'name':name}) node.set('value',value) @@ -51,14 +51,10 @@ if __name__=='__main__': key(20);focused('Theme music volume') 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') - 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') key(20);focused('Theme music volume');assert focus(snapshot()).endswith('20%') 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: adb('logcat','-c');open_silo();wait_log('KaleidoTheme: READY volume=20%') screenshot('030-silo-theme') @@ -76,24 +72,24 @@ if __name__=='__main__': # Actual video uses validation mode, which avoids changing Plex progress. adb('logcat','-c') 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) 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 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')=='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','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') - (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()] assert any(e.get('event')=='audioAdvancing' 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') finally: 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) assert adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')==original_xml 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') 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) launch() (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') diff --git a/scripts/verify_details.py b/scripts/verify_details.py index 8d8736f..b13cd91 100644 --- a/scripts/verify_details.py +++ b/scripts/verify_details.py @@ -45,7 +45,7 @@ def main(): screenshot('details-cast-restored') 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) - 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) 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') diff --git a/scripts/verify_details_layout.py b/scripts/verify_details_layout.py index 2a2e95c..54888aa 100644 --- a/scripts/verify_details_layout.py +++ b/scripts/verify_details_layout.py @@ -4,9 +4,9 @@ from device import screenshot 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) -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. -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. for _ in range(6): if '3 Body Problem' in focus(snapshot()):break diff --git a/scripts/verify_library_jump.py b/scripts/verify_library_jump.py index e784357..39c5ed1 100644 --- a/scripts/verify_library_jump.py +++ b/scripts/verify_library_jump.py @@ -58,7 +58,7 @@ def section_check(tab,media_type): for _ in range(8): if focus(snapshot())=='Animation':break 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') jump('S',expected) screenshot('030-'+media_type+'-animation-jump') diff --git a/scripts/verify_movie_details.py b/scripts/verify_movie_details.py index 51b22e0..73c0f3d 100644 --- a/scripts/verify_movie_details.py +++ b/scripts/verify_movie_details.py @@ -4,11 +4,11 @@ from device import screenshot 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) -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) # The genre/sort filters sit between the section tabs and the grid. -if 'All genres' in focus(snapshot()):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') +if focus(snapshot()).startswith('Unwatched'):key(20) +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) wait(lambda r:focus(r)=='Play' or focus(r).startswith('Resume'),'Movie play action') root=snapshot();screenshot('movie-details-0.1.11') diff --git a/scripts/verify_ui.py b/scripts/verify_ui.py index 361a528..66669f6 100644 --- a/scripts/verify_ui.py +++ b/scripts/verify_ui.py @@ -47,7 +47,7 @@ def browse(): 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') 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') 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)