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

@ -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"
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}}
}

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. */
@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)

View file

@ -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…"

View file

@ -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.

View file

@ -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")

View file

@ -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)

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.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"))

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)
}
}