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
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 127
versionName = "0.96.0-special-idents"
versionCode = 128
versionName = "0.97.0-weighted-three"
}
buildFeatures { compose = true }
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
@@ -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()) {
@@ -0,0 +1,66 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
/**
* Four weeks of top-ups on every channel from copies of the box's committed plans and pools, run by hand:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*ReplayFingerprintTest*'
* Writes replay-fingerprints.txt there, one line per channel: a fingerprint of every programme booked and why. Run it
* on two versions of the app to show which channels a change touches. Only uses what every version has.
*/
class ReplayFingerprintTest {
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
private fun plan(file: File): ChannelPlan {
val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
val entries = (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n")
ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d),
o.getLong("a"), o.optString("w"), o.optString("p"))
}
return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"),
marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } },
t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(),
t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty()))
}
private fun pool(file: File): List<PoolSeries> {
val rows = JSONObject(file.readText()).getJSONArray("series")
return (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes")
PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j ->
val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5))
}, o.optString("group"))
}
}
@Test fun fourWeeks() {
assumeTrue(dir != null && dir.isDirectory)
val zone = java.time.ZoneId.of("Europe/London")
val out = StringBuilder()
for (programming in SmartChannels.sortedBy { it.number }) {
val committedFile = File(dir, "schedule-${programming.number}.json"); val poolFile = File(dir, "episodes-${programming.number}.json")
if (!committedFile.exists() || !poolFile.exists()) continue
val committed = plan(committedFile); val series = pool(poolFile)
var current = committed
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
val end = now + 28 * 24 * 60 * 60_000L
val all = committed.entries.toMutableList()
while (now < end) {
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone,
shuffle = programming.shuffleEpisodes, mixed = programming::mixes) ?: break
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
now += 6 * 60 * 60_000L
}
val text = all.joinToString("\n") { "${it.startMs} ${it.seriesId} ${it.mark} ${it.media.item.id} ${it.why} ${it.presentation}" }
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) }.take(16)
val committedDigest = java.security.MessageDigest.getInstance("SHA-256").digest(all.take(committed.entries.size).joinToString("\n") { "${it.startMs} ${it.seriesId} ${it.mark} ${it.media.item.id} ${it.why} ${it.presentation}" }.toByteArray()).joinToString("") { "%02x".format(it) }.take(16)
out.appendLine("${programming.number} committed=$committedDigest kept=${all.take(committed.entries.size) == committed.entries} fourWeeks=$digest programmes=${all.size}")
}
File(dir, System.getenv("ORBIT_FINGERPRINT_NAME") ?: "replay-fingerprints.txt").writeText(out.toString())
println(out)
}
}
@@ -0,0 +1,138 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
/**
* Orbit Three, four weeks of new bookings after its committed plan, from copies of the box's files, both ways, run by hand:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*WeightedRotationReplayTest*'
* "Before" is the rule installed today: equal turns with finish-together, Family Guy in the evening. "After" is the app
* as it is now: Family Guy out of the evening and weighted rotation. Both top up every six hours exactly as the box does,
* from the committed plan. Writes weighted-rotation-replay.txt with the figures, and fails on any broken rule.
*/
class WeightedRotationReplayTest {
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
private val zone = java.time.ZoneId.of("Europe/London")
private val day = 24 * 60 * 60_000L
private val hour = 60 * 60_000L
private fun plan(file: File): ChannelPlan {
val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
val entries = (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n")
ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d),
o.getLong("a"), o.optString("w"), o.optString("p"))
}
return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"),
marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } },
t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(),
t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty()))
}
private fun pool(file: File): List<PoolSeries> {
val rows = JSONObject(file.readText()).getJSONArray("series")
return (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes")
PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j ->
val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5))
}, o.optString("group"))
}
}
private fun replay(committed: ChannelPlan, series: List<PoolSeries>, parts: List<DayPart>, programming: ChannelProgramming, weightOf: ((PoolSeries) -> Double)?, restartEvery: Int = 0): List<ScheduleEntry> {
var current = committed
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
val end = committed.endMs + 28 * day
val all = committed.entries.toMutableList()
val folder = java.nio.file.Files.createTempDirectory("replay").toFile()
var step = 0
while (now < end) {
// Now and then, a restart: the plan goes through the save file, as it does when the box is switched off.
if (restartEvery > 0 && ++step % restartEvery == 0) { ScheduleStore(folder).savePlan("user", 103, current); current = ScheduleStore(folder).loadPlan("user", 103)!! }
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, parts, zone,
shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = weightOf) ?: break
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
now += 6 * hour
}
all.sortBy { it.startMs }
return all.filter { it.startMs < end }
}
private val tierNames = mapOf(TIER_CORE to "core", TIER_SUPPORTING to "supporting", TIER_SURPRISE to "surprise")
private fun report(name: String, entries: List<ScheduleEntry>, series: List<PoolSeries>, parts: List<DayPart>, programming: ChannelProgramming, out: StringBuilder): Map<String, Any> {
val titles = series.associate { it.id to it.title }
fun tier(id: String) = tierNames.getValue(ThreeTiers[seriesKey(titles.getValue(id))] ?: TIER_SUPPORTING)
fun block(e: ScheduleEntry) = dayPartFor(series, parts, e.startMs, zone).second
val minutes = entries.groupBy { it.seriesId }.mapValues { (_, es) -> es.sumOf { it.media.durationMs } / 60_000.0 }
val total = minutes.values.sum()
out.appendLine("== $name (${entries.size} programmes, ${"%.0f".format(total / 60)} hours)")
for (t in listOf("core", "supporting", "surprise")) {
val m = minutes.filterKeys { tier(it) == t }.values.sum()
out.appendLine(" $t: ${"%.1f".format(100 * m / total)}% of airtime")
}
// By block: what each tier gets in the evening, where the starvation was.
entries.groupBy(::block).toSortedMap().forEach { (b, es) ->
val bm = es.groupBy { it.seriesId }.mapValues { (_, x) -> x.sumOf { it.media.durationMs } / 60_000.0 }; val bt = bm.values.sum()
out.appendLine(" $b: " + listOf("core", "supporting", "surprise").joinToString { t -> "$t ${"%.0f".format(100 * bm.filterKeys { tier(it) == t }.values.sum() / bt)}%" } +
"; top: " + bm.entries.sortedByDescending { it.value }.take(4).joinToString { "${titles[it.key]} ${"%.0f".format(100 * it.value / bt)}%" })
}
val four = listOf("Gavin & Stacey", "The Mighty Boosh", "Spaced", "Phoenix Nights")
out.appendLine(" the four: " + four.joinToString { t -> val id = series.firstOrNull { seriesKey(it.title) == seriesKey(t) }?.id; "$t ${entries.count { it.seriesId == id }} airings (${entries.count { it.seriesId == id && block(it).contains("18") }} in the evening)" })
// Longest wait between airings, from the start of the period for a show that hasn't aired yet.
val first = entries.first().startMs; val last = entries.last().endMs
val inBlocks = parts.flatMap { it.titles }.map(::seriesKey).toSet()
val waits = series.filter { seriesKey(it.title) in inBlocks }.associate { s ->
s.title to (listOf(first) + entries.filter { it.seriesId == s.id }.map { it.startMs } + listOf(last)).zipWithNext().maxOf { (a, b) -> b - a } / day.toDouble()
}
out.appendLine(" longest waits: " + waits.entries.sortedByDescending { it.value }.take(6).joinToString { "${it.key} ${"%.1f".format(it.value)} d" })
val never = waits.filter { (t, _) -> entries.none { titles[it.seriesId] == t } }.keys
out.appendLine(" never aired: ${never.ifEmpty { listOf("none") }.joinToString()}")
val sameFile = entries.groupBy { it.media.item.id }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.startMs - a.startMs < SAME_FILE_MS } }
val twice = entries.zipWithNext().count { (a, b) -> a.seriesId == b.seriesId }
val ordered = series.filter { !programming.mixes(it) }.associateBy { it.id }
val backwards = entries.filter { it.seriesId in ordered }.groupBy { it.seriesId }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.mark <= a.mark && b.mark != ordered.getValue(a.seriesId).episodes.first().mark } }
val restarts = series.associate { s -> s.title to entries.filter { it.seriesId == s.id && it.mark == (if (programming.mixes(s)) shuffledEpisodes(s) else s.episodes).first().mark }.map { it.startMs } }
val quick = restarts.mapValues { (_, at) -> at.zipWithNext().count { (a, b) -> b - a < RUN_REST_MS } }.filterValues { it > 0 }
// A burst: one show taking more than half of any three-hour stretch.
val bursts = entries.indices.count { i -> val window = entries.drop(i).takeWhile { it.startMs < entries[i].startMs + 3 * hour }; window.size >= 4 && window.count { it.seriesId == entries[i].seriesId } * 2 > window.size }
val gaps = entries.zipWithNext().count { (a, b) -> a.endMs != b.startMs }
val outOfBlock = entries.count { e -> val (available, _, _) = dayPartFor(series, parts, e.startMs, zone); available.none { it.id == e.seriesId } }
out.appendLine(" same file within 24 h: $sameFile; same show twice running: $twice; in-order shows stepping back: $backwards; gaps or overlaps: $gaps; outside its block: $outOfBlock")
out.appendLine(" runs restarted within 3 days: ${quick.ifEmpty { mapOf("none" to 0) }}; three-hour stretches over half one show: $bursts")
out.appendLine(" by title: " + series.filter { (minutes[it.id] ?: 0.0) > 0 }.sortedByDescending { minutes[it.id] }.joinToString { "${it.title} ${"%.1f".format(100 * minutes.getValue(it.id) / total)}% [${tier(it.id).take(3)}]" })
out.appendLine()
return mapOf("sameFile" to sameFile, "twice" to twice, "backwards" to backwards, "gaps" to gaps, "outOfBlock" to outOfBlock, "never" to never, "maxWait" to waits.values.max())
}
@Test fun orbitThreeFourWeeks() {
assumeTrue(dir != null && File(dir, "episodes-103.json").exists())
val programming = SmartChannels.first { it.number == 103 }
val committed = plan(File(dir, "schedule-103.json")); val series = pool(File(dir, "episodes-103.json"))
val before = programming.dayParts.map { if (it.fromHour == 18 && it.toHour == 22) it.copy(titles = it.titles + "Family Guy") else it }
val old = replay(committed, series, before, programming, null)
val new = replay(committed, series, programming.dayParts, programming, programming::weightOf)
val restarted = replay(committed, series, programming.dayParts, programming, programming::weightOf, restartEvery = 3)
assertEquals(committed.entries, old.take(committed.entries.size)); assertEquals(committed.entries, new.take(committed.entries.size))
assertEquals("a restart changes nothing", new, restarted)
val start = committed.endMs
val out = StringBuilder("Orbit Three: four weeks of new bookings after the committed plan (which ends ${java.time.Instant.ofEpochMilli(start).atZone(zone).toLocalDateTime()}),\n" +
"both rules topping up every six hours from the box's real committed plan and pool. Committed programmes are identical in both.\n\n")
report("Before: equal turns, finish together, Family Guy in the evening", old.filter { it.startMs >= start }, series, before, programming, out)
val after = report("After: weighted 3 / 2 / 1, Family Guy out of the evening", new.filter { it.startMs >= start }, series, programming.dayParts, programming, out)
// Scottish Comedy Night: every programme Friday and Saturday 21:00 to midnight is a Scottish show, presented as one.
val scottish = new.filter { it.startMs >= start }.filter { val l = java.time.Instant.ofEpochMilli(it.startMs).atZone(zone); l.dayOfWeek in setOf(java.time.DayOfWeek.FRIDAY, java.time.DayOfWeek.SATURDAY) && l.hour >= 21 }
out.appendLine("Scottish Comedy Night: ${scottish.size} programmes, all presented as three.scottish: ${scottish.all { it.presentation == "three.scottish" }}")
out.appendLine("Family Guy in the evening after: ${new.filter { it.startMs >= start }.count { e -> series.first { it.id == e.seriesId }.title == "Family Guy" }} airings")
out.appendLine("A save and reload every 18 hours gives the identical four weeks: true")
File(dir, "weighted-rotation-replay.txt").writeText(out.toString())
println(out)
assertTrue(scottish.isNotEmpty() && scottish.all { it.presentation == "three.scottish" })
assertEquals(0, after["sameFile"]); assertEquals(0, after["twice"]); assertEquals(0, after["backwards"]); assertEquals(0, after["gaps"]); assertEquals(0, after["outOfBlock"])
assertEquals(emptySet<String>(), after["never"])
}
}
@@ -0,0 +1,162 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.ZoneOffset
class WeightedRotationTest {
private val zone = ZoneOffset.UTC
private val day = 24 * 60 * 60_000L
private val start = java.time.LocalDate.of(2026, 11, 10).atStartOfDay(zone).toInstant().toEpochMilli()
private fun show(title: String, episodes: Int, minutes: Int = 25) =
PoolSeries(title, title, (1..episodes).map { PoolEpisode("$title-$it", "src", EpisodeMark(1 + (it - 1) / 10, 1 + (it - 1) % 10), "E$it", minutes * 60_000L) })
private fun weights(vararg pairs: Pair<String, Double>) = pairs.associate { seriesKey(it.first) to it.second }.let { w -> { s: PoolSeries -> w[seriesKey(s.title)] ?: TIER_SUPPORTING } }
private fun run(pool: List<PoolSeries>, weightOf: (PoolSeries) -> Double, days: Int = 28, parts: List<DayPart> = emptyList(), mixed: (PoolSeries) -> Boolean = { false }, cursor: ScheduleCursor = ScheduleCursor()) =
extendWeighted(pool, cursor, start, start + days * day, weightOf, parts, zone, { _, _, _ -> false }, false, mixed)
private fun minutes(plan: ChannelPlan) = plan.entries.groupBy { it.seriesId }.mapValues { (_, es) -> es.sumOf { it.media.durationMs } / 60_000.0 }
@Test fun airtimeFollowsTheTiersNotTheEpisodeCounts() {
val pool = listOf(show("Core", 300), show("Huge surprise", 457), show("Supporting", 400))
val m = minutes(run(pool, weights("Core" to TIER_CORE, "Huge surprise" to TIER_SURPRISE)))
// 3 : 1 : 2, whatever the episode counts.
assertEquals(3.0, m.getValue("Core") / m.getValue("Huge surprise"), 0.15)
assertEquals(1.5, m.getValue("Core") / m.getValue("Supporting"), 0.1)
}
@Test fun longEpisodesDontBuyExtraAirtime() {
val pool = listOf(show("Hour long", 200, 56), show("Half hour", 200, 25)) + (1..4).map { show("Other $it", 200) }
val m = minutes(run(pool, weights()))
assertEquals(1.0, m.getValue("Hour long") / m.getValue("Half hour"), 0.1)
}
@Test fun aLongSeriesCantHoldAShortOneHostageAndNothingStarves() {
// Three's old trap: the short shows have reached the end of their runs, a 457-episode show hasn't.
val pool = listOf(show("Gavin", 19), show("Spaced", 14), show("Huge", 457))
val atEnd = ScheduleCursor(marks = mapOf("Gavin" to pool[0].episodes.last().mark, "Spaced" to pool[1].episodes.last().mark))
val plan = run(pool, weights("Gavin" to TIER_CORE, "Spaced" to TIER_CORE, "Huge" to TIER_SURPRISE), cursor = atEnd)
for (title in listOf("Gavin", "Spaced", "Huge")) {
val times = listOf(start) + plan.entries.filter { it.seriesId == title }.map { it.startMs } + listOf(plan.entries.last().endMs)
val longest = times.zipWithNext().maxOf { (a, b) -> b - a }
assertTrue("$title waits ${longest / day.toDouble()} days", longest <= 4 * day)
}
}
@Test fun aShortSeriesDoesntRestartTooOftenAndComesBackWithoutABurst() {
val pool = listOf(show("Six parter", 6), show("Long A", 200), show("Long B", 200))
val plan = run(pool, weights("Six parter" to TIER_CORE))
val six = plan.entries.filter { it.seriesId == "Six parter" }
val starts = six.filter { it.mark == pool[0].episodes.first().mark }.map { it.startMs }
assertTrue(starts.size >= 5)
starts.zipWithNext().forEach { (a, b) -> assertTrue(b - a >= RUN_REST_MS) }
// Back from its rest it takes its turn with the others, never more than every other slot.
plan.entries.zipWithNext().forEach { (a, b) -> assertFalse(a.seriesId == b.seriesId) }
starts.drop(1).forEach { at -> val next = plan.entries.filter { it.startMs >= at }.take(6); assertTrue(next.count { it.seriesId == "Six parter" } <= 3) }
}
@Test fun aLongCoreSeriesCarriesStraightOnIntoItsNextRun() {
// Spaced's 14 episodes take more than three days at its share, so nothing holds it back at the end of a run.
val pool = listOf(show("Spaced", 14)) + (1..30).map { show("Other $it", 100) }
val plan = run(pool, weights("Spaced" to TIER_CORE))
val spaced = plan.entries.filter { it.seriesId == "Spaced" }
val waits = spaced.zipWithNext().map { (a, b) -> b.startMs - a.startMs }
val usual = waits.sorted()[waits.size / 2]
assertTrue(waits.map { it / 3_600_000.0 }.toString() + " usual ${usual / 3_600_000.0}", waits.max() <= 2 * usual)
}
@Test fun inOrderShowsStayInOrderAndShuffledShowsKeepTheirDeck() {
val story = show("Story", 18); val sketch = show("Sketch", 16)
val pool = listOf(story, sketch, show("Other", 30))
val mixed = { s: PoolSeries -> s.title == "Sketch" }
val plan = run(pool, weights("Story" to TIER_CORE), mixed = mixed)
val storyMarks = plan.entries.filter { it.seriesId == "Story" }.map { it.mark }
storyMarks.zipWithNext().forEach { (a, b) -> assertTrue(b > a || b == story.episodes.first().mark) }
// The sketch show plays its fixed shuffled deck in order, every episode before any repeat.
val deck = shuffledEpisodes(sketch).map { it.mark }
val sketchMarks = plan.entries.filter { it.seriesId == "Sketch" }.map { it.mark }
sketchMarks.forEachIndexed { i, mark -> assertEquals(deck[i % deck.size], mark) }
}
@Test fun aTopUpCarriesOnExactlyAsOneLongPlanWould() {
val pool = listOf(show("Story", 18), show("Sketch", 16), show("Long", 120), show("Odd", 6))
val w = weights("Story" to TIER_CORE, "Odd" to TIER_SURPRISE)
val mixed = { s: PoolSeries -> s.title == "Sketch" }
val whole = run(pool, w, days = 14, mixed = mixed)
val first = extendWeighted(pool, ScheduleCursor(), start, start + 7 * day, w, emptyList(), zone, { _, _, _ -> false }, false, mixed)
val recent = first.entries.filter { it.startMs >= first.endMs - SAME_FILE_MS }.associate { it.media.item.id to it.startMs }
val second = extendWeighted(pool, first.tail, first.endMs, start + 14 * day, w, emptyList(), zone, { _, _, _ -> false }, false, mixed, recent)
assertEquals(whole.entries.map { it.seriesId to it.mark }, (first.entries + second.entries).map { it.seriesId to it.mark })
}
@Test fun noShowTwiceRunningAndNoFileAgainWithin24Hours() {
val pool = listOf(show("A", 3), show("B", 40), show("C", 40))
val plan = run(pool, weights("A" to TIER_CORE))
plan.entries.zipWithNext().forEach { (a, b) -> assertFalse(a.seriesId == b.seriesId) }
plan.entries.groupBy { it.media.item.id }.values.forEach { es -> es.zipWithNext().forEach { (a, b) -> assertTrue(b.startMs - a.startMs >= SAME_FILE_MS) } }
}
@Test fun aShowJoiningLaterDoesntFloodTheBlock() {
val pool = listOf(show("A", 100), show("B", 100))
val week = run(pool, weights(), days = 7)
val joined = extendWeighted(pool + show("New", 100), week.tail, week.endMs, week.endMs + 7 * day, weights(), emptyList(), zone, { _, _, _ -> false }, false, { false })
// The newcomer takes its share, about a third, not every slot until it has caught up.
val share = joined.entries.count { it.seriesId == "New" }.toDouble() / joined.entries.size
assertEquals(1.0 / 3, share, 0.05)
}
@Test fun blocksAndEventsAreKept() {
val pool = listOf(show("Still Game", 50), show("Day show", 50), show("Late show", 50))
val parts = listOf(DayPart(21, 0, listOf("Still Game"), days = setOf(java.time.DayOfWeek.FRIDAY), key = "three.scottish"),
DayPart(6, 21, listOf("Day show", "Still Game")), DayPart(21, 6, listOf("Late show")))
val plan = run(pool, weights("Still Game" to TIER_CORE), parts = parts)
plan.entries.forEach { e ->
val l = java.time.Instant.ofEpochMilli(e.startMs).atZone(zone)
val expected = parts.first { it.covers(l.hour, l.dayOfWeek) }.titles
assertTrue("${e.seriesId} at $l", e.seriesId in expected)
if (l.dayOfWeek == java.time.DayOfWeek.FRIDAY && l.hour >= 21) assertEquals("three.scottish", e.presentation)
}
}
@Test fun aRestartBetweenTopUpsChangesNothingAndCommittedProgrammesStay() {
val pool = listOf(show("Story", 18), show("Sketch", 16), show("Long", 120), show("Odd", 6))
val w = weights("Story" to TIER_CORE, "Odd" to TIER_SURPRISE)
val mixed = { s: PoolSeries -> s.title == "Sketch" }
// A plan committed before the switch, by today's equal turns: it must come through untouched.
val committed = extendSchedule(pool, ScheduleCursor(), start, start + 7 * day, mixed = mixed, zone = zone)
val folder = java.nio.file.Files.createTempDirectory("weighted").toFile()
var straight: ChannelPlan = committed; var restarted: ChannelPlan = committed
val all = committed.entries.toMutableList(); val allRestarted = committed.entries.toMutableList()
var now = start + day
while (now < start + 28 * day) {
straight = topUpPlan(straight, straight.tail, pool, now, zone = zone, mixed = mixed, weightOf = w)!!
ScheduleStore(folder).savePlan("user", 103, restarted)
restarted = topUpPlan(ScheduleStore(folder).loadPlan("user", 103), ScheduleCursor(), pool, now, zone = zone, mixed = mixed, weightOf = w)!!
straight.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
restarted.entries.filter { e -> allRestarted.none { it.startMs == e.startMs } }.forEach { allRestarted += it }
now += 6 * 60 * 60_000L
}
assertEquals(all, allRestarted)
assertEquals(committed.entries, all.take(committed.entries.size))
assertTrue(all.size > 2 * committed.entries.size)
all.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) }
// The tallies and run starts came through the save as they went in.
assertEquals(straight.tail, ScheduleStore(folder).also { it.savePlan("user", 103, straight) }.loadPlan("user", 103)!!.tail)
// Story keeps its order across every top-up and restart; Sketch keeps its deck.
val story = all.filter { it.seriesId == "Story" }.map { it.mark }
story.zipWithNext().forEach { (a, b) -> assertTrue(b > a || b == pool[0].episodes.first().mark) }
val deck = shuffledEpisodes(pool[1]).map { it.mark }
val sketch = all.filter { it.seriesId == "Sketch" }.map { it.mark }
val at = deck.indexOf(sketch.first())
sketch.forEachIndexed { i, mark -> assertEquals(deck[(at + i) % deck.size], mark) }
}
@Test fun onlyOrbitThreeIsWeighted() {
assertEquals(listOf(103), SmartChannels.filter { it.tierWeights != null }.map { it.number })
val three = SmartChannels.first { it.number == 103 }
assertTrue(three.searches.none { seriesKey(it) == seriesKey("Family Guy") })
assertEquals(TIER_CORE, three.weightOf(show("Gavin & Stacey", 1)), 0.0)
assertEquals(TIER_SURPRISE, three.weightOf(show("Brass Eye", 1)), 0.0)
assertEquals(TIER_SUPPORTING, three.weightOf(show("Peep Show", 1)), 0.0)
}
}
+75
View File
@@ -0,0 +1,75 @@
# Orbit TV 0.97.0: editorially weighted rotation on Orbit Three (Phase 1)
Phase 1 of the plan after the editorial compliance audit, approved by Paul on 3 November 2026 at 23:45: Orbit Three only, behind a per-channel switch. Scheduler only: no playback, presentation, asset or homepage changes.
## What's in it
- **Tiers on Orbit Three** (`ThreeTiers`, ChannelIdentities.kt), from docs/channels/orbit-three.md: core 3, supporting 2, surprises 1. Core: 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. Surprises: 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. Every other listed show is supporting.
- **The switch** is `ChannelProgramming.tierWeights`. Only Orbit Three (103) sets it; every other channel takes exactly the path it took in 0.96.0.
- **Family Guy is out of Three's evening.** Riot is its home. Its progress is kept in Three's cursor, so a future approved crossover would carry on where it left off. Committed bookings are untouched, so any Family Guy already booked on Three still airs.
- **The rule** (`extendWeighted`, ChannelSchedule.kt). Each block keeps a tally per show: the minutes it has aired there 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 nobody waits for anyone else to finish (finish-together doesn't apply).
- A show new to a block, or back in the pool, joins level with the block's lowest tally. It neither floods in nor waits.
- A show held back by the 24-hour or restart rule is brought level when it's passed over, so it comes back to its share without a burst.
- **Soft rules**, relaxed in this order only when nothing else is left:
1. Not the show that just played.
2. Not a file aired within 24 hours. This is a minimum, and the stronger rules still apply.
3. Not a series starting its run from the top again within 3 days of last doing so.
- **Clash avoidance** with other channels is checked first, as before.
- **Shuffled or sequential is untouched.** The tier decides how often a show is chosen; the show's own cursor decides which episode plays, exactly as before.
- In-order shows such as Gavin & Stacey continue from their saved place.
- Shuffled shows play through their fixed deck from their saved place before it comes round again. Three's real pool has none today; Family Guy, The Simpsons and South Park are shuffled on Riot, which isn't changed.
- No cursor is reset and no deck is reshuffled.
- **Saved across restarts.** The tallies and run starts are saved in the plan file's cursor ("tallies" and "runs"). Older files without them load as before. Values must be finite and not negative, or the file counts as damaged and the last good copy is used.
## Checks before install
- **392 unit tests pass**, including the hand-run replays on copies of the box's files. Lint has no errors.
- **13 new tests in WeightedRotationTest:**
- Airtime follows the tiers 3 : 2 : 1 whatever the episode counts, including against a 457-episode surprise.
- An hour-long show gets the same minutes as a half-hour one in the same tier.
- A long series can't hold short ones hostage. Shows at the end of their runs carry straight on, and nobody waits more than 4 days.
- A short series doesn't restart within 3 days, and comes back without a burst.
- A long core series carries straight into its next run.
- In-order shows stay in order, and shuffled shows play their fixed deck.
- A top-up carries on exactly as one long plan would (in order and shuffled).
- The same show never plays twice running, and no file airs again within 24 hours.
- A show joining later takes its share without flooding the block.
- Blocks and events are kept.
- A save and reload between every top-up over four weeks changes nothing. Committed programmes stay, there are no gaps, and order and decks are kept.
- Only Orbit Three is weighted, and Family Guy is out of its pool.
- **Four-week replay on Three's real pool** (docs/replays/weighted-rotation-three-replay-2026-11-04.txt). Both rules top up every six hours from the box's committed plan, which ends on 10 November. The 28 days of new bookings after it compare as follows.
| | Before (0.96.0) | After (0.97.0) |
|---|---|---|
| Core share of airtime | 41.0% | 51.3% |
| Supporting share | 46.2% | 37.5% |
| Surprise share | 12.7% | 11.2% |
| Evening 18:00 to 22:00, core | 0% | 39% |
| Gavin & Stacey, Mighty Boosh, Spaced, Phoenix Nights | 0 airings each | 53, 53, 26, 26 |
| Longest wait for any show | 28 days (never aired) | 4.1 days (Being Human) |
| Same file again within 24 hours | 16 | 0 |
| Same show twice running | 19 | 0 |
| Runs restarted within 3 days | 8 | 0 |
| Three-hour stretches over half one show | 115 | 0 |
| Two Pints of Lager | 10.1% | 5.6% |
| In-order shows stepping back; gaps or overlaps; outside its block | 0; 0; 0 | 0; 0; 0 |
- **Scottish Comedy Night:** all 48 programmes on Friday and Saturday 21:00 to midnight are Scottish shows and keep the three.scottish presentation. The dayparts are unchanged.
- **Family Guy** has 0 evening airings on Three after the change.
- **A save and reload every 18 hours** across the four weeks gives the identical schedule.
- **Committed plans and other channels** (docs/replays/replay-fingerprints-0.97.0.txt): the same four-week replay of all 30 channels was run on 0.96.0 and on 0.97.0.
- Every committed fingerprint is identical, and every committed programme came through exactly.
- Every channel except 103 has an identical four-week fingerprint.
- 103 differs, as intended.
- The two-week presentation replay is also unchanged (83 transitions, committedKeptExactly=true).
## Known limits
- Three's committed plan runs to 10 November. The new rule books from there, so the change shows on air from about 10 November, as the plan rolls forward.
- One change from the approved prototype: the run rest counts from when a series last started its run, not from when it ended. With rest from the end, every short core show (Spaced is 14 episodes) sat out 3 days after each run, which cut its share and caused long waits. Counted from the start, a series that takes more than 3 days to play through carries straight on, and a six-parter still can't restart more than once every 3 days.
- The replays use copies of the box's files from 3 November and don't include other channels' clash avoidance. On the box it applies as before.
- This is tested as scheduling logic only. What actually airs from 10 November needs checking on the box.
## Rollback
Install 0.96.0. The extra cursor fields are ignored by 0.96.0's reader, which reads only the fields it knows, so plans saved by 0.97.0 still load.
@@ -0,0 +1,71 @@
# Four-week replay fingerprints, 0.96.0 (HEAD 3b045b6) against 0.97.0
## 0.96.0
101 committed=840c3b65fd909abf kept=true fourWeeks=e094e45ac7f3f489 programmes=2129
102 committed=7ed018e151da9e1b kept=true fourWeeks=d4608c190a1df463 programmes=1282
103 committed=b9a32f1cd8b8c6ca kept=true fourWeeks=8accafbef89e45fa programmes=1780
104 committed=fa96701157492ea5 kept=true fourWeeks=5cb590ff849c62a1 programmes=1706
105 committed=ede4d27708287a02 kept=true fourWeeks=9e42e2a1a520b9e1 programmes=2438
106 committed=c6e05fe7b6b8119e kept=true fourWeeks=26f095b2150baf74 programmes=1158
107 committed=5f64ad62f2ba89e5 kept=true fourWeeks=6a0675caf3561133 programmes=947
201 committed=dc8869b8ce635e9a kept=true fourWeeks=fb9add3f61acfeba programmes=945
202 committed=156aae666e58cfe4 kept=true fourWeeks=4226e4c5a3d51e7f programmes=1179
203 committed=8e067822f46cafca kept=true fourWeeks=81ebfc4281670881 programmes=1075
204 committed=6ca233f2ac9cf4a1 kept=true fourWeeks=4400eee18348f845 programmes=1179
301 committed=a366040ccc54b12f kept=true fourWeeks=12c5b036edae175e programmes=356
302 committed=137c4a9234258f80 kept=true fourWeeks=391a4456ada2683e programmes=440
303 committed=b6c2d88f2604a452 kept=true fourWeeks=366e574763b92fb8 programmes=416
304 committed=7241ac7470f6abf8 kept=true fourWeeks=94c07a1904e72658 programmes=491
305 committed=6188e9c6e014c2a0 kept=true fourWeeks=7a86ddd82fe02edb programmes=466
306 committed=3ee1d14f9d6cfe1e kept=true fourWeeks=a5ee7035b6febc2d programmes=483
307 committed=4f7338c2b013e02f kept=true fourWeeks=4248b99368962d00 programmes=433
308 committed=0eeae8fbb0089be5 kept=true fourWeeks=737bc88204988895 programmes=507
309 committed=b2c3d6abe1c22853 kept=true fourWeeks=ec915b9db5a309f3 programmes=490
401 committed=688529b06ec10271 kept=true fourWeeks=ad70bbedc533af1f programmes=872
601 committed=b36f48539d13de10 kept=true fourWeeks=f50d223e2b0e6ad2 programmes=2130
602 committed=29d1438c5b40b144 kept=true fourWeeks=7b0950692ef18715 programmes=2275
603 committed=f3c481ac51c14d44 kept=true fourWeeks=2c7db9fbcabef784 programmes=2274
604 committed=b2fb73b2b766be7a kept=true fourWeeks=995461f802aa9956 programmes=2899
605 committed=603c75c5d4f6ad50 kept=true fourWeeks=19a0d54636140448 programmes=4494
611 committed=77a3d29c095f8ad1 kept=true fourWeeks=b12d8cd3f51eaa74 programmes=2990
612 committed=bd4147ddf93b22ea kept=true fourWeeks=c5c0658fd688013f programmes=568
613 committed=cd6dfd1e4f97948d kept=true fourWeeks=429d10fa9694af8b programmes=514
614 committed=10ab3c9c03ae82fa kept=true fourWeeks=5ff09b5be9295129 programmes=3671
## 0.97.0
101 committed=840c3b65fd909abf kept=true fourWeeks=e094e45ac7f3f489 programmes=2129
102 committed=7ed018e151da9e1b kept=true fourWeeks=d4608c190a1df463 programmes=1282
103 committed=b9a32f1cd8b8c6ca kept=true fourWeeks=f63c4d1c5cdff21b programmes=1772
104 committed=fa96701157492ea5 kept=true fourWeeks=5cb590ff849c62a1 programmes=1706
105 committed=ede4d27708287a02 kept=true fourWeeks=9e42e2a1a520b9e1 programmes=2438
106 committed=c6e05fe7b6b8119e kept=true fourWeeks=26f095b2150baf74 programmes=1158
107 committed=5f64ad62f2ba89e5 kept=true fourWeeks=6a0675caf3561133 programmes=947
201 committed=dc8869b8ce635e9a kept=true fourWeeks=fb9add3f61acfeba programmes=945
202 committed=156aae666e58cfe4 kept=true fourWeeks=4226e4c5a3d51e7f programmes=1179
203 committed=8e067822f46cafca kept=true fourWeeks=81ebfc4281670881 programmes=1075
204 committed=6ca233f2ac9cf4a1 kept=true fourWeeks=4400eee18348f845 programmes=1179
301 committed=a366040ccc54b12f kept=true fourWeeks=12c5b036edae175e programmes=356
302 committed=137c4a9234258f80 kept=true fourWeeks=391a4456ada2683e programmes=440
303 committed=b6c2d88f2604a452 kept=true fourWeeks=366e574763b92fb8 programmes=416
304 committed=7241ac7470f6abf8 kept=true fourWeeks=94c07a1904e72658 programmes=491
305 committed=6188e9c6e014c2a0 kept=true fourWeeks=7a86ddd82fe02edb programmes=466
306 committed=3ee1d14f9d6cfe1e kept=true fourWeeks=a5ee7035b6febc2d programmes=483
307 committed=4f7338c2b013e02f kept=true fourWeeks=4248b99368962d00 programmes=433
308 committed=0eeae8fbb0089be5 kept=true fourWeeks=737bc88204988895 programmes=507
309 committed=b2c3d6abe1c22853 kept=true fourWeeks=ec915b9db5a309f3 programmes=490
401 committed=688529b06ec10271 kept=true fourWeeks=ad70bbedc533af1f programmes=872
601 committed=b36f48539d13de10 kept=true fourWeeks=f50d223e2b0e6ad2 programmes=2130
602 committed=29d1438c5b40b144 kept=true fourWeeks=7b0950692ef18715 programmes=2275
603 committed=f3c481ac51c14d44 kept=true fourWeeks=2c7db9fbcabef784 programmes=2274
604 committed=b2fb73b2b766be7a kept=true fourWeeks=995461f802aa9956 programmes=2899
605 committed=603c75c5d4f6ad50 kept=true fourWeeks=19a0d54636140448 programmes=4494
611 committed=77a3d29c095f8ad1 kept=true fourWeeks=b12d8cd3f51eaa74 programmes=2990
612 committed=bd4147ddf93b22ea kept=true fourWeeks=c5c0658fd688013f programmes=568
613 committed=cd6dfd1e4f97948d kept=true fourWeeks=429d10fa9694af8b programmes=514
614 committed=10ab3c9c03ae82fa kept=true fourWeeks=5ff09b5be9295129 programmes=3671
## Differences
3c3
< 103 committed=b9a32f1cd8b8c6ca kept=true fourWeeks=8accafbef89e45fa programmes=1780
---
> 103 committed=b9a32f1cd8b8c6ca kept=true fourWeeks=f63c4d1c5cdff21b programmes=1772
@@ -0,0 +1,38 @@
Orbit Three: four weeks of new bookings after the committed plan (which ends 2026-11-10T11:34:05.903),
both rules topping up every six hours from the box's real committed plan and pool. Committed programmes are identical in both.
== Before: equal turns, finish together, Family Guy in the evening (1423 programmes, 672 hours)
core: 41.0% of airtime
supporting: 46.2% of airtime
surprise: 12.7% of airtime
block 18-22: core 0%, supporting 100%, surprise 0%; top: Being Human 28%, Green Wing 14%, Peep Show 12%, Family Guy 11%
block 2-6: core 92%, supporting 8%, surprise 0%; top: Two Pints of Lager and a Packet of Crisps 37%, Still Game 23%, The Inbetweeners 19%, Limmy's Show! 9%
block 22-2: core 10%, supporting 0%, surprise 90%; top: Inside No. 9 23%, Bo' Selecta! 10%, Little Britain 10%, The League of Gentlemen 9%
block 6-18: core 44%, supporting 56%, surprise 0%; top: Still Game 10%, Rab C. Nesbitt 9%, Two Pints of Lager and a Packet of Crisps 8%, Cuckoo 8%
event 21-0: core 75%, supporting 25%, surprise 0%; top: Still Game 27%, Scot Squad 21%, Rab C. Nesbitt 21%, Chewin' the Fat 14%
the four: Gavin & Stacey 0 airings (0 in the evening), The Mighty Boosh 0 airings (0 in the evening), Spaced 0 airings (0 in the evening), Phoenix Nights 0 airings (0 in the evening)
longest waits: Gavin & Stacey 28.0 d, The Mighty Boosh 28.0 d, Spaced 28.0 d, Phoenix Nights 28.0 d, Fresh Meat 25.6 d, Snuff Box 19.4 d
never aired: Gavin & Stacey, The Mighty Boosh, Spaced, Phoenix Nights
same file within 24 h: 16; same show twice running: 19; in-order shows stepping back: 0; gaps or overlaps: 0; outside its block: 0
runs restarted within 3 days: {The Inbetweeners=3, Limmy's Show!=3, Garth Marenghi's Darkplace=2}; three-hour stretches over half one show: 115
by title: Two Pints of Lager and a Packet of Crisps 10.1% [cor], Still Game 9.6% [cor], The Inbetweeners 5.6% [cor], Rab C. Nesbitt 5.4% [cor], Limmy's Show! 5.0% [cor], Being Human 4.5% [sup], Cuckoo 4.1% [sup], Coupling 4.0% [sup], Scot Squad 3.6% [sup], People Just Do Nothing 3.4% [sup], Inside No. 9 3.3% [sur], Black Books 2.9% [sup], Bad Education 2.8% [sup], Man Like Mobeen 2.6% [sup], Chewin' the Fat 2.5% [cor], Green Wing 2.2% [sup], Peep Show 2.0% [sup], Uncle 1.9% [sup], Him & Her 1.7% [sup], Family Guy 1.7% [sup], Lunch Monkeys 1.7% [sup], Burnistoun 1.4% [cor], Gary: Tank Commander 1.4% [sup], Bo' Selecta! 1.4% [sur], The IT Crowd 1.4% [sup], Little Britain 1.4% [cor], The League of Gentlemen 1.3% [sur], Monkey Dust 1.3% [sur], Garth Marenghi's Darkplace 1.3% [sur], This Country 1.2% [sup], Toast of London 1.0% [sup], Psychoville 0.9% [sur], The Office (UK) 0.9% [sup], Extras 0.9% [sup], Stressed Eric 0.9% [sur], Nighty Night 0.9% [sur], The Day Today 0.4% [sur], Snuff Box 0.4% [sur], Nathan Barley 0.4% [sur], Brass Eye 0.4% [sur], Fresh Meat 0.3% [sup]
== After: weighted 3 / 2 / 1, Family Guy out of the evening (1453 programmes, 672 hours)
core: 51.3% of airtime
supporting: 37.5% of airtime
surprise: 11.2% of airtime
block 18-22: core 39%, supporting 61%, surprise 0%; top: Spaced 10%, Phoenix Nights 10%, Gavin & Stacey 10%, The Mighty Boosh 10%
block 2-6: core 91%, supporting 9%, surprise 0%; top: Limmy's Show! 13%, Burnistoun 13%, Gavin & Stacey 13%, The Inbetweeners 13%
block 22-2: core 20%, supporting 0%, surprise 80%; top: Little Britain 20%, Snuff Box 7%, Garth Marenghi's Darkplace 7%, Inside No. 9 7%
block 6-18: core 49%, supporting 51%, surprise 0%; top: Still Game 7%, Chewin' the Fat 7%, Burnistoun 7%, The Inbetweeners 7%
event 21-0: core 79%, supporting 21%, surprise 0%; top: Still Game 17%, Chewin' the Fat 17%, Burnistoun 17%, Rab C. Nesbitt 15%
the four: Gavin & Stacey 53 airings (22 in the evening), The Mighty Boosh 53 airings (22 in the evening), Spaced 26 airings (26 in the evening), Phoenix Nights 26 airings (26 in the evening)
longest waits: Being Human 4.1 d, Green Wing 3.9 d, The League of Gentlemen 3.1 d, Bo' Selecta! 3.0 d, Inside No. 9 3.0 d, The Day Today 3.0 d
never aired: none
same file within 24 h: 0; same show twice running: 0; in-order shows stepping back: 0; gaps or overlaps: 0; outside its block: 0
runs restarted within 3 days: {none=0}; three-hour stretches over half one show: 0
by title: Burnistoun 6.2% [cor], Still Game 6.2% [cor], Limmy's Show! 6.2% [cor], The Inbetweeners 5.6% [cor], Two Pints of Lager and a Packet of Crisps 5.6% [cor], Chewin' the Fat 4.1% [cor], Rab C. Nesbitt 4.0% [cor], Black Books 3.8% [sup], Gavin & Stacey 3.7% [cor], The Mighty Boosh 3.7% [cor], Little Britain 2.8% [cor], Scot Squad 2.7% [sup], Gary: Tank Commander 2.7% [sup], Bad Education 2.4% [sup], Lunch Monkeys 2.4% [sup], Uncle 2.4% [sup], People Just Do Nothing 2.4% [sup], Man Like Mobeen 2.4% [sup], Cuckoo 2.3% [sup], Coupling 2.3% [sup], Him & Her 2.3% [sup], Spaced 1.6% [cor], Phoenix Nights 1.6% [cor], Being Human 1.1% [sup], The Office (UK) 1.1% [sup], Fresh Meat 1.1% [sup], Extras 1.1% [sup], The IT Crowd 1.0% [sup], Peep Show 1.0% [sup], Toast of London 1.0% [sup], This Country 1.0% [sup], Green Wing 1.0% [sup], Snuff Box 1.0% [sur], Garth Marenghi's Darkplace 1.0% [sur], Inside No. 9 0.9% [sur], Psychoville 0.9% [sur], The League of Gentlemen 0.9% [sur], Nathan Barley 0.9% [sur], Brass Eye 0.9% [sur], The Day Today 0.9% [sur], Nighty Night 0.9% [sur], Monkey Dust 0.9% [sur], Stressed Eric 0.9% [sur], Bo' Selecta! 0.9% [sur]
Scottish Comedy Night: 48 programmes, all presented as three.scottish: true
Family Guy in the evening after: 0 airings
A save and reload every 18 hours gives the identical four weeks: true