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
@@ -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()) {