Release Kaleido 0.5.0 with source bitrate, audio selection and show shuffle
All checks were successful
Validate and publish Kaleido / android (push) Successful in 3m4s

This commit is contained in:
Elijah 2026-10-28 11:19:25 -07:00
parent eeebc9af38
commit dedf62a19e
19 changed files with 372 additions and 32 deletions

View file

@ -1,5 +1,12 @@
# Kaleido releases
## 0.5.0
- Show the selected version's source bitrate beside Original quality in the playback quality menu.
- Add a named Audio entry to Playback options alongside the speaker button. Preserve position, pause state and selected tracks when switching audio or rebuilding a Plex stream.
- Add Shuffle on TV show pages. Play episodes from all seasons in repeating shuffled cycles, starting each episode from the beginning and continuing even when ordinary autoplay is off. Seasons keep their usual Play action.
- Record sparse audio underrun and sink-error diagnostics for investigating intermittent dropouts. A short Infinity War check did not reproduce the reported stutter; a fix for that symptom is not yet confirmed.
## 0.4.1
- Make Categories about the genre: large centered labels over dim artwork with subdued natural color, a compact four-column grid and a restrained focus outline. Remove title captions and FILM/SERIES badges from category cards.

View file

@ -0,0 +1,56 @@
package tv.kaleido.app
import android.content.Intent
import android.media.session.MediaSessionManager
import android.media.session.PlaybackState
import android.os.SystemClock
import androidx.lifecycle.ViewModelProvider
import androidx.test.platform.app.InstrumentationRegistry
import kotlinx.coroutines.runBlocking
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
/** Opt-in real episode endings and Compose autoplay; validation mode never writes Plex progress. */
class PlaybackChangesIntegrationTest {
@Test fun shuffleContinuesAfterTwoNaturalEndingsWithNormalAutoplayOff()=runBlocking {
assumeTrue(InstrumentationRegistry.getArguments().getString("playbackChanges")=="true")
val instrumentation=InstrumentationRegistry.getInstrumentation()
val app=instrumentation.targetContext.applicationContext as KaleidoApplication
val show=app.api.details("6115")
val episodes=app.api.allEpisodes(show.id)
assertTrue(episodes.map{it.parentId}.distinct().size>1)
val activity=instrumentation.startActivitySync(Intent(app,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
lateinit var vm:KaleidoViewModel
instrumentation.runOnMainSync{vm=ViewModelProvider(activity)[KaleidoViewModel::class.java]}
val oldCountdown=vm.autoplaySeconds
instrumentation.uiAutomation.adoptShellPermissionIdentity("android.permission.MEDIA_CONTENT_CONTROL")
try {
instrumentation.runOnMainSync{vm.chooseAutoplaySeconds(0);vm.playShuffled(show,validation=true)}
await{vm.playing!=null&&vm.shuffling}
val played=mutableSetOf<String>()
val manager=app.getSystemService(MediaSessionManager::class.java)
repeat(2) {
val current=vm.playing!!
assertTrue(episodes.any{it.id==current.id})
assertTrue("No repeat before exhausting the show",played.add(current.id))
assertTrue(vm.startFromZero)
await{manager.getActiveSessions(null).any{it.packageName==app.packageName&&it.playbackState?.state==PlaybackState.STATE_PLAYING}}
val controller=manager.getActiveSessions(null).first{it.packageName==app.packageName&&it.playbackState?.state==PlaybackState.STATE_PLAYING}
val duration=controller.metadata!!.getLong(android.media.MediaMetadata.METADATA_KEY_DURATION)
assertTrue(duration>5000)
controller.transportControls.seekTo(duration-4000)
await{vm.playing?.id!=current.id}
assertTrue(vm.shuffling)
}
assertFalse(played.contains(vm.playing!!.id))
} finally {
instrumentation.runOnMainSync{vm.chooseAutoplaySeconds(oldCountdown);vm.stopPlayback()}
instrumentation.uiAutomation.dropShellPermissionIdentity()
}
}
private fun await(check:()->Boolean) {
val deadline=SystemClock.elapsedRealtime()+60000
while(!check()){assertTrue("Playback transition timed out",SystemClock.elapsedRealtime()<deadline);SystemClock.sleep(200)}
}
}

View file

@ -85,6 +85,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var linkingAccount by mutableStateOf(false);private set
var accountToken = session?.accountToken.orEmpty()
var playing by mutableStateOf<Title?>(null); private set
var playbackInstance by mutableIntStateOf(0);private set
var startFromZero by mutableStateOf(false); private set
var focusId by mutableStateOf("")
var update by mutableStateOf<Release?>(null); private set
@ -114,6 +115,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var episodeQueue by mutableStateOf(emptyList<Title>());private set
var relatedShows by mutableStateOf(emptyList<Title>());private set
var transitioningEpisode by mutableStateOf(false);private set
private var shuffleEpisodes by mutableStateOf<ShuffleEpisodes<Title>?>(null)
val shuffling get()=shuffleEpisodes!=null
private var episodeContextJob:Job?=null
private var episodeTransitionJob:Job?=null
private var loadJob: Job? = null
@ -593,12 +596,26 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
sectionCache.clear();characterOffsetCache.clear()
}
fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) {
shuffleEpisodes=null
debugMode=null;debugValidation=false;debugValidationFile=null
val playable=if(item.type=="show" || item.type=="season") {
val episodes=api.allEpisodes(item.id);episodes.firstOrNull {it.offset>0&&!it.watched} ?: episodes.firstOrNull {!it.watched} ?: episodes.firstOrNull() ?: throw PlexException("No playable episodes are available.")
} else item
val d=api.details(playable.id);require(d.media.firstOrNull()?.parts?.isNotEmpty()==true){"No playable media file is available."};startFromZero=fromStart;playing=d
}
/** Starts a show-wide shuffle bag. Watched state and resume offsets do not affect eligibility. */
fun playShuffled(show:Title,validation:Boolean=false):Unit=launchLoad({playShuffled(show,validation)}) {
require(show.type=="show") { "Shuffle is available from a TV show page." }
debugMode=null;debugValidation=BuildConfig.DEBUG&&validation;debugValidationFile=null
val episodes=api.allEpisodes(show.id).filter{it.type=="episode"}.distinctBy{it.id}
val order=ShuffleEpisodes(episodes,Title::id)
val first=order.first ?: throw PlexException("No playable episodes are available.")
val metadata=api.details(first.id)
require(metadata.media.firstOrNull()?.parts?.isNotEmpty()==true){"No playable media file is available."}
shuffleEpisodes=order
startFromZero=true
playing=metadata
}
fun loadEpisodeContext(item:Title) {
if(item.type!="episode")return
if(episodeQueue.any{it.id==item.id})return
@ -612,21 +629,29 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}
}
}
fun followingEpisode(item:Title):Title? {val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null}
fun followingEpisode(item:Title):Title? {
val shuffle=shuffleEpisodes
if(shuffle!=null)return shuffle.following(item.id)
val i=episodeQueue.indexOfFirst{it.id==item.id};return if(i>=0)episodeQueue.getOrNull(i+1)else null
}
fun nextEpisode(item: Title) {
if(episodeTransitionJob?.isActive==true)return
episodeTransitionJob=viewModelScope.launch {
transitioningEpisode=true
try {
val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
val i=episodes.indexOfFirst{it.id==item.id};val next=if(i>=0)episodes.getOrNull(i+1)else null
if(next!=null){val metadata=api.details(next.id);if(playing?.id==item.id){startFromZero=true;playing=metadata}}
val shuffle=shuffleEpisodes
val next=if(shuffle!=null)shuffle.following(item.id) else {
val episodes=if(episodeQueue.any{it.id==item.id})episodeQueue else api.allEpisodes(item.grandparentId).sortedWith(compareBy<Title>{it.parentIndex}.thenBy{it.index})
val i=episodes.indexOfFirst{it.id==item.id};if(i>=0)episodes.getOrNull(i+1)else null
}
if(next!=null){val metadata=api.details(next.id);if(playing?.id==item.id){if(shuffle!=null)shuffle.advance(item.id,next.id);startFromZero=true;playbackInstance++;playing=metadata}}
else if(playing?.id==item.id)stopPlayback()
}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The next episode could not be loaded."){nextEpisode(item)}}finally{transitioningEpisode=false}
}
}
fun stopPlayback(){
val finished=playing
shuffleEpisodes=null
if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
// A season or episode page shows the last episode played, with fresh progress in its row.
detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id}

View file

@ -81,8 +81,9 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
mode==2->"Converting · "+quality.conversion.label
serverConverting->if(serverAudioConverting)"Converted video and audio"else "Converted video"
serverAudioConverting->"Original video · Converted audio"
else->StreamQuality.Original.label
else->qualityOptionLabel(StreamQuality.Original)
}
fun qualityOptionLabel(value:StreamQuality)=value.forMedia(media)
var loading by mutableStateOf(true);private set
var error by mutableStateOf<String?>(null);private set
var position by mutableLongStateOf(if(vm.startFromZero)0 else item.offset);private set
@ -98,12 +99,13 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
val part get()=parts[partIndex.coerceIn(0,parts.lastIndex)]
private val partOffset get()=partStart(parts,partIndex)
var activeSubtitle by mutableStateOf(parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set
var activeAudio by mutableStateOf(parts.first().streams.firstOrNull{it.type==2&&it.selected}?.id.orEmpty());private set
var activeAudio by mutableStateOf((parts.first().streams.firstOrNull{it.type==2&&it.selected} ?: parts.first().streams.firstOrNull{it.type==2})?.id.orEmpty());private set
private var streamSession=UUID.randomUUID().toString()
private var streamStart=0L
private var preparing=false
private var closed=false
private val prepareMutex=Mutex()
private val streamSelectionMutex=Mutex()
private var fallbackPending=false
private var nativeSelectionApplied=false
private val reports=Channel<TimelineReport>(Channel.UNLIMITED)
@ -122,6 +124,15 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
}
init {
audit?.let{player.addAnalyticsListener(it)}
// 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}")
}
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}")
}
})
player.addListener(object: Player.Listener {
override fun onPlaybackStateChanged(state: Int) {
loading=state==Player.STATE_BUFFERING
@ -138,6 +149,9 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
override fun onIsPlayingChanged(value: Boolean){isPlaying=value;if(!preparing&&!closed)report(if(value)"playing"else "paused")}
override fun onTracksChanged(value: Tracks){
tracks=value
audit?.event("selectedTracks",org.json.JSONObject().put("audio",org.json.JSONArray(value.groups.filter{it.type==C.TRACK_TYPE_AUDIO}.flatMap{g->
(0 until g.length).filter{g.isTrackSelected(it)}.map{index->g.getTrackFormat(index).let{f->org.json.JSONObject().put("id",f.id).put("mime",f.sampleMimeType).put("channels",f.channelCount)}}
})))
Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}")
// Some extractors expose only audio for an unsupported video codec (e.g. VC-1).
if(value.groups.isNotEmpty()&&media.videoCodec.isNotBlank()&&
@ -182,6 +196,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
serverConverting=false;serverAudioConverting=false
// Empty track events from stop must not be mistaken for a missing video track.
player.stop()
selector.parameters=selector.buildUponParameters().clearOverrides().build()
try {
if(mode>0)runCatching{api.stopTranscode(streamSession)}
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset
@ -197,7 +212,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==currentStream(activeSubtitle)?.id)C.SELECTION_FLAG_DEFAULT else 0).build()
})
} else {
val p=api.transcodeParams(item,streamSession,mode,partOffsetMs,quality.conversion,mediaIndex,partIndex,local,vm.subtitleSize.plexPercent)
val p=api.transcodeParams(item,streamSession,mode,partOffsetMs,quality.conversion,mediaIndex,partIndex,local,vm.subtitleSize.plexPercent).toMutableMap().apply {
currentStream(activeAudio)?.let{put("audioStreamID",it.id)}
put("subtitleStreamID",currentStream(activeSubtitle)?.id ?: "0")
}
val decision=api.container("/video/:/transcode/universal/decision",p)
val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()}
.flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}
@ -267,15 +285,24 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
}
fun selectServerStream(stream:Stream?,type:Int) {
scope.launch {
try {
streamSelectionMutex.withLock {
try {prepareMutex.withLock selection@{
if(closed)return@selection
val part=part
if(type==C.TRACK_TYPE_TEXT){activeSubtitle=stream?.id ?: "0";api.selectStreams(part,subtitle=activeSubtitle)}else{activeAudio=stream?.id.orEmpty();api.selectStreams(part,audio=activeAudio)}
if(mode>0){prepare(mode,position,player.playWhenReady);return@launch}
val selected=stream?.let{currentStream(it.id)}
val id=selected?.id ?: "0"
if(type==C.TRACK_TYPE_AUDIO&&selected==null)return@selection
if(type==C.TRACK_TYPE_TEXT){api.selectStreams(part,subtitle=id);activeSubtitle=id}
else{api.selectStreams(part,audio=id);activeAudio=id}
val offset=currentPosition();val resume=player.playWhenReady
audit?.event("streamSelected",org.json.JSONObject().put("type",type).put("streamId",id).put("offset",offset).put("resume",resume))
if(mode>0){prepareInternal(mode,offset,resume);return@selection}
if(stream==null){selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return@launch}
val match=nativeTrack(type,stream)
val match=selected?.let{nativeTrack(type,it)}
if(match!=null&&tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second)
else prepare(2,position) // Image subtitles and unsupported embedded tracks are burned by Plex.
}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "Could not change the selected track."}
else prepareInternal(if(type==C.TRACK_TYPE_AUDIO)1 else 2,offset,resume)
}}catch(e:CancellationException){throw e}catch(e:Exception){error="Could not change the selected track. Please try again."}
}
}
}
fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()}
@ -289,6 +316,8 @@ enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:
SD("480p · 3 Mbps",720,480,3000);
/** Target used when Plex must convert; Original falls back to 1080p if direct streaming fails. */
val conversion get()=if(this==Original)FullHD else this
fun forMedia(media:Media):String = if(this!=Original)label else "$label · "+
if(media.bitrate>0)String.format(java.util.Locale.US,"%.1f Mbps",media.bitrate/1000.0)else "Bitrate unavailable"
}
fun clockTime(ms:Long):String {val s=(ms.coerceAtLeast(0)/1000);return if(s>=3600)"%d:%02d:%02d".format(s/3600,s/60%60,s%60)else "%d:%02d".format(s/60,s%60)}
/** Subtitle text size; [plexPercent] sizes subtitles Plex burns into converted video. */

View file

@ -23,19 +23,21 @@ import kotlinx.coroutines.delay
@Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) {
val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f)
// Audio and Subtitles have their own buttons; this menu holds the remaining options.
val entries=listOfNotNull(4 to "Quality · ${vm.activeQuality.label}"+if(vm.localConnection)""else " (remote)",5 to "Speed · ${speedLabel(controller.playbackRate)}",
// Audio is also named here so it is discoverable without recognizing the speaker icon.
val entries=listOfNotNull(10 to "Audio · ${controller.currentStream(controller.activeAudio)?.title ?: "Choose track"}",
4 to "Quality · ${controller.qualityOptionLabel(vm.activeQuality)}"+if(vm.localConnection)""else " (remote)",5 to "Speed · ${speedLabel(controller.playbackRate)}",
if(item.chapters.isNotEmpty())7 to "Chapters" else null,8 to "Subtitle size · ${vm.subtitleSize.label}",9 to "Subtitle style · ${vm.subtitleStyle.label}")
// A submenu returns focus to the option that opened it.
var returnTo by remember{mutableIntStateOf(0)}
val dismiss={if(menu==3)close()else open(3)}
when(menu) {
3->TrackPanel("Playback options",entries.map{it.second},-1,dismiss,focusIndex=entries.indexOfFirst{it.first==returnTo}.coerceAtLeast(0)){index->returnTo=entries[index].first;open(entries[index].first)}
4->TrackPanel(if(vm.localConnection)"Playback quality"else "Remote playback quality",StreamQuality.entries.map{it.label},vm.activeQuality.ordinal,dismiss){controller.changeQuality(StreamQuality.entries[it]);close()}
4->TrackPanel(if(vm.localConnection)"Playback quality"else "Remote playback quality",StreamQuality.entries.map(controller::qualityOptionLabel),vm.activeQuality.ordinal,dismiss){controller.changeQuality(StreamQuality.entries[it]);close()}
5->TrackPanel("Playback speed",speeds.map(::speedLabel),speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()}
7->TrackPanel("Chapters",item.chapters.map{"${it.title} · ${clockTime(it.start)}"},item.chapters.indexOfLast{it.start<=controller.position},dismiss){controller.seekTo(item.chapters[it].start);close()}
8->TrackPanel("Subtitle size",SubtitleSize.entries.map{it.label},vm.subtitleSize.ordinal,dismiss){vm.chooseSubtitleSize(SubtitleSize.entries[it]);close()}
9->TrackPanel("Subtitle style",SubtitleStyle.entries.map{it.label},vm.subtitleStyle.ordinal,dismiss){vm.chooseSubtitleStyle(SubtitleStyle.entries[it]);close()}
10->AudioTrackPanel(controller,dismiss,close)
}
}
@ -44,7 +46,7 @@ internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toStrin
@Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,dismiss:()->Unit,next:()->Unit) {
val upcoming=vm.followingEpisode(item)
// Settings › Playback sets the countdown; 0 turns autoplay off.
val countdown=vm.autoplaySeconds
val countdown=if(vm.shuffling&&vm.autoplaySeconds==0)5 else vm.autoplaySeconds
var autoplay by remember{mutableStateOf(countdown>0)}
var seconds by remember{mutableIntStateOf(countdown)}
LaunchedEffect(autoplay,upcoming?.id) {
@ -53,7 +55,7 @@ internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toStrin
val season=vm.episodeQueue.filter{it.parentId==item.parentId}
LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) {
item {
Text(if(upcoming!=null)"Up next"else "More to watch",color=Accent,fontSize=25.sp,fontWeight=FontWeight.SemiBold)
Text(if(vm.shuffling)"Up next · Shuffle"else if(upcoming!=null)"Up next"else "More to watch",color=Accent,fontSize=25.sp,fontWeight=FontWeight.SemiBold)
Row(Modifier.padding(top=13.dp),horizontalArrangement=Arrangement.spacedBy(20.dp),verticalAlignment=Alignment.CenterVertically) {
if(upcoming!=null)Artwork(vm.api,upcoming.still.ifBlank{upcoming.thumb},Modifier.width(205.dp).aspectRatio(16f/9f).clip(RoundedCornerShape(5.dp)),480,270,animate=false)
Column(Modifier.weight(1f)) {

View file

@ -193,7 +193,8 @@ import kotlinx.coroutines.delay
}}
if(postPlay)PostPlayScreen(vm,item,{postPlay=false;controls=true},{vm.nextEpisode(item)})
controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})}
if(trackMenu in 1..2) {
if(trackMenu==1)AudioTrackPanel(controller,::closeTracks,::closeTracks)
if(trackMenu==2) {
val type=if(trackMenu==1)C.TRACK_TYPE_AUDIO else C.TRACK_TYPE_TEXT
val streams=controller.part.streams.filter{it.type==(if(trackMenu==1)2 else 3)}
val options=(if(trackMenu==2)listOf("Off")else emptyList())+streams.map{it.title}
@ -209,6 +210,17 @@ import kotlinx.coroutines.delay
}
}
/** The same track selector is reachable from the speaker and from Playback options. */
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable internal fun AudioTrackPanel(controller:PlaybackController,dismiss:()->Unit,close:()->Unit) {
val streams=controller.part.streams.filter{it.type==2}
val active=controller.currentStream(controller.activeAudio)
TrackPanel("Audio tracks",streams.map{it.title},streams.indexOfFirst{it.id==active?.id},dismiss){index->
streams.getOrNull(index)?.let{controller.selectServerStream(it,C.TRACK_TYPE_AUDIO)}
close()
}
}
/** A short, non-focusable cue leaves the picture and remote focus undisturbed. */
@Composable private fun QuickSkipFeedback(seconds:Int,pulse:Int,allowed:Boolean,modifier:Modifier) {
// Keep the final label while the cue fades out.

View file

@ -120,7 +120,7 @@ import java.io.File
if(vm.busy) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopCenter),color=Accent,trackColor=Color.Transparent)
if(vm.error!=null) ErrorDialog(vm.error!!,{vm.dismissError()},{vm.retry()})
vm.contextItem?.let{item->if(vm.playing==null)TitleActions(vm,item)}
vm.playing?.let {item-> androidx.compose.runtime.key(item.id) {PlaybackScreen(vm,item)} }
vm.playing?.let {item-> androidx.compose.runtime.key(item.id,vm.playbackInstance) {PlaybackScreen(vm,item)} }
if(startup)StartupSplash({splashExit.value},{!vm.busy}){brandReady=true}
}
}

View file

@ -0,0 +1,49 @@
package tv.kaleido.app
import kotlin.random.Random
/** A repeating shuffle bag that never repeats the previous episode at a cycle boundary. */
internal class ShuffleEpisodes<T>(
episodes: List<T>,
private val id: (T) -> String,
private val random: Random = Random.Default,
) {
private val episodes = episodes.distinctBy(id)
private var order = this.episodes.shuffled(random)
private var currentIndex = 0
private var nextCycle: List<T>? = null
val first: T? get() = order.firstOrNull()
/** Returns the item after [currentId], preparing the next bag when needed. */
fun following(currentId: String): T? {
if (order.getOrNull(currentIndex)?.let(id) != currentId) return null
if (currentIndex < order.lastIndex) return order[currentIndex + 1]
return nextCycle?.firstOrNull() ?: makeNextCycle(order[currentIndex]).also { nextCycle = it }.firstOrNull()
}
/** Advances only when [nextId] is the next item returned by [following]. */
fun advance(currentId: String, nextId: String): Boolean {
if (following(currentId)?.let(id) != nextId) return false
if (currentIndex == order.lastIndex) {
order = nextCycle ?: makeNextCycle(order[currentIndex])
nextCycle = null
currentIndex = 0
} else {
currentIndex++
}
return order.getOrNull(currentIndex)?.let(id) == nextId
}
private fun makeNextCycle(previous: T): List<T> {
val shuffled = episodes.shuffled(random)
if (shuffled.size < 2 || id(shuffled.first()) != id(previous)) return shuffled
val firstDifferent = shuffled.indexOfFirst { id(it) != id(previous) }
if (firstDifferent < 1) return shuffled
return shuffled.toMutableList().also { bag ->
val first = bag[0]
bag[0] = bag[firstDifferent]
bag[firstDifferent] = first
}
}
}

View file

@ -160,6 +160,7 @@ private object DetailsScroll:BringIntoViewSpec {
if(item.type!="collection")Row(Modifier.horizontalScroll(rememberScrollState()).padding(vertical=3.dp),horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
ActionButton(if(item.offset>0)"Resume from ${clockTime(item.offset)}"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,modifier=actionNavigation.focusRequester(actionFocus),primary=true,initialFocus=initialFocus){played(vm,page);vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay,modifier=actionNavigation){played(vm,page);vm.play(item,true)}
if(page.type=="show"&&item.type=="show")ActionButton("Shuffle episodes",Icons.Outlined.Shuffle,modifier=actionNavigation){played(vm,page);vm.playShuffled(item)}
if(item.type in listOf("movie","show","season","episode")) {
val watched=item.isWatched(vm.watchedPercent)
ActionButton(if(vm.markingId==item.id)"Updating…"else if(watched)"Mark unwatched"else "Mark watched",if(watched)Icons.Outlined.CheckCircle else Icons.Outlined.Check,modifier=actionNavigation){vm.mark(item)}

View file

@ -51,6 +51,13 @@ class PlaybackModelTest {
@Test fun speedLabels() {
assertEquals("Normal",speedLabel(1f));assertEquals("1.25×",speedLabel(1.25f));assertEquals("2×",speedLabel(2f))
}
@Test fun originalQualityUsesTheSelectedVersionsBitrate() {
val media=Media("1","mkv","hevc","eac3","4k",3840,2160,19094,emptyList())
assertEquals("Original quality · 19.1 Mbps",StreamQuality.Original.forMedia(media))
assertEquals("Original quality · 0.8 Mbps",StreamQuality.Original.forMedia(media.copy(bitrate=768)))
assertEquals("Original quality · Bitrate unavailable",StreamQuality.Original.forMedia(media.copy(bitrate=0)))
assertEquals(StreamQuality.FullHD.label,StreamQuality.FullHD.forMedia(media))
}
@Test fun seasonPagesShowTheNextEpisode() {
val watched=title("episode","1").copy(watched=true)
val unwatched=title("episode","2");val started=title("episode","3").copy(duration=60_000,offset=10_000)

View file

@ -0,0 +1,63 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.random.Random
class ShuffleEpisodesTest {
@Test fun eachBagContainsEveryEpisodeOnceAndBoundaryDoesNotRepeat() {
val episodes=listOf("e1","e2","e3","e4","e5")
val shuffle=ShuffleEpisodes(episodes,{it},Random(42))
var current=shuffle.first
assertNotNull(current)
val firstBag=mutableListOf(current!!)
repeat(episodes.size-1) {
val next=shuffle.following(current!!)
assertNotNull(next)
assertTrue(shuffle.advance(current!!,next!!))
current=next
firstBag+=current!!
}
assertEquals(episodes.size,firstBag.distinct().size)
assertEquals(episodes.toSet(),firstBag.toSet())
val previous=current!!
val next=shuffle.following(previous)
assertNotNull(next)
assertNotEquals(previous,next)
assertTrue(shuffle.advance(previous,next!!))
current=next
val secondBag=mutableListOf(current!!)
repeat(episodes.size-1) {
val upcoming=shuffle.following(current!!)
assertNotNull(upcoming)
assertTrue(shuffle.advance(current!!,upcoming!!))
current=upcoming
secondBag+=current!!
}
assertEquals(episodes.size,secondBag.distinct().size)
assertEquals(episodes.toSet(),secondBag.toSet())
}
@Test fun onlyEpisodeRepeatsWhenItIsTheWholeShow() {
val shuffle=ShuffleEpisodes(listOf("only"),{it},Random(42))
assertEquals("only",shuffle.first)
assertEquals("only",shuffle.following("only"))
assertTrue(shuffle.advance("only","only"))
assertEquals("only",shuffle.following("only"))
}
@Test fun rejectsUnknownCurrentAndUnexpectedAdvance() {
val shuffle=ShuffleEpisodes(listOf("e1","e2","e3"),{it},Random(42))
assertNull(shuffle.following("missing"))
val current=shuffle.first!!
assertEquals(false,shuffle.advance(current,"missing"))
assertNotNull(shuffle.following(current))
}
}

Binary file not shown.

View file

@ -1 +1 @@
6644676bc7c84caf8b3a917bb2f48c088ae6ad5871c3681308713eece3442d6a Kaleido.apk
06d942779eae498db63c923746a38fd64640cbd3221953712e649fc86f9f2633 Kaleido.apk

View file

@ -1,7 +1,7 @@
{
"version": "0.4.1",
"versionCode": 18,
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.4.1/distribution/Kaleido.apk",
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.4.1/distribution/Kaleido.apk.sha256",
"notes": "- Make Categories about the genre: large centered labels over dim artwork with subdued natural color, a compact four-column grid and a restrained focus outline. Remove title captions and FILM/SERIES badges from category cards.\n- Give every movie and TV category a distinct artwork source. Match overlapping genres together, preserve scarce choices, and fetch more candidates when needed instead of reusing a background."
"version": "0.5.0",
"versionCode": 19,
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.5.0/distribution/Kaleido.apk",
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.5.0/distribution/Kaleido.apk.sha256",
"notes": "- Show the selected version's source bitrate beside Original quality in the playback quality menu.\n- Add a named Audio entry to Playback options alongside the speaker button. Preserve position, pause state and selected tracks when switching audio or rebuilding a Plex stream.\n- Add Shuffle on TV show pages. Play episodes from all seasons in repeating shuffled cycles, starting each episode from the beginning and continuing even when ordinary autoplay is off. Seasons keep their usual Play action.\n- Record sparse audio underrun and sink-error diagnostics for investigating intermittent dropouts. A short Infinity War check did not reproduce the reported stutter; a fix for that symptom is not yet confirmed."
}

View file

@ -4,6 +4,14 @@ For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback find
Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`.
## 2026-10-28 playback quality, audio selection and show shuffle (0.5.0)
- Original quality now uses the selected media version's source bitrate; Infinity War shows `19.1 Mbps`. No source bitrate is invented when Plex omits it. The quality menu and audio-track popup were checked in actual device screenshots.
- `scripts/verify_playback_changes.py audio` passed real Infinity War track switches in Original mode and Plex conversion. Selected stereo audio was actually delivered as AC3 two-channel audio and AAC two-channel audio respectively; the paused state and timeline position survived both switches. The script restored the prior Plex audio selection and local preferences. Validation playback suppresses timeline/scrobble writes.
- Twelve focused unit checks passed (`PlaybackModelTest`, `ShuffleEpisodesTest`), along with lint and signed debug/release builds. The opt-in `PlaybackChangesIntegrationTest` passed two natural episode endings through the real player/Compose post-play path with ordinary autoplay set to Off; shuffle continued to different episodes. The test restored the original autoplay preference. Shuffle bags cover every eligible episode from all seasons before reshuffling and avoid repeating the previous episode at a bag boundary; a one-episode show explicitly recreates playback for its next cycle.
- The reported intermittent Infinity War audio stutter remains unresolved. A 45-second steady baseline near one hour played its original Dolby Vision video and EAC3 eight-channel audio without player errors or audio underruns; the user reports that rewinding does not repeat the symptom and that it also happens with boost disabled. No codec, output routing or buffer change was made without a reproduction. Release logcat now records sparse `KaleidoAudio` underrun/sink-error events with position and audio path, and the debug validation harness can fail on audio underruns with `--fail-on-audio-underrun`.
- The signed release passed the focused show/season UI check: Shuffle is remote-focusable on Silo's show page and absent on its season page. Reinstalled the release, installed its baseline profile and compiled only Kaleido with `speed-profile`, then returned the onn to Home. The user authorized publication after these local checks.
## 2026-10-28 genre-led category revision (0.4.1)
- The user requested a genre-led page instead of title-led cards: four columns, centered 22 sp genre labels, no title captions or FILM/SERIES badges, and dim artwork in the background. Natural artwork color is retained at 65% saturation after a monochrome preview was rejected. There are no added genre color tints.

View file

@ -34,6 +34,7 @@ def main():
parser.add_argument('--expect-width',type=int)
parser.add_argument('--expect-channels',type=int)
parser.add_argument('--expect-audio-encoding',type=int)
parser.add_argument('--fail-on-audio-underrun',action='store_true')
args=parser.parse_args()
folder=OUT/'playback-validation'/('onn' if DEVICE=='192.168.50.195:5555' else 'tcl')/args.label
folder.mkdir(parents=True,exist_ok=True)
@ -111,11 +112,13 @@ def main():
'errors':[r['code'] for r in records if r['event']=='error'],'errorDetails':[r for r in records if r['event'] in ('error','prepareFailure')],'finalSample':last,'seek':seek_result,
'expectsVideo':expects_video,'videoRendered':not expects_video or any(r.get('videoCounters',{}).get('rendered',0)>5 for r in samples),
'closed':any(r['event']=='closed' for r in records),'before':watched(before),'after':watched(after),
'audioUnderruns':[r for r in records if r['event']=='audioUnderrun'],
'transport':'private-local-fixture' if args.fixture else 'Plex','progressUnchanged':None if args.fixture else watched(before)==watched(after)}
(folder/'result.json').write_text(json.dumps(result,indent=2))
print(json.dumps({k:result[k] for k in ('label','readySeconds','firstFrame','audioAdvancing','videoDecoders','errors','progressUnchanged')}),flush=True)
print('Output:',last.get('video'),last.get('audio'),'mode:',last.get('mode'),'seek:',seek_result,flush=True)
if ready is None:raise SystemExit('Playback did not become ready; see private evidence')
if args.fail_on_audio_underrun and result['audioUnderruns']:raise SystemExit('Audio underrun detected; see private evidence')
if not result['closed']:raise SystemExit('Player did not close cleanly')
if result['progressUnchanged'] is False:raise SystemExit('Unexpected progress change; see before/after evidence')
if args.seek and not seek_result['correct']:raise SystemExit('Seek did not reach the expected absolute position')

View file

@ -0,0 +1,78 @@
"""Focused 0.5 checks: bitrate and actual audio switching, plus show-only Shuffle placement."""
import argparse,json,time,urllib.parse,urllib.request
from device import adb,OUT,screenshot
from inspect_server import get,base,token
from validate_playback import audit
from verify_ui import key,focused,text,wait,labels,focus,snapshot,launch,passed
def wait_for(check,description,timeout=50):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
if check():return
time.sleep(.25)
raise AssertionError(description)
def audio():
item=get('/library/metadata/870')['Metadata'][0]
part=item['Media'][0]['Part'][0]
streams=[s for s in part['Stream'] if s['streamType']==2]
original=next((s for s in streams if s.get('selected')),streams[0])
stereo=next(s for s in streams if s.get('channels')==2)
preferences=adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')
def restore_track():
request=urllib.request.Request(base+'/library/parts/'+str(part['id'])+'?'+urllib.parse.urlencode({'audioStreamID':original['id'],'allParts':1}),method='PUT',headers={'X-Plex-Token':token})
with urllib.request.urlopen(request,timeout=20) as r:assert r.status==200
try:
for mode in (0,2):
restore_track()
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','rm','-f','files/playback-validation.jsonl')
print('Checking audio mode',mode,flush=True)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','870','--el','testOffset','90000','--ei','testMode',str(mode),'--ez','testValidation','true')
wait_for(lambda:any(r['event']=='sample' and r.get('playing') and r.get('position',0)>90000 for r in audit()[1]),'Playback ready')
key(127);focused('Play')
wait_for(lambda:(lambda s:bool(s) and not s[-1]['playing'])([r for r in audit()[1] if r['event']=='sample']),'Playback paused')
key(22,4);focused('Playback options');key(23);focused('Audio ·')
if mode==0:
key(20);focused('Quality ·');key(23);focused('Original quality · 19.1 Mbps')
screenshot('050-original-bitrate');key(4);focused('Quality ·');key(19);focused('Audio ·')
key(23);text('Audio tracks')
screenshot('050-audio-tracks-'+str(mode))
# The selected Plex default receives initial focus.
delta=streams.index(stereo)-streams.index(original)
key(20 if delta>=0 else 19,abs(delta));focused(stereo['displayTitle'])
before=[r for r in audit()[1] if r['event']=='sample'][-1]['position']
key(23);focused('Playback options')
wait_for(lambda:any(r['event']=='selectedTracks' and any(a.get('channels')==2 for a in r.get('audio',[])) for r in audit()[1]),'Stereo track must actually be selected')
wait_for(lambda:(lambda s:bool(s) and s[-1]['state']==3)([r for r in audit()[1] if r['event']=='sample']),'Track switch ready')
samples=[r for r in audit()[1] if r['event']=='sample']
assert not samples[-1]['playing'],'Paused state must survive track switch'
assert abs(samples[-1]['position']-before)<2500,'Track switch must preserve position'
key(126)
wait_for(lambda:(lambda s:bool(s) and s[-1].get('audio',{}).get('channels')==2 and s[-1].get('playing'))([r for r in audit()[1] if r['event']=='sample']),'Selected stereo audio must play')
raw,records=audit();(OUT/('050-track-switch-'+str(mode)+'.jsonl')).write_bytes(raw)
assert not any(r['event']=='error' for r in records)
passed('Actual stereo selection, position and pause preservation in '+('Original' if mode==0 else 'Plex conversion'))
finally:
adb('shell','am','force-stop','tv.kaleido.app');restore_track()
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=preferences)
def show():
launch();key(22,3);focused('Search');key(23)
focused('Movies, shows, episodes, people')
adb('shell','input','text','silo');text('TV shows');key(66);focused('Silo');key(23);text('Seasons')
root=text('Shuffle episodes');screenshot('050-show-shuffle')
# Focus starts on the season rail. Reach its action row and explicitly focus Shuffle.
if 'Season' in focus(root):key(19)
wait(lambda r:any(x in focus(r) for x in ('Play','Resume','Watch next','Shuffle')),'Show actions')
if 'Shuffle' not in focus(snapshot()):key(22)
focused('Shuffle episodes')
key(20);focused('Season 1');key(23)
wait(lambda r:'Episodes' in labels(r) or any(x.startswith(('Play','Resume')) for x in labels(r)),'Season page')
assert not any('Shuffle' in s for s in labels(snapshot())),'Shuffle must not appear on seasons'
screenshot('050-season-without-shuffle')
passed('Show Shuffle is remote-focusable and absent from season pages')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('check',choices=['audio','show']);args=parser.parse_args()
(audio if args.check=='audio' else show)()

View file

@ -92,14 +92,14 @@ def player():
passed('Compact player controls over actual video')
key(19);focused('Playback timeline');key(22);capture('timeline');key(20);focused('Play')
passed('D-pad Up focuses timeline, Right seeks, Down returns to play')
key(22,2);focused('Audio tracks');key(23);text('Audio');capture('audio')
key(22,2);focused('Audio tracks');key(23);text('Audio tracks');capture('audio')
key(4);focused('Audio tracks');key(22);focused('Subtitles');key(23);text('Off');capture('subtitles')
passed('Audio and subtitle panels open, close, and restore focus')
key(4);focused('Subtitles');key(22);focused('Playback options');key(23);text('Playback options')
key(20);focused('Speed');key(23);text('Playback speed');focused('Normal');key(20);focused('1.25×');key(23)
key(20,2);focused('Speed');key(23);text('Playback speed');focused('Normal');key(20);focused('1.25×');key(23)
focused('Playback options');key(23);text('Speed · 1.25×');key(4);focused('Playback options')
key(23);text('Playback options');key(23);text('Playback quality');focused('Original quality');key(20);focused('4K');key(19);focused('Original quality');key(23)
focused('Playback options');time.sleep(5);key(23);text('Quality · Original quality');key(4);focused('Playback options')
key(23);text('Playback options');key(20);key(23);text('Playback quality');focused('Original quality');key(20);focused('4K');key(19);focused('Original quality');key(23)
focused('Playback options');time.sleep(5);key(23);wait(lambda r:any(s.startswith('Quality · Original quality') for s in labels(r)),'Original bitrate quality label');key(4);focused('Playback options')
passed('Player gear changes speed and switches a conversion to Original quality while retaining focus')
key(4)
wait(lambda r:focus(r)=='' and '2 Fast 2 Furious' not in labels(r),'Controls hidden by Back')

View file

@ -1,2 +1,2 @@
versionName=0.4.1
versionCode=18
versionName=0.5.0
versionCode=19