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

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