0.99.7: clash avoidance keeps compact airings per plan (re-read only when a plan changes), weighted planning remembers each next episode, pool diagnostics for unmatched list entries
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m45s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m37s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 09:55:09 +00:00
co-authored by Claude Opus 5.5
parent 623fb5a4e7
commit 18ec926eb4
9 changed files with 140 additions and 17 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 136
versionName = "0.99.6-after-dark-review"
versionCode = 137
versionName = "0.99.7-planning-speed"
}
buildFeatures { compose = true }
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
@@ -308,9 +308,14 @@ internal fun nextInTurn(pool: List<PoolSeries>, last: String?, eligible: (PoolSe
internal typealias ProgrammeClash = (show: PoolSeries, startMs: Long, endMs: Long) -> Boolean
/** The same show may run on several channels, just not at the same moment. Compares by title, so two copies of a show still count. */
internal fun clashesWith(plans: List<ChannelPlan>): ProgrammeClash {
val airings = plans.flatMap { it.entries }.groupBy { seriesKey(it.media.item.title.substringBefore(" / ")) }
return { show, startMs, endMs -> airings[seriesKey(show.title)].orEmpty().any { it.startMs < endMs && startMs < it.endMs } }
internal fun clashesWith(plans: List<ChannelPlan>): ProgrammeClash = clashesWithAirings(plans.flatMap(::airingsOf))
/** What a plan puts on air, as much as clash avoidance needs: each programme's title key and its times. */
internal data class Airing(val key: String, val startMs: Long, val endMs: Long)
internal fun airingsOf(plan: ChannelPlan) = plan.entries.map { Airing(seriesKey(it.media.item.title.substringBefore(" / ")), it.startMs, it.endMs) }
internal fun clashesWithAirings(airings: List<Airing>): ProgrammeClash {
val byKey = airings.groupBy { it.key }
return { show, startMs, endMs -> byKey[seriesKey(show.title)].orEmpty().any { it.startMs < endMs && startMs < it.endMs } }
}
/**
@@ -451,10 +456,11 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
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]
// Each show's next episode, worked out once and kept until that show plays: finding it means searching its episode list.
val next = HashMap<String, PoolEpisode>()
fun following(show: PoolSeries): PoolEpisode = next.getOrPut(show.id) {
if (!isMixed(show)) nextEpisode(show, marks[show.id])
else running(show).let { mix -> 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?> {
@@ -493,6 +499,7 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
val weight = part?.takeIf { series in available }?.weights?.get(seriesKey(series.title)) ?: weightOf(series)
tally[series.id] = tally[series.id]!! + episode.durationMs / 60_000.0 / weight
marks[series.id] = episode.mark
next.remove(series.id)
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
@@ -78,6 +78,17 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
* Brings a channel's plan up to seven days ahead, reading the provider only if the cached pool is missing or old.
* A failed refresh keeps what's there, so a provider outage can't disturb what's committed.
*/
/**
* What each other channel has on air, for clash avoidance, kept with its plan file's stamp, so a scheduling pass doesn't
* parse every plan again for each channel. Only titles and times are kept, not whole plans.
*/
private val otherAirings = HashMap<Pair<String, Int>, Pair<Pair<Long, Long>, List<Airing>>>()
private fun airingsOn(userId: String, number: Int): List<Airing> = synchronized(otherAirings) {
val stamp = store.planStamp(number)
otherAirings[userId to number]?.takeIf { it.first == stamp }?.second
?: store.loadPlan(userId, number)?.let(::airingsOf).orEmpty().also { otherAirings[userId to number] = stamp to it }
}
fun topUp(session: EmbySampleSession, userId: String, programming: ChannelProgramming, loop: SampleChannel, checkActive: () -> Unit = {}): SchedulerReport {
SeriesInspection.take()?.let { title -> runCatching { session.inspectSeries(title) }.getOrElse { listOf("inspect failed: ${it.javaClass.simpleName} ${(it as? EmbyCheckException)?.httpStatus} ${it.message?.take(160)}") }.forEach { Log.i("OrbitSchedule", it) } }
val number = programming.number
@@ -107,8 +118,13 @@ 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()
// 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) }) }
// Other channels' plans are only read if this one is actually about to grow, and a plan read before is reused until its file changes.
var othersMs = 0L
val others by lazy {
val began = android.os.SystemClock.elapsedRealtime()
clashesWithAirings((SmartChannels.map { it.number }.filter { it != number } + DRIVE_IN_NUMBER).flatMap { airingsOn(userId, it) })
.also { othersMs = android.os.SystemClock.elapsedRealtime() - began }
}
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,
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
@@ -121,7 +137,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
requests, fetchMs, planMs, store.sizes(number).values.sum(), requests == 0, plan.endMs,
added.size, added.count { "deferred" in it.why }, added.count { "fallback" in it.why },
if (added.isEmpty()) 0 else added.count { others(PoolSeries(it.seriesId, it.media.item.title.substringBefore(" / "), emptyList()), it.startMs, it.endMs) })
Log.i("OrbitSchedule", report.logLine(number))
Log.i("OrbitSchedule", report.logLine(number) + if (othersMs > 0) " othersMs=$othersMs" else "")
return report
}
}
@@ -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.99.6\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.7\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -241,19 +241,23 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
android.util.Log.i("OrbitSchedule", "channel=${programming.number} series=\"$title\" copies=${match.size} episodes=${best?.episodes?.size ?: 0}")
if (best != null) pool += best
}
} else for (search in programming.searches) {
} else for ((index, search) in programming.searches.withIndex()) {
if (pool.size == programming.seriesCount) break
checkActive()
requests++
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
val exact = candidates.count { seriesKey(it.title) == seriesKey(search) }
val match = bestSeriesMatch(search, if (programming.exactTitles) candidates.filter { seriesKey(it.title) == seriesKey(search) } else candidates)
// Counts only, never titles: which list entry found nothing, and at which step, so a missing show can be traced.
if (match == null) { android.util.Log.i("OrbitSchedule", "channel=${programming.number} listed=${index + 1} unmatched candidates=${candidates.size} exact=$exact"); continue }
// A second copy of a show in the library counts as the same show.
if (pool.any { it.id == match.id || seriesKey(it.title) == seriesKey(match.title) }) continue
// A library can hold several copies of one show, one with a single episode and another with the whole run.
// The copy with the most episodes this box can play is the one the channel uses.
val copies = (listOf(match) + candidates.filter { it.id != match.id && seriesKey(it.title) == seriesKey(match.title) }.sortedBy { it.year ?: Int.MAX_VALUE }).take(MAX_SERIES_COPIES)
val read = copies.map { copy -> readWholeSeries(transport, userId, ::currentToken, copy, checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) }
val best = read.maxByOrNull { it.episodes.size }?.takeIf { it.episodes.isNotEmpty() } ?: continue
val best = read.maxByOrNull { it.episodes.size }?.takeIf { it.episodes.isNotEmpty() }
if (best == null) { android.util.Log.i("OrbitSchedule", "channel=${programming.number} listed=${index + 1} matched copies=${copies.size} playableEpisodes=0"); continue }
if (copies.size > 1) android.util.Log.i("OrbitSchedule", "channel=${programming.number} copies=${copies.size} usedCopy=${read.indexOf(best) + 1} episodes=${read.map { it.episodes.size }}")
pool += best
}
@@ -102,6 +102,8 @@ internal class ScheduleStore(private val directory: File) {
.put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation) }) }
write(file("schedule", number), root(userId, number).put("tail", encodeCursor(plan.tail)).put("entries", entries))
}
/** Changes whenever the plan file is written, so a plan already read can be reused until then. */
fun planStamp(number: Int): Pair<Long, Long> = file("schedule", number).let { it.lastModified() to it.length() }
fun loadPlan(userId: String, number: Int): ChannelPlan? = read(file("schedule", number), userId, number) { root ->
val rows = root.getJSONArray("entries")
val entries = (0 until rows.length()).map { index ->
@@ -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.99.6")
next.setRequestProperty("User-Agent", "OrbitTV/0.99.7")
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()) {
+29
View File
@@ -0,0 +1,29 @@
# Orbit TV 0.99.7: faster top-ups and pool diagnostics
This release prepares for the final audit (4 November 2026). It changes no scheduling decision; the same programmes are booked. It includes 0.99.6.
## What's in it
- **Clash avoidance reads less.**
- **Before:** each time a channel tops up, it parsed every other channel's whole plan file to avoid clashes, about 30 files and several megabytes on the box. A full scheduling pass did that once per growing channel.
- **Now:** the scheduler keeps just what clash avoidance needs from each plan (title key, start and end, as `Airing` and `clashesWithAirings`). It keeps them together with the plan file's modified time and size, and reads a file again only when it has changed.
- The log line gains `othersMs=` when it builds this index, so its cost on the box can be seen.
- **Weighted planning looks each show's next episode up once.** `extendWeighted` worked out every eligible show's next episode several times per pick, by searching its episode list. It now keeps the answer until that show plays.
- **Pool diagnostics, counts only, never titles.** When a listed series isn't added to a pool, the log names its position in the list and the reason:
- `listed=N unmatched candidates=C exact=E`: the server's search found no exact title.
- `listed=N matched copies=C playableEpisodes=0`: it was found, but none of its episodes can play on the box.
This is how Vortex's Tenchi Muyo! Tenchi Universe will be traced at its next refresh. The library holds it (1995, TV-PG); the pool reader drops it, for a reason not yet known.
## Checks before install
- **415 unit tests pass**, including the hand-run replays. Lint has no errors.
- **The same programmes are booked:** a four-week replay of all 30 channels on box copies taken at 09:40 gives exactly the same fingerprint as 0.99.6 on every channel (docs/replays/replay-fingerprints-0.99.7.txt).
- **Where the time went, measured on box copies on this machine:**
- A weighted top-up of Orbit X takes about 0.2 seconds of planning.
- Reading the 30 other plans takes about 0.07 seconds.
- The box took 41 seconds, so most of that time is most likely its slower JSON parsing and the pools refreshing alongside. That isn't proven. `othersMs=` will show the split on the box.
## Rollback
Install 0.99.6. No saved data changes.
@@ -0,0 +1,65 @@
# Four-week replay fingerprints, 0.99.6 against 0.99.7, from box copies taken 4 November 09:40
## 0.99.6
101 committed=d6b776321a893917 kept=true fourWeeks=fd73cd1bfd91253f programmes=2186
102 committed=af055f4884bd0782 kept=true fourWeeks=8fc1249489a0aee7 programmes=1331
103 committed=22917d8e8630459b kept=true fourWeeks=f33f53a3921c66ab programmes=1849
104 committed=aefdd56242124676 kept=true fourWeeks=77f6a7e3bc0ba69c programmes=1752
105 committed=3853c5f2cb672d1c kept=true fourWeeks=b7932d9c4a49c444 programmes=2510
106 committed=c6e05fe7b6b8119e kept=true fourWeeks=a4207fcc179d9c1a programmes=1159
107 committed=c72c969596622017 kept=true fourWeeks=3b821bdbd71a5bf6 programmes=988
201 committed=3b19e3bc730bf848 kept=true fourWeeks=7e1cdb97b7a40718 programmes=959
202 committed=ef8312b2b343d76d kept=true fourWeeks=40e714264d4cfd8a programmes=1106
203 committed=99f6b4220cff3cbc kept=true fourWeeks=7c9092d57552f039 programmes=1147
204 committed=2199aacf4d8d6efd kept=true fourWeeks=f07cfe0fceb0010b programmes=1261
301 committed=cb9c3dfeebdfd3ce kept=true fourWeeks=1138042adf912319 programmes=355
302 committed=0e47ac761e574662 kept=true fourWeeks=eb7ce80d8c0ccb56 programmes=434
303 committed=e0583a7eb1a82100 kept=true fourWeeks=2e109220600f6caa programmes=422
304 committed=8ef6c0747b62685e kept=true fourWeeks=2df18531c5755e87 programmes=484
305 committed=7b6961ce80e3719d kept=true fourWeeks=7320d069f382e568 programmes=495
306 committed=ddb284481edcdf5f kept=true fourWeeks=390e53c5f2aa3e0d programmes=494
307 committed=95087afee891c9ff kept=true fourWeeks=7c267a8cdbf693fa programmes=443
308 committed=caa2613998d76d0d kept=true fourWeeks=5a68309f856b533d programmes=503
309 committed=c9d3865ba25f4ebc kept=true fourWeeks=c94e22dd641452b3 programmes=501
401 committed=ca73a73d5cb28be7 kept=true fourWeeks=64706a885c16e095 programmes=890
601 committed=4fc397af44c55469 kept=true fourWeeks=f39f6fc286c41d73 programmes=2188
602 committed=296a943c2f25b865 kept=true fourWeeks=ddad3077b4b9142d programmes=2352
603 committed=bbd5b6464b52db34 kept=true fourWeeks=d79896b87e9db503 programmes=2314
604 committed=fbee086ffc8bd0ff kept=true fourWeeks=bef6da686ac27b00 programmes=3158
605 committed=6cda6ee486656aee kept=true fourWeeks=0e4443f10ddac85c programmes=4428
611 committed=ba7b5eae9ef67a7e kept=true fourWeeks=42fa58d46861c9e1 programmes=3031
612 committed=21dc64eb844a9767 kept=true fourWeeks=08b5cba3b889649e programmes=577
613 committed=bbcae35720001cff kept=true fourWeeks=1ac6222e88e010dc programmes=525
614 committed=a1a4ce9889ff6ead kept=true fourWeeks=9c20998165b2c635 programmes=3787
## 0.99.7
101 committed=d6b776321a893917 kept=true fourWeeks=fd73cd1bfd91253f programmes=2186
102 committed=af055f4884bd0782 kept=true fourWeeks=8fc1249489a0aee7 programmes=1331
103 committed=22917d8e8630459b kept=true fourWeeks=f33f53a3921c66ab programmes=1849
104 committed=aefdd56242124676 kept=true fourWeeks=77f6a7e3bc0ba69c programmes=1752
105 committed=3853c5f2cb672d1c kept=true fourWeeks=b7932d9c4a49c444 programmes=2510
106 committed=c6e05fe7b6b8119e kept=true fourWeeks=a4207fcc179d9c1a programmes=1159
107 committed=c72c969596622017 kept=true fourWeeks=3b821bdbd71a5bf6 programmes=988
201 committed=3b19e3bc730bf848 kept=true fourWeeks=7e1cdb97b7a40718 programmes=959
202 committed=ef8312b2b343d76d kept=true fourWeeks=40e714264d4cfd8a programmes=1106
203 committed=99f6b4220cff3cbc kept=true fourWeeks=7c9092d57552f039 programmes=1147
204 committed=2199aacf4d8d6efd kept=true fourWeeks=f07cfe0fceb0010b programmes=1261
301 committed=cb9c3dfeebdfd3ce kept=true fourWeeks=1138042adf912319 programmes=355
302 committed=0e47ac761e574662 kept=true fourWeeks=eb7ce80d8c0ccb56 programmes=434
303 committed=e0583a7eb1a82100 kept=true fourWeeks=2e109220600f6caa programmes=422
304 committed=8ef6c0747b62685e kept=true fourWeeks=2df18531c5755e87 programmes=484
305 committed=7b6961ce80e3719d kept=true fourWeeks=7320d069f382e568 programmes=495
306 committed=ddb284481edcdf5f kept=true fourWeeks=390e53c5f2aa3e0d programmes=494
307 committed=95087afee891c9ff kept=true fourWeeks=7c267a8cdbf693fa programmes=443
308 committed=caa2613998d76d0d kept=true fourWeeks=5a68309f856b533d programmes=503
309 committed=c9d3865ba25f4ebc kept=true fourWeeks=c94e22dd641452b3 programmes=501
401 committed=ca73a73d5cb28be7 kept=true fourWeeks=64706a885c16e095 programmes=890
601 committed=4fc397af44c55469 kept=true fourWeeks=f39f6fc286c41d73 programmes=2188
602 committed=296a943c2f25b865 kept=true fourWeeks=ddad3077b4b9142d programmes=2352
603 committed=bbd5b6464b52db34 kept=true fourWeeks=d79896b87e9db503 programmes=2314
604 committed=fbee086ffc8bd0ff kept=true fourWeeks=bef6da686ac27b00 programmes=3158
605 committed=6cda6ee486656aee kept=true fourWeeks=0e4443f10ddac85c programmes=4428
611 committed=ba7b5eae9ef67a7e kept=true fourWeeks=42fa58d46861c9e1 programmes=3031
612 committed=21dc64eb844a9767 kept=true fourWeeks=08b5cba3b889649e programmes=577
613 committed=bbcae35720001cff kept=true fourWeeks=1ac6222e88e010dc programmes=525
614 committed=a1a4ce9889ff6ead kept=true fourWeeks=9c20998165b2c635 programmes=3787