Add Vortex and fairer repeats, with a longer Terra list (0.41.0, Phase C in testing)
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m37s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m22s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-02 06:34:20 +00:00
co-authored by Claude Opus 5.5
parent a43d7ec70a
commit e83ae88d29
9 changed files with 88 additions and 23 deletions
@@ -3,15 +3,26 @@ package tv.orbit.classic
/** What makes a channel itself. The engine below knows nothing about any particular channel. */
internal data class ChannelProgramming(val number: Int, val name: String, val searches: List<String>, val seriesCount: Int = 3,
/** Set for a film channel: how long before a film may air again, as long as the pool allows it. */
val filmRestMs: Long? = null)
val filmRestMs: Long? = null,
/** A show that finishes waits until every show has finished, so nothing repeats while others have new episodes. */
val finishTogether: Boolean = false,
/** Only the exact title counts, for channels whose short names could match something unrelated. */
val exactTitles: Boolean = false) {
/** Changes when the list does, so the episode cache is read again. What's already committed stays. */
val signature get() = "${searches.joinToString("|")}#$seriesCount"
}
internal val SmartChannels = listOf(
ChannelProgramming(102, "After Dark", listOf("The Thing", "The Evil Dead", "Re-Animator", "Hellraiser", "Videodrome", "An American Werewolf in London",
"Halloween", "Day of the Dead", "They Live", "Escape from New York", "The Fog", "Near Dark", "The Lost Boys", "Fright Night", "Society", "Tremors",
"Basket Case", "Phantasm", "Repo Man", "Donnie Darko", "The Wicker Man", "Suspiria", "Eraserhead", "Blue Velvet", "From Dusk Till Dawn", "Scream",
"Poltergeist", "The Howling", "Creepshow", "Prince of Darkness"), seriesCount = 40, filmRestMs = 48 * 60 * 60_000L),
ChannelProgramming(140, "Terra", listOf("Blue Planet", "Planet Earth", "Frozen Planet", "Life on Earth", "Our Planet", "Dynasties",
"Seven Worlds One Planet", "A Perfect Planet", "Hostile Planet", "The Living Planet"), seriesCount = 8),
ChannelProgramming(103, "Vortex", listOf("Dragon Ball Z", "Batman Beyond", "Superman: The Animated Series", "Naruto", "Gundam Wing", "Yu Yu Hakusho", "Samurai Jack"),
seriesCount = 6, finishTogether = true),
ChannelProgramming(140, "Terra", listOf("The Blue Planet", "Blue Planet II", "Planet Earth", "Planet Earth II", "Planet Earth III", "Frozen Planet", "Frozen Planet II",
"Life on Earth", "The Living Planet", "The Trials of Life", "Our Planet", "Our Planet II", "Dynasties", "Dynasties II", "Seven Worlds, One Planet", "A Perfect Planet",
"Hostile Planet", "Africa", "Wild China", "South Pacific", "Great Barrier Reef", "The Hunt", "The Life of Mammals", "The Life of Birds", "Nature's Great Events", "Green Planet", "Prehistoric Planet"),
seriesCount = 20, finishTogether = true, exactTitles = true),
ChannelProgramming(152, "Paradox", ChannelPresets.first { it.number == 152 }.searches))
internal data class EpisodeMark(val season: Int, val episode: Int) : Comparable<EpisodeMark> {
@@ -42,6 +53,12 @@ internal const val SCHEDULE_KEEP_PAST_MS = 24 * 60 * 60_000L
internal fun nextEpisode(series: PoolSeries, last: EpisodeMark?): PoolEpisode =
last?.let { mark -> series.episodes.firstOrNull { it.mark > mark } } ?: series.episodes.first()
/** The next show after [last] in the rota that [eligible] allows. */
internal fun nextInTurn(pool: List<PoolSeries>, last: String?, eligible: (PoolSeries) -> Boolean): PoolSeries {
val after = pool.indexOfFirst { it.id == last } + 1
return (0 until pool.size).map { pool[(after + it) % pool.size] }.first(eligible)
}
/**
* A film past its rest, chosen by a generator seeded from the start time so a plan can be explained and reproduced.
* If the pool is too small for the rest period, the film that has waited longest.
@@ -71,7 +88,7 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
}
/** Shows take turns, one episode each, back to back from [fromMs] until [untilMs] is covered. */
internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, filmRestMs: Long? = null): ChannelPlan {
internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, filmRestMs: Long? = null, finishTogether: Boolean = false): ChannelPlan {
require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() })
if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs)
val marks = cursor.marks.toMutableMap()
@@ -79,7 +96,8 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
var last = cursor.lastSeriesId
var start = fromMs
while (start < untilMs) {
val series = pool[(pool.indexOfFirst { it.id == last } + 1) % pool.size]
if (finishTogether && pool.all { marks[it.id] == it.episodes.last().mark }) marks.clear()
val series = nextInTurn(pool, last) { !finishTogether || marks[it.id] != it.episodes.last().mark }
val episode = nextEpisode(series, marks[series.id])
val media = ScheduledMedia(scheduledItem(series.title, episode), episode.sourceId, episode.durationMs)
entries += ScheduleEntry(series.id, episode.mark, media, start)
@@ -110,12 +128,12 @@ internal fun airedCursor(base: ScheduleCursor, entries: List<ScheduleEntry>, now
* Only ever appends. Programmes already committed stay as they are, apart from dropping old ones.
* With no usable plan it starts from now at the aired position.
*/
internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List<PoolSeries>?, nowMs: Long, filmRestMs: Long? = null): ChannelPlan? {
internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List<PoolSeries>?, nowMs: Long, filmRestMs: Long? = null, finishTogether: Boolean = false): ChannelPlan? {
val kept = existing?.let { plan -> plan.copy(entries = plan.entries.dropWhile { it.endMs < nowMs - SCHEDULE_KEEP_PAST_MS }) }
if (kept != null && kept.endMs >= nowMs + SCHEDULE_TOP_UP_MS) return kept
if (pool.isNullOrEmpty()) return kept
val from = if (kept != null && kept.endMs > nowMs) kept.endMs else nowMs
val added = extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs)
val added = extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether)
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
}
@@ -37,14 +37,14 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
var pool = cached
var requests = 0
var fetchMs = 0L
if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS) {
if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS || cached.signature != programming.signature) {
val started = android.os.SystemClock.elapsedRealtime()
try {
val read = session.readChannelPool(programming, loop, checkActive)
requests = read.requests
fetchMs = android.os.SystemClock.elapsedRealtime() - started
if (read.series.isNotEmpty()) {
pool = ScheduleStore.SavedPool(read.series, now)
pool = ScheduleStore.SavedPool(read.series, now, programming.signature)
store.savePool(userId, number, pool)
}
} catch (failure: EmbyCheckException) { if (cached == null) throw failure }
@@ -53,7 +53,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
val existing = store.loadPlan(userId, number)
val progress = store.loadProgress(userId, number)
val base = progress?.aired ?: ScheduleCursor()
val plan = topUpPlan(existing, base, pool?.series, now, programming.filmRestMs) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
val plan = topUpPlan(existing, base, pool?.series, now, programming.filmRestMs, programming.finishTogether) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
if (plan !== existing) store.savePlan(userId, number, plan)
store.saveProgress(userId, number, ScheduleStore.SavedProgress(progress?.enabled ?: true, airedCursor(base, plan.entries, now)))
session.rememberScheduledItems(plan.entries.map { it.media.item })
@@ -41,7 +41,7 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
connection.connectTimeout = 10_000
connection.readTimeout = request.readTimeoutMs ?: if (request.path == "/Sessions/Logout") 5_000 else 15_000
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.40.0\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.41.0\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -116,7 +116,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
seriesMatches = saved.matches.takeIf { it.isNotEmpty() }; approvedSeries = saved.approved
episodeSamples = saved.episodes; channel = saved.orbitOne; toonamiChannel = saved.toonami; extraChannels = saved.extra
darkMovies = saved.darkMovies; approvedDark = saved.approvedDark; afterDarkChannel = saved.afterDark
val available = availableSampleChannels(channel, afterDarkChannel?.let(::onAir), toonamiChannel, *extraChannels.map(::onAir).toTypedArray())
val available = availableSampleChannels(channel, afterDarkChannel?.let(::onAir), toonamiChannel?.let(::onAir), *extraChannels.map(::onAir).toTypedArray())
selectedNumber = available.firstOrNull { it.number == saved.selectedNumber }?.number ?: available.firstOrNull()?.number ?: 101
onChannelAvailable(available.isNotEmpty())
}
@@ -174,7 +174,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
}
// Read before the channels appear, so the guide never shows the loop for a moment first.
scheduledChannels = withContext(Dispatchers.IO) {
(saved.extra + listOfNotNull(saved.afterDark)).mapNotNull { loop -> scheduler.load(saved.identity.userId, loop)?.also { resumed.rememberScheduledItems(it.plan.entries.map { entry -> entry.media.item }) } }.associateBy { it.number }
(saved.extra + listOfNotNull(saved.afterDark, saved.toonami)).mapNotNull { loop -> scheduler.load(saved.identity.userId, loop)?.also { resumed.rememberScheduledItems(it.plan.entries.map { entry -> entry.media.item }) } }.associateBy { it.number }
}
session = resumed; sample = resumed.sample; applyChoices(saved)
saveTicket = savedStore.ticket()
@@ -213,9 +213,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
}
}
LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
fun smartLoop(programming: ChannelProgramming) = (extraChannels + listOfNotNull(afterDarkChannel)).firstOrNull { it.number == programming.number }
fun smartLoop(programming: ChannelProgramming) = (extraChannels + listOfNotNull(afterDarkChannel, toonamiChannel)).firstOrNull { it.number == programming.number }
// Keeps smart channels topped up in the background. A failure changes nothing on air.
LaunchedEffect(session, extraChannels, afterDarkChannel) {
LaunchedEffect(session, extraChannels, afterDarkChannel, toonamiChannel) {
val active = session ?: return@LaunchedEffect
while (true) {
for (programming in SmartChannels) {
@@ -253,7 +253,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
val ready = !busy && !restoring && now >= nextAttemptAt && username.isNotBlank() && password.text.isNotEmpty()
playback?.let { plan -> session?.let { active -> EmbyPlaybackDialog(active, plan, onClose = { playback = null }) } }
val liveSession = session
val availableChannels = availableSampleChannels(channel, afterDarkChannel?.let(::onAir), toonamiChannel, *extraChannels.map(::onAir).toTypedArray())
val availableChannels = availableSampleChannels(channel, afterDarkChannel?.let(::onAir), toonamiChannel?.let(::onAir), *extraChannels.map(::onAir).toTypedArray())
val liveChannel = availableChannels.firstOrNull { it.number == selectedNumber }
if ((mainGuide || mainHome) && liveSession != null && liveChannel != null) {
if (watchingChannel) ScheduledChannelPlayer(liveSession, liveChannel, channelClockOffset,
@@ -205,7 +205,8 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
if (pool.size == programming.seriesCount) break
checkActive()
requests++
val match = bestSeriesMatch(search, searchSeries(transport, userId, ::currentToken, search).candidates) ?: continue
val candidates = searchSeries(transport, userId, ::currentToken, search).candidates
val match = bestSeriesMatch(search, if (programming.exactTitles) candidates.filter { seriesKey(it.title) == seriesKey(search) } else candidates) ?: continue
if (pool.any { it.id == match.id }) continue
val whole = readWholeSeries(transport, userId, ::currentToken, match, checkActive, onRequest = { requests++ })
if (whole.episodes.isNotEmpty()) pool += whole
@@ -12,7 +12,7 @@ import java.io.FileOutputStream
internal class ScheduleStore(private val directory: File) {
companion object { const val SCHEMA = 1 }
internal class SavedProgress(val enabled: Boolean, val aired: ScheduleCursor)
internal class SavedPool(val series: List<PoolSeries>, val fetchedAtMs: Long)
internal class SavedPool(val series: List<PoolSeries>, val fetchedAtMs: Long, val signature: String = "")
private fun file(kind: String, number: Int) = File(directory, "$kind-$number.json")
@@ -85,7 +85,7 @@ internal class ScheduleStore(private val directory: File) {
show.episodes.forEach { e -> episodes.put(JSONArray().put(e.id).put(e.sourceId).put(e.mark.season).put(e.mark.episode).put(e.title).put(e.durationMs)) }
series.put(JSONObject().put("id", show.id).put("title", show.title).put("episodes", episodes))
}
write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("series", series))
write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("signature", pool.signature).put("series", series))
}
fun loadPool(userId: String, number: Int): SavedPool? = read(file("episodes", number), userId, number) { root ->
val rows = root.getJSONArray("series")
@@ -96,7 +96,7 @@ internal class ScheduleStore(private val directory: File) {
val e = episodes.getJSONArray(row)
PoolEpisode(validId(e.getString(0)), validId(e.getString(1)), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), validDuration(e.getLong(5)))
}.also { require(it.isNotEmpty()) })
}, root.getLong("fetched"))
}, root.getLong("fetched"), root.optString("signature"))
}
/** Bytes held for a channel, for the measurements. */
@@ -33,7 +33,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.instanceFollowRedirects = false
next.connectTimeout = 10_000
next.readTimeout = 20_000
next.setRequestProperty("User-Agent", "OrbitTV/0.40.0")
next.setRequestProperty("User-Agent", "OrbitTV/0.41.0")
next.setRequestProperty("Accept-Encoding", "identity")
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {