0.97.0: editorially weighted rotation on Orbit Three, Family Guy out of its evening
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m9s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m31s

Tiers core 3, supporting 2, surprises 1, behind a per-channel switch set only for
Orbit Three. Tallies and run starts saved in the cursor. Shuffled and in-order
episode choice unchanged. Four-week replay on the real pool and fingerprints of
every channel against 0.96.0 in docs/replays.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-03 23:59:36 +00:00
co-authored by Claude Opus 5.5
parent 3b045b65bd
commit 5b7b180a10
13 changed files with 674 additions and 13 deletions
@@ -48,12 +48,19 @@ internal val Orbit2Mixed get() = Orbit2Shows.toSet()
private val ThreeScottish = listOf("Still Game", "Limmy's Show!", "Burnistoun", "Chewin' the Fat", "Rab C. Nesbitt", "Gary: Tank Commander", "Scot Squad")
private val ThreeDaytime = listOf("Two Pints of Lager and a Packet of Crisps", "The Inbetweeners", "Bad Education", "Uncle", "Him & Her",
"Coupling", "Cuckoo", "Lunch Monkeys", "Man Like Mobeen", "People Just Do Nothing", "Black Books") + ThreeScottish
// Family Guy left Three's evening on 4 November 2026: Riot is its home. A future crossover would be approved on its own.
private val ThreeEvening = listOf("Gavin & Stacey", "The Mighty Boosh", "Spaced", "Fresh Meat", "Phoenix Nights",
"Being Human", "Green Wing", "This Country", "Extras", "The Office (UK)", "Toast of London", "Peep Show", "The IT Crowd", "Family Guy")
"Being Human", "Green Wing", "This Country", "Extras", "The Office (UK)", "Toast of London", "Peep Show", "The IT Crowd")
private val ThreeLate = listOf("Little Britain", "The League of Gentlemen", "Nighty Night", "Snuff Box", "Monkey Dust", "Psychoville", "Inside No. 9",
"Garth Marenghi's Darkplace", "Brass Eye", "The Day Today", "Nathan Barley", "Bo' Selecta!", "Stressed Eric")
private val ThreeOvernight = listOf("Two Pints of Lager and a Packet of Crisps", "The Inbetweeners", "Gavin & Stacey", "The Mighty Boosh", "Still Game", "Limmy's Show!", "Burnistoun", "Black Books")
internal val ThreeShows get() = (ThreeDaytime + ThreeEvening + ThreeLate).distinct()
/** Orbit Three's editorial tiers, from docs/channels/orbit-three.md: core 3, supporting 2 (everything else listed), surprises 1. */
internal val ThreeTiers: Map<String, Double> get() =
listOf("Still Game", "Limmy's Show!", "Burnistoun", "Chewin' the Fat", "Rab C. Nesbitt", "Gavin & Stacey", "The Mighty Boosh", "Little Britain",
"The Inbetweeners", "Two Pints of Lager and a Packet of Crisps", "Spaced", "Phoenix Nights").associate { seriesKey(it) to TIER_CORE } +
listOf("The League of Gentlemen", "Nighty Night", "Snuff Box", "Monkey Dust", "Psychoville", "Inside No. 9", "Garth Marenghi's Darkplace",
"Brass Eye", "The Day Today", "Nathan Barley", "Bo' Selecta!", "Stressed Eric").associate { seriesKey(it) to TIER_SURPRISE }
internal val ThreeDayParts get() = listOf(
DayPart(21, 0, ThreeScottish, days = setOf(DayOfWeek.FRIDAY, DayOfWeek.SATURDAY), key = "three.scottish"),
DayPart(6, 18, ThreeDaytime), DayPart(18, 22, ThreeEvening), DayPart(22, 2, ThreeLate), DayPart(2, 6, ThreeOvernight))
@@ -34,7 +34,14 @@ internal data class ChannelProgramming(val number: Int, val name: String, val se
/** Films a series channel may carry, each only in an event that names it. Empty everywhere but Ring X. */
val channelFilms: List<String> = emptyList(),
/** Series a film channel may carry, each only in an event that names it, one whole episode a night in order. Empty everywhere but After Dark. */
val filmSeries: List<String> = emptyList()) {
val filmSeries: List<String> = emptyList(),
/**
* Editorially weighted rotation (see [extendWeighted]), switched on per channel: each show's weight from its tier in
* the channel's brief. Null keeps equal turns. Only Orbit Three has it (approved 4 November 2026).
*/
val tierWeights: Map<String, Double>? = null) {
/** A show's weight here, by its tier; a show the brief doesn't name counts as supporting. */
fun weightOf(show: PoolSeries) = tierWeights?.get(seriesKey(show.title)) ?: TIER_SUPPORTING
/** Whether a show plays its episodes in a mixed order here. */
fun mixes(show: PoolSeries) = shuffleEpisodes || seriesKey(show.title) in shuffleTitles.mapTo(HashSet(), ::seriesKey)
/** Changes when the list does, so the episode cache is read again. What's already committed stays. */
@@ -89,7 +96,10 @@ internal val SmartChannels = listOf(
ChannelPresets.filter { it.smartOnly }.map { ChannelProgramming(it.number, it.name, it.searches, seriesCount = if (it.films) it.searches.size else 60, finishTogether = !it.films, exactTitles = true,
filmRestMs = if (it.films) 7 * 24 * 60 * 60_000L else null,
suggestionRules = SmartChannelRules[it.number].orEmpty(), dayParts = SmartChannelParts[it.number].orEmpty(), shuffleTitles = SmartChannelMixed[it.number].orEmpty(),
channelFilms = if (it.number == 401) PpvSunday else emptyList()) }
channelFilms = if (it.number == 401) PpvSunday else emptyList(), tierWeights = SmartChannelTiers[it.number]) }
/** Editorially weighted rotation, per channel, once its tiers are approved. Orbit Three only for now (4 November 2026). */
private val SmartChannelTiers: Map<Int, Map<String, Double>> get() = mapOf(103 to ThreeTiers)
/** Shows that play in a mixed order on channels whose identity is agreed. See ChannelIdentities.kt. */
private val SmartChannelMixed: Map<Int, Set<String>> get() = mapOf(101 to Orbit1Mixed, 102 to Orbit2Mixed, 103 to ThreeMixed, 104 to GoldMixed, 105 to RiotMixed,
@@ -134,7 +144,11 @@ internal data class ScheduleCursor(val lastSeriesId: String? = null, val marks:
/** When each film last started, for its rest period. */
val filmShown: Map<String, Long> = emptyMap(),
/** The last show to air in each block, so a block picks up its rotation where it left off rather than starting again each day. */
val blockLast: Map<String, String> = emptyMap())
val blockLast: Map<String, String> = emptyMap(),
/** Weighted rotation only: each block's tally per show, the minutes it has aired there divided by its tier's weight. */
val tallies: Map<String, Map<String, Double>> = emptyMap(),
/** Weighted rotation only: when each show last started its run from the top, so a short series doesn't restart too often. */
val runStarted: Map<String, Long> = emptyMap())
internal data class ScheduleEntry(val seriesId: String, val mark: EpisodeMark, val media: ScheduledMedia, val startMs: Long,
/** Why the planner chose this, for diagnostics only. Empty for programmes planned before reasons were kept. */
@@ -292,6 +306,85 @@ private const val ON_TIME_RUN_IN_MS = 90 * 60_000L
/** A series on a film channel airs at most once in this long, so a long event window still holds one episode. */
private const val SERIES_NIGHT_MS = 12 * 60 * 60_000L
/** The tiers' weights: a core show gets one and a half times a supporting show's airtime in a block, a surprise half. */
internal const val TIER_CORE = 3.0
internal const val TIER_SUPPORTING = 2.0
internal const val TIER_SURPRISE = 1.0
/** A series doesn't start its run from the top again within this long of last doing so, while others can play. */
internal const val RUN_REST_MS = 3 * 24 * 60 * 60_000L
/** The same file never airs again within this long while another show could play. A minimum; other protections still apply. */
internal const val SAME_FILE_MS = 24 * 60 * 60_000L
/**
* Editorially weighted rotation (Orbit Three first, 4 November 2026). Each block keeps a tally per show: the minutes it
* has aired in that block divided by its tier's weight. The eligible show with the lowest tally goes next, so airtime
* follows the tiers, not episode counts or runtimes, and no eligible show can be passed over for long. A show new to a
* block starts level with the block's lowest tally, so it neither floods in nor waits. Nobody waits for anyone else to
* finish: each show follows its own cursor, in order or through its fixed shuffled deck, exactly as before; this only
* decides how often a show is chosen, never which episode it plays. Eligibility, relaxed in this order only when nothing
* else is left: not the show that just played; not a file aired within [SAME_FILE_MS]; not a series starting its run again
* within [RUN_REST_MS] of last starting it; and never a show airing on another channel at that moment.
*/
internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, weightOf: (PoolSeries) -> Double,
dayParts: List<DayPart>, zone: java.time.ZoneId, avoid: ProgrammeClash, shuffle: Boolean, mixed: (PoolSeries) -> Boolean,
/** Files aired shortly before [fromMs], for the same-file guard across a top-up. */
recentFiles: Map<String, Long> = emptyMap()): ChannelPlan {
val marks = cursor.marks.toMutableMap()
val shown = cursor.filmShown.toMutableMap()
val tallies = cursor.tallies.mapValues { it.value.toMutableMap() }.toMutableMap()
val runStarted = cursor.runStarted.toMutableMap()
val aired = recentFiles.toMutableMap()
val mixes = HashMap<String, List<PoolEpisode>>()
val entries = mutableListOf<ScheduleEntry>()
var last = cursor.lastSeriesId
var start = fromMs
fun isMixed(show: PoolSeries) = shuffle || mixed(show)
fun running(show: PoolSeries) = if (isMixed(show)) mixes.getOrPut(show.id) { shuffledEpisodes(show) } else show.episodes
fun following(show: PoolSeries): PoolEpisode {
if (!isMixed(show)) return nextEpisode(show, marks[show.id])
val mix = running(show)
return mix[(mix.indexOfFirst { it.mark == marks[show.id] } + 1) % mix.size]
}
fun hadItsTurn(available: List<PoolSeries>, at: Long) = available.any { film -> film.isFilm && shown[film.id]?.let { at - it < ONCE_A_NIGHT_MS } == true }
fun partAt(at: Long): Triple<List<PoolSeries>, String, DayPart?> {
val first = dayPartFor(pool, dayParts, at, zone)
val part = first.third ?: return first
return if (part.once && hadItsTurn(first.first, at)) dayPartFor(pool, dayParts - part, at, zone) else first
}
// A show that has left the pool loses its tally, so if it comes back it joins level rather than owed a backlog.
val ids = pool.mapTo(HashSet()) { it.id }
tallies.values.forEach { block -> block.keys.retainAll(ids) }
while (start < untilMs) {
val (available, block, part) = partAt(start)
val tally = tallies.getOrPut(block) { HashMap() }
// A show new to the block, or back in it, joins level with the block's lowest, not at nothing.
val floor = available.mapNotNull { tally[it.id] }.minOrNull() ?: 0.0
available.forEach { tally.putIfAbsent(it.id, floor) }
val clear = available.filter { !avoid(it, start, start + following(it).durationMs) }.ifEmpty { available }
val rules = listOf<(PoolSeries) -> Boolean>(
{ it.id != last }, { aired[following(it).id]?.let { at -> start - at < SAME_FILE_MS } != true }, { following(it).mark != running(it).first().mark || runStarted[it.id]?.let { at -> start - at < RUN_REST_MS } != true })
// Drop the softest rules first, only as far as needed to leave a choice.
val eligible = (rules.size downTo 0).asSequence().map { kept -> clear.filter { show -> rules.take(kept).all { it(show) } } }.first { it.isNotEmpty() }
// A show held back by the 24-hour or restart rule is brought up level, so it comes back to its share without a burst.
val low = eligible.minOf { tally[it.id]!! }
clear.filter { it.id != last && it !in eligible }.forEach { tally[it.id] = maxOf(tally[it.id]!!, low) }
val series = eligible.minWith(compareBy<PoolSeries> { tally[it.id]!! }.thenBy { pool.indexOf(it) })
val episode = following(series)
val why = "$block; weighted: lowest tally for its tier (${"%.0f".format(tally[series.id])})" + if (eligible.size < clear.size) ", others resting or just played" else ""
val item = if (series.isFilm) SampleItem(series.title, "Movie", episode.durationMs / 60_000, "", episode.id, episode.durationMs) else scheduledItem(series.title, episode)
entries += ScheduleEntry(series.id, episode.mark, ScheduledMedia(item, episode.sourceId, episode.durationMs), start, why, if (series in available) part?.key.orEmpty() else "")
tally[series.id] = tally[series.id]!! + episode.durationMs / 60_000.0 / weightOf(series)
marks[series.id] = episode.mark
aired[episode.id] = start
// The start of a run: its first episode in season order, or the first of its shuffled deck.
if (episode.mark == running(series).first().mark) runStarted[series.id] = start
if (series.isFilm) shown[series.id] = start
last = series.id
start += episode.durationMs
}
return ChannelPlan(entries, ScheduleCursor(last, marks, shown, cursor.blockLast, tallies, runStarted))
}
/** 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, finishTogether: Boolean = false,
dayParts: List<DayPart> = emptyList(), zone: java.time.ZoneId = java.time.ZoneId.systemDefault(), avoid: ProgrammeClash = { _, _, _ -> false }, shuffle: Boolean = false,
@@ -423,7 +516,7 @@ internal fun airedCursor(base: ScheduleCursor, entries: List<ScheduleEntry>, now
marks[it.seriesId] = it.mark; last = it.seriesId
if (it.media.item.type == "Movie") shown[it.seriesId] = it.startMs
}
return ScheduleCursor(last, marks, shown, base.blockLast)
return ScheduleCursor(last, marks, shown, base.blockLast, base.tallies, base.runStarted)
}
/**
@@ -432,13 +525,18 @@ internal fun airedCursor(base: ScheduleCursor, entries: List<ScheduleEntry>, now
*/
internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List<PoolSeries>?, nowMs: Long, filmRestMs: Long? = null, finishTogether: Boolean = false,
dayParts: List<DayPart> = emptyList(), zone: java.time.ZoneId = java.time.ZoneId.systemDefault(), avoid: ProgrammeClash = { _, _, _ -> false }, shuffle: Boolean = false, noThirdInARow: Boolean = true,
mixed: (PoolSeries) -> Boolean = { false }, blockRotation: Boolean = true): ChannelPlan? {
mixed: (PoolSeries) -> Boolean = { false }, blockRotation: Boolean = true,
/** Set for a channel with editorially weighted rotation ([ChannelProgramming.weightOf]); null keeps equal turns. */
weightOf: ((PoolSeries) -> Double)? = null): 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 trailing = kept?.entries?.lastOrNull()?.let { tail -> kept.entries.asReversed().takeWhile { it.seriesId == tail.seriesId }.size } ?: 0
val added = extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow, blockRotation)
val added = if (weightOf != null && filmRestMs == null) {
val recent = kept?.entries.orEmpty().filter { it.startMs >= from - SAME_FILE_MS }.associate { it.media.item.id to it.startMs }
extendWeighted(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, weightOf, dayParts, zone, avoid, shuffle, mixed, recent)
} else extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow, blockRotation)
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
}
@@ -108,7 +108,8 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
// Other channels' plans are only read if this one is actually about to grow.
val others by lazy { clashesWith((SmartChannels.map { it.number }.filter { it != number } + DRIVE_IN_NUMBER).mapNotNull { store.loadPlan(userId, it) }) }
val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts,
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes,
weightOf = programming.tierWeights?.let { programming::weightOf }) ?: 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 })
@@ -66,7 +66,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.96.0\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.97.0\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -77,6 +77,8 @@ internal class ScheduleStore(private val directory: File) {
.put("marks", JSONObject().also { marks -> cursor.marks.forEach { (id, mark) -> marks.put(id, JSONArray().put(mark.season).put(mark.episode)) } })
.put("shown", JSONObject().also { shown -> cursor.filmShown.forEach { (id, at) -> shown.put(id, at) } })
.also { o -> if (cursor.blockLast.isNotEmpty()) o.put("blocks", JSONObject().also { blocks -> cursor.blockLast.forEach { (block, id) -> blocks.put(block, id) } }) }
.also { o -> if (cursor.tallies.isNotEmpty()) o.put("tallies", JSONObject().also { all -> cursor.tallies.forEach { (block, t) -> all.put(block, JSONObject().also { row -> t.forEach { (id, v) -> row.put(id, v) } }) } }) }
.also { o -> if (cursor.runStarted.isNotEmpty()) o.put("runs", JSONObject().also { runs -> cursor.runStarted.forEach { (id, at) -> runs.put(id, at) } }) }
private fun decodeCursor(o: JSONObject): ScheduleCursor {
val marks = o.getJSONObject("marks")
return ScheduleCursor(if (o.isNull("last")) null else validId(o.getString("last")),
@@ -84,7 +86,10 @@ internal class ScheduleStore(private val directory: File) {
// Absent in files saved before film channels existed.
o.optJSONObject("shown")?.let { shown -> shown.keys().asSequence().associate { id -> validId(id) to shown.getLong(id) } }.orEmpty(),
// Absent in files saved before blocks kept their own place.
o.optJSONObject("blocks")?.let { blocks -> blocks.keys().asSequence().associate { block -> block.take(80) to validId(blocks.getString(block)) } }.orEmpty())
o.optJSONObject("blocks")?.let { blocks -> blocks.keys().asSequence().associate { block -> block.take(80) to validId(blocks.getString(block)) } }.orEmpty(),
// Absent until a channel uses weighted rotation.
o.optJSONObject("tallies")?.let { all -> all.keys().asSequence().associate { block -> block.take(80) to all.getJSONObject(block).let { row -> row.keys().asSequence().associate { id -> validId(id) to row.getDouble(id).also { v -> require(v.isFinite() && v >= 0) } } } } }.orEmpty(),
o.optJSONObject("runs")?.let { runs -> runs.keys().asSequence().associate { id -> validId(id) to runs.getLong(id) } }.orEmpty())
}
private fun validId(id: String) = id.also { require(EmbyClient.validId(it)) }
/** Reasons are diagnostics. A long one is cut rather than refused, so it can never cost a plan. */
@@ -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.96.0")
next.setRequestProperty("User-Agent", "OrbitTV/0.97.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()) {