0.99.3: adaptive film rest for After Dark and Premiere (events keep 7 days)
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m57s
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 01:23:15 +00:00
co-authored by Claude Opus 5.5
parent 1a8e2647ab
commit 047fb50532
10 changed files with 219 additions and 29 deletions
@@ -43,7 +43,9 @@ internal data class ChannelProgramming(val number: Int, val name: String, val se
* 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) {
val tierWeights: Map<String, Double>? = null,
/** A film channel's everyday blocks rest each film for a share of how long their own films take to play through ([adaptiveRestMs]). */
val adaptiveFilmRest: Boolean = false) {
/** 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. */
@@ -76,7 +78,7 @@ private val AfterDarkFilms = listOf("The Thing (1982)", "The Evil Dead (1983)",
"Army of Darkness", "House (1977)", "The Holy Mountain", "Repo! The Genetic Opera")
internal val SmartChannels = listOf(
ChannelProgramming(AFTER_DARK_NUMBER, "After Dark", AfterDarkFilms, seriesCount = AfterDarkFilms.size, filmSeries = listOf(LAST_DRIVE_IN), filmRestMs = 7 * 24 * 60 * 60_000L,
ChannelProgramming(AFTER_DARK_NUMBER, "After Dark", AfterDarkFilms, seriesCount = AfterDarkFilms.size, filmSeries = listOf(LAST_DRIVE_IN), filmRestMs = 7 * 24 * 60 * 60_000L, adaptiveFilmRest = true,
dayParts = AfterDarkEvents + listOf(DayPart(21, 5), DayPart(5, 21, listOf("The 'Burbs", "'Til Death Do Us Part (2017)", "Tremors (1990)", "The Lost Boys (1987)", "Fright Night (1985)", "Poltergeist (1982)", "Scream (1996)",
"Escape from New York", "They Live", "Repo Man", "Donnie Darko", "From Dusk Till Dawn", "Creepshow", "Near Dark", "Halloween (1978)", "The Fog (1980)", "Blue Velvet",
"The Wicker Man (1973)", "An American Werewolf in London", "Prince of Darkness"), group = "day")),
@@ -101,7 +103,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(), tierWeights = SmartChannelTiers[it.number]) }
channelFilms = if (it.number == 401) PpvSunday else emptyList(), tierWeights = SmartChannelTiers[it.number], adaptiveFilmRest = it.number in AdaptiveFilmRestChannels) }
/** Film channels whose rest adapts to their pools: Premiere, whose pool runs well past a week (After Dark is set above). Proposed 4 November 2026. */
private val AdaptiveFilmRestChannels get() = setOf(301)
/** Editorially weighted rotation, per channel, once its tiers are approved: Orbit Three (0.97.0), then Odyssey, Wild, Orbit X and ToonZ (0.98.0). */
private val SmartChannelTiers: Map<Int, Map<String, Double>> get() = mapOf(103 to ThreeTiers, 202 to OdysseyTiers, 203 to WildTiers, 603 to OrbitXTiers, 605 to ToonZTiers)
@@ -265,7 +270,8 @@ internal fun chooseFilm(pool: List<PoolSeries>, shown: Map<String, Long>, startM
/** Films by their rest period, back to back from [fromMs] until [untilMs] is covered. */
internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, restMs: Long,
dayParts: List<DayPart> = emptyList(), zone: java.time.ZoneId = java.time.ZoneId.systemDefault(), avoid: ProgrammeClash = { _, _, _ -> false }): ChannelPlan {
dayParts: List<DayPart> = emptyList(), zone: java.time.ZoneId = java.time.ZoneId.systemDefault(), avoid: ProgrammeClash = { _, _, _ -> false },
adaptiveRest: Boolean = false): ChannelPlan {
val shown = cursor.filmShown.toMutableMap()
val entries = mutableListOf<ScheduleEntry>()
var last = cursor.lastSeriesId
@@ -286,7 +292,9 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
continue
}
val films = available.filter { it.isFilm }.ifEmpty { pool.filter { it.isFilm } }.ifEmpty { available }
val (film, why) = chooseFilm(films, shown, start, restMs, avoid)
// Events keep the channel's rest; everyday blocks, when adaptive, rest by how long their own films last.
val rest = if (adaptiveRest && part?.days.isNullOrEmpty()) adaptiveRestMs(films, part, restMs) else restMs
val (film, why) = chooseFilm(films, shown, start, rest, avoid)
val copy = film.episodes.first()
val item = SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs)
// Only a programme actually drawn from the event's own titles carries its presentation.
@@ -298,6 +306,25 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
return ChannelPlan(entries, ScheduleCursor(last, marks, shown))
}
/** Adaptive film rest: a small block rests films this share of its play-through time; a big one up to [ADAPTIVE_REST_LONG_SHARE], never under the channel's rest. */
internal const val ADAPTIVE_REST_SHORT_SHARE = 0.9
internal const val ADAPTIVE_REST_LONG_SHARE = 0.8
internal const val ADAPTIVE_REST_FLOOR_MS = 2 * 24 * 60 * 60_000L
internal const val ADAPTIVE_REST_CEILING_MS = 14 * 24 * 60 * 60_000L
/**
* How long a film rests in an everyday block, from how long the block's films take to play through back to back in its
* daily hours. When that's too short for the channel's own rest ([restMs]), [ADAPTIVE_REST_SHORT_SHARE] of it, so each
* pick comes from a real shortlist instead of the same longest-waiting order every cycle. When it's longer, up to
* [ADAPTIVE_REST_LONG_SHARE] of it but never less than [restMs], so a big pool airs more of itself.
*/
internal fun adaptiveRestMs(films: List<PoolSeries>, part: DayPart?, restMs: Long): Long {
val hours = part?.let { ((it.toHour - it.fromHour + 24) % 24).let { h -> if (h == 0) 24 else h } } ?: 24
val cycle = films.sumOf { it.episodes.first().durationMs }.toDouble() * 24 / hours
val rest = if (cycle * ADAPTIVE_REST_SHORT_SHARE < restMs) cycle * ADAPTIVE_REST_SHORT_SHARE else maxOf(restMs.toDouble(), cycle * ADAPTIVE_REST_LONG_SHARE)
return rest.toLong().coerceIn(ADAPTIVE_REST_FLOOR_MS, ADAPTIVE_REST_CEILING_MS)
}
/** A one-a-night event counts as having had its turn for this long after a programme from it starts. */
private const val ONCE_A_NIGHT_MS = 12 * 60 * 60_000L
/** How far ahead an on-time appointment is looked for, and how late after its hour it may start. */
@@ -438,9 +465,11 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
/** Off only in tests, to show that this rule is the one difference from planning before it existed. */
noThirdInARow: Boolean = true,
/** Off only in tests: each block keeps its own place in the rotation. */
blockRotation: Boolean = true): ChannelPlan {
blockRotation: Boolean = true,
/** Film channels only: see [ChannelProgramming.adaptiveFilmRest]. */
adaptiveRest: Boolean = false): ChannelPlan {
require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() })
if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs, dayParts, zone, avoid)
if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs, dayParts, zone, avoid, adaptiveRest)
val marks = cursor.marks.toMutableMap()
val entries = mutableListOf<ScheduleEntry>()
var last = cursor.lastSeriesId
@@ -570,7 +599,9 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
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,
/** Set for a channel with editorially weighted rotation ([ChannelProgramming.weightOf]); null keeps equal turns. */
weightOf: ((PoolSeries) -> Double)? = null): ChannelPlan? {
weightOf: ((PoolSeries) -> Double)? = null,
/** Film channels only: see [ChannelProgramming.adaptiveFilmRest]. */
adaptiveRest: Boolean = false): ChannelPlan? {
val kept = existing?.let { plan -> plan.copy(entries = plan.entries.dropWhile { it.endMs < nowMs - SCHEDULE_KEEP_PAST_MS }) }
if (kept != null && kept.endMs >= nowMs + SCHEDULE_TOP_UP_MS) return kept
if (pool.isNullOrEmpty()) return kept
@@ -579,7 +610,7 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
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 }
extendByBlock(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, weightOf, dayParts, zone, avoid, shuffle, mixed, finishTogether, recent, trailing)
} else extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow, blockRotation)
} else extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow, blockRotation, adaptiveRest)
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
}
@@ -111,7 +111,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
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,
weightOf = programming.tierWeights?.let { programming::weightOf }) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest) ?: 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.99.2\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.3\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -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.2")
next.setRequestProperty("User-Agent", "OrbitTV/0.99.3")
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()) {