0.99.9: the confirmed After Dark, Horror, Evidence, Odyssey and Terra events are appointments; block eligibility worked out once per pool
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m34s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m29s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 11:10:18 +00:00
co-authored by Claude Opus 5.5
parent 4f6ffeae2e
commit 36c0907ec3
10 changed files with 374 additions and 20 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 138
versionName = "0.99.8-after-dark-daytime"
versionCode = 139
versionName = "0.99.9-event-appointments"
}
buildFeatures { compose = true }
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
@@ -213,7 +213,7 @@ private val TerraWider = listOf("Hostile Planet", "Wild China", "Wild Russia", "
private val TerraEarlierNames = listOf("Our Planet II", "Dynasties", "Dynasties II", "Africa", "South Pacific", "Great Barrier Reef")
internal val TerraShows get() = (TerraLandmarks + TerraWider + TerraEarlierNames).distinct()
internal val TerraDayParts get() = listOf(
DayPart(20, 22, TerraLandmarks, days = setOf(DayOfWeek.SUNDAY), key = "terra.sunday"),
DayPart(20, 22, TerraLandmarks, days = setOf(DayOfWeek.SUNDAY), onTime = true, key = "terra.sunday"),
DayPart(6, 18, TerraShows), DayPart(18, 23, TerraLandmarks), DayPart(23, 6, TerraShows))
/** Wild: people meeting nature and surviving it. The presenters and participants are the story. */
@@ -250,7 +250,7 @@ private val OdysseyJourneys = listOf("Civilisation", "Civilizations", "Civilisat
private val OdysseyAwaitingHome = listOf("Band of Brothers")
internal val OdysseyShows get() = (OdysseySpace + OdysseyEngineering + OdysseyDisasters + OdysseyJourneys + OdysseyAwaitingHome).distinct()
internal val OdysseyDayParts get() = listOf(
DayPart(14, 18, OdysseyJourneys, days = Weekend),
DayPart(14, 18, OdysseyJourneys, days = Weekend, onTime = true),
// Reviewed suggestions (the "all" group) join the daytime.
DayPart(6, 18, OdysseyEngineering + OdysseySpace - setOf("Horizon", "Through the Wormhole", "The Sky at Night"), group = "all"), DayPart(18, 23, OdysseySpace), DayPart(23, 6, OdysseyDisasters))
internal val OdysseyMixed get() = setOf("The Universe", "How the Universe Works", "Horizon", "Impossible Engineering", "Engineering the Impossible", "Extreme Engineering", "Megastructures",
@@ -276,7 +276,7 @@ private val EvidenceDark = listOf("Luther", "Line of Duty", "Happy Valley", "Bro
private val EvidenceSundayMystery = listOf("Inspector Morse", "Lewis", "A Touch of Frost", "Midsomer Murders", "Vera", "Columbo", "Sherlock")
internal val EvidenceShows get() = (EvidenceProcedurals + EvidenceDetectives + EvidenceDark).distinct()
internal val EvidenceDayParts get() = listOf(
DayPart(20, 22, EvidenceSundayMystery, days = setOf(DayOfWeek.SUNDAY)),
DayPart(20, 22, EvidenceSundayMystery, days = setOf(DayOfWeek.SUNDAY), onTime = true),
DayPart(6, 18, EvidenceProcedurals + listOf("Columbo"), group = "all"), DayPart(18, 21, EvidenceDetectives), DayPart(21, 1, EvidenceDark), DayPart(1, 6, EvidenceProcedurals))
/** Serial dramas tell a story, so they stay in order. */
internal val EvidenceMixed get() = EvidenceShows.toSet() - setOf("Line of Duty", "Broadchurch", "Happy Valley", "The Wire", "Dexter", "Luther", "Sherlock")
@@ -305,14 +305,16 @@ internal val CultClassics = listOf("The Rocky Horror Picture Show", "Repo Man",
* and the last film it starts runs to its natural end. When every film in it is resting, the one that has waited longest
* plays, as on any film channel; when none of its films are in the library at all, the channel's usual block carries on.
*/
internal val HorrorDayParts get() = listOf(DayPart(20, 2, SlasherSaturday, days = setOf(DayOfWeek.SATURDAY), key = "horror.slasher"))
internal val HorrorDayParts get() = listOf(DayPart(20, 2, SlasherSaturday, days = setOf(DayOfWeek.SATURDAY), onTime = true, key = "horror.slasher"))
/**
* After Dark's Saturday staple: one whole hosted episode, in order, running its full length however long. Its window opens at 20:00
* because the film before it is usually still running: starting from the first slot after 20:00 lands it around 21:00.
* After Dark's Saturday staple: one whole hosted episode, in order, running its full length however long. An appointment at 21:00
* since 4 November 2026: the film before it is chosen to finish in time (its window opened at 20:00 before, to land around 21:00).
*/
internal const val LAST_DRIVE_IN = "The Last Drive-in with Joe Bob Briggs"
internal val AfterDarkEvents get() = listOf(DayPart(21, 1, BMovieThrowbacks, days = setOf(DayOfWeek.FRIDAY), key = "afterdark.bmovie"), DayPart(20, 1, listOf(LAST_DRIVE_IN), days = setOf(DayOfWeek.SATURDAY), key = "afterdark.drivein"),
DayPart(21, 1, CultClassics, days = setOf(DayOfWeek.SUNDAY), key = "afterdark.cult"))
// All three are appointments (4 November 2026): the films before them are chosen to finish in time, so each night starts near 21:00.
internal val AfterDarkEvents get() = listOf(DayPart(21, 1, BMovieThrowbacks, days = setOf(DayOfWeek.FRIDAY), onTime = true, key = "afterdark.bmovie"),
DayPart(21, 1, listOf(LAST_DRIVE_IN), days = setOf(DayOfWeek.SATURDAY), onTime = true, key = "afterdark.drivein"),
DayPart(21, 1, CultClassics, days = setOf(DayOfWeek.SUNDAY), onTime = true, key = "afterdark.cult"))
/** Orbit Junior: British children's TV for about 5 to 11, with the classics at breakfast. Tots is the preferred home of modern preschool. */
private val JuniorBreakfast = listOf("Thomas the Tank Engine & Friends", "Thomas & Friends", "Postman Pat", "Brum", "Rosie and Jim", "Pingu", "Pingu in the City", "Button Moon",
@@ -277,16 +277,34 @@ internal fun dayPartChoice(pool: List<PoolSeries>, parts: List<DayPart>, startMs
dayPartFor(pool, parts, startMs, zone).let { it.first to it.second }
/** [dayPartChoice], with the part it came from, or null for the whole pool. */
/**
* Which of a pool's shows each block may use, worked out once per pool and block rather than for every programme planned:
* matching titles means normalising every name, which made planning take seconds on the box. Keyed by the very pool and
* block objects, so a different pool or a changed block is always worked out afresh.
*/
private object PartPools {
private val recent = ArrayDeque<Pair<List<PoolSeries>, java.util.IdentityHashMap<DayPart, List<PoolSeries>>>>()
@Synchronized fun of(pool: List<PoolSeries>, part: DayPart, allowed: () -> List<PoolSeries>): List<PoolSeries> {
val entry = recent.firstOrNull { it.first === pool } ?: (pool to java.util.IdentityHashMap<DayPart, List<PoolSeries>>()).also {
recent.addFirst(it)
if (recent.size > 8) recent.removeLast()
}
return entry.second.getOrPut(part, allowed)
}
}
internal fun dayPartFor(pool: List<PoolSeries>, parts: List<DayPart>, startMs: Long, zone: java.time.ZoneId): Triple<List<PoolSeries>, String, DayPart?> {
val local = java.time.Instant.ofEpochMilli(startMs).atZone(zone)
// An event with nothing to show gives way to the ordinary block for that time.
for (part in parts.filter { it.covers(local.hour, local.dayOfWeek) }) {
val name = (if (part.days.isNotEmpty()) "event " else "block ") + part.group.ifEmpty { "${part.fromHour}-${part.toHour}" }
if (part.titles.isEmpty() && part.group.isEmpty()) return Triple(pool, name, part)
val titles = part.titles.map(::seriesKey).toSet()
// A film is named with its year, as "Halloween (1978)"; the pool already holds that exact film under its plain title.
val films = part.titles.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
val allowed = pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || (part.group.isNotEmpty() && it.group == part.group) }
val allowed = PartPools.of(pool, part) {
val titles = part.titles.map(::seriesKey).toSet()
// A film is named with its year, as "Halloween (1978)"; the pool already holds that exact film under its plain title.
val films = part.titles.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || (part.group.isNotEmpty() && it.group == part.group) }
}
if (allowed.isNotEmpty()) return Triple(allowed, name, part)
}
// A film saved for an event doesn't appear in everyday programming.
@@ -382,7 +400,19 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
val films = available.filter { it.isFilm }.ifEmpty { pool.filter { it.isFilm } }.ifEmpty { available }
// 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()) blockRest.getOrPut(part) { sharedAdaptiveRestMs(pool, dayParts, part, restMs) } else restMs
val (film, why) = chooseFilm(films, shown, start, rest, avoid)
var (film, why) = chooseFilm(films, shown, start, rest, avoid)
// Before an appointment, a rested film that leaves it on time, picked in the same seeded order as any other.
val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, (ON_TIME_FILM_RUN_IN_MS / (60 * 60_000L)).toInt()) { at -> dayPartFor(pool, dayParts, at, zone) }
if (appointment != null) {
val clear = films.filter { f -> !avoid(f, start, start + f.episodes.first().durationMs) }
// Rested films in the same seeded order as any other pick; when none is rested, the longest waiting first, as the fallback would.
val rested = clear.filter { f -> shown[f.id]?.let { start - it >= rest } != false }.shuffled(java.util.Random(start))
.ifEmpty { clear.sortedBy { shown[it.id] ?: Long.MIN_VALUE } }
fitBeforeAppointment(appointment, start, film, rested, ON_TIME_FILM_RUN_IN_MS, followers = 2) { start + it.episodes.first().durationMs }?.let {
film = it
why = "$why; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment).atZone(zone).toLocalTime()}"
}
}
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.
@@ -455,6 +485,55 @@ private const val ON_TIME_GRACE_MS = 20 * 60_000L
private const val ON_TIME_LAST_CALL_MS = 60 * 60_000L
/** How long before an appointment the programmes leading into it may be adjusted. */
private const val ON_TIME_RUN_IN_MS = 90 * 60_000L
/** The same for films, which are long: the last two or three before an appointment have to be chosen together for it to start in time. */
private const val ON_TIME_FILM_RUN_IN_MS = 6 * 60 * 60_000L
/**
* The next on-time appointment within [lookaheadHours] after [at]: the first hour boundary whose part is an
* appointment with something to show. Shared by the weighted and film planners; equal turns has its own, unchanged.
*/
internal fun nextAppointment(at: Long, zone: java.time.ZoneId, lookaheadHours: Int = ON_TIME_LOOKAHEAD_HOURS, partAt: (Long) -> Triple<List<PoolSeries>, String, DayPart?>): Long? {
val hour = 60 * 60_000L
val nextHour = java.time.Instant.ofEpochMilli(at).atZone(zone).truncatedTo(java.time.temporal.ChronoUnit.HOURS).plusHours(1).toInstant().toEpochMilli()
return (0 until lookaheadHours).map { nextHour + it * hour }.firstOrNull { boundary ->
val (shows, _, part) = partAt(boundary)
part?.onTime == true && shows.isNotEmpty()
}
}
/**
* Before an appointment, a programme that leaves it on time, as equal turns has done since PPV Sunday: one ending at the
* appointment or in its first [ON_TIME_GRACE_MS], or one leaving a gap another candidate closes. Only the last
* [runInMs] before the appointment is adjusted ([ON_TIME_RUN_IN_MS] for series, [ON_TIME_FILM_RUN_IN_MS] for films), nothing is cut and nothing is left empty. [candidates] are in the
* planner's own order of preference and already satisfy its rules. Null keeps [chosen].
*/
internal fun <T> fitBeforeAppointment(appointment: Long, start: Long, chosen: T, candidates: List<T>, runInMs: Long = ON_TIME_RUN_IN_MS,
/** How many more programmes may follow before the appointment: 1 for series, 2 for films, which are long. */
followers: Int = 1, ends: (T) -> Long): T? {
val latest = appointment + ON_TIME_GRACE_MS
if (ends(chosen) <= appointment - runInMs) return null
val remaining = appointment - start
fun length(x: T) = ends(x) - start
/** Whether [first] can open a run of up to [followers] more different candidates that ends at the appointment or in its grace. */
fun opensRun(first: T): Boolean {
val total = length(first)
if (total in remaining..remaining + ON_TIME_GRACE_MS) return true
if (total > remaining) return false
val rest = candidates.filter { it != first }.map(::length)
if (followers >= 1 && rest.any { total + it in remaining..remaining + ON_TIME_GRACE_MS }) return true
if (followers >= 2) rest.forEachIndexed { i, a -> if (total + a < remaining) for (j in i + 1 until rest.size) if (total + a + rest[j] in remaining..remaining + ON_TIME_GRACE_MS) return true }
return false
}
if (opensRun(chosen)) return null
val fits = candidates.filter { ends(it) <= latest }
// Best is one ending at the appointment, then one a single programme can follow in time, then any that opens a run.
return fits.firstOrNull { ends(it) >= appointment }
?: fits.firstOrNull { x -> ends(x) < appointment && candidates.any { it != x && ends(x) + length(it) in appointment..latest } }
?: fits.firstOrNull { opensRun(it) }
?: fits.firstOrNull().takeIf { ends(chosen) > latest }
// Failing that, at least something that ends while the appointment's window is still open, so it isn't missed.
?: candidates.firstOrNull { ends(it) < appointment + ON_TIME_LAST_CALL_MS }.takeIf { ends(chosen) >= appointment + ON_TIME_LAST_CALL_MS }
}
/** 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
@@ -530,14 +609,20 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
// 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 byTally = compareBy<PoolSeries> { tally[it.id]!! }.thenBy { pool.indexOf(it) }
val preferred = eligible.minWith(byTally)
// Before an appointment, the eligible show that leaves it on time, then any clear one, in tally order.
val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, partAt = ::partAt)
val fitted = appointment?.let { at -> fun ends(show: PoolSeries) = start + following(show).durationMs
fitBeforeAppointment(at, start, preferred, eligible.sortedWith(byTally), ends = ::ends) ?: fitBeforeAppointment(at, start, preferred, clear.sortedWith(byTally), ends = ::ends) }
val series = fitted ?: preferred
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 "") +
when {
unclashed.isEmpty() -> "; fallback: every show here airs elsewhere then"
series.id == last && unclashed.size < available.size -> "; again, as the others here air elsewhere then"
else -> ""
}
} + if (fitted != null) "; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment!!).atZone(zone).toLocalTime()}" 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 "")
val weight = part?.takeIf { series in available }?.weights?.get(seriesKey(series.title)) ?: weightOf(series)
@@ -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.8\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.9\"")
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.8")
next.setRequestProperty("User-Agent", "OrbitTV/0.99.9")
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,47 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.DayOfWeek
/** The confirmed events become appointments (4 November 2026): they start near their hour, with nothing cut and no gaps. */
class EventAppointmentsTest {
private val zone = java.time.ZoneId.of("Europe/London")
private val day = 24 * 60 * 60_000L
private val monday = java.time.LocalDate.of(2026, 11, 16).atStartOfDay(zone).toInstant().toEpochMilli()
private fun channel(n: Int) = SmartChannels.first { it.number == n }
@Test fun theFiveChannelsEventsAreAppointments() {
val after = channel(AFTER_DARK_NUMBER).dayParts.filter { it.key.startsWith("afterdark.") }
assertEquals(listOf(21, 21, 21), after.map { it.fromHour }); assertTrue(after.all { it.onTime })
assertTrue(channel(304).dayParts.single { it.key == "horror.slasher" }.let { it.onTime && it.fromHour == 20 })
assertTrue(channel(107).dayParts.single { it.days == setOf(DayOfWeek.SUNDAY) }.let { it.onTime && it.fromHour == 20 })
assertTrue(channel(202).dayParts.single { it.days.isNotEmpty() }.let { it.onTime && it.fromHour == 14 })
assertTrue(channel(201).dayParts.single { it.key == "terra.sunday" }.let { it.onTime && it.fromHour == 20 })
}
@Test fun aFilmEventStartsNearItsHourWithNothingCut() {
val films = (1..120).map { PoolSeries("f$it", "Film $it", listOf(PoolEpisode("f$it", "s", EpisodeMark(1, 1), "Film $it", (82L + it * 7 % 45) * 60_000L))) }
val parts = listOf(DayPart(21, 1, films.take(20).map { it.title }, days = setOf(DayOfWeek.FRIDAY), onTime = true, key = "test.event"), DayPart(0, 24))
val plan = extendFilmSchedule(films, ScheduleCursor(), monday, monday + 21 * day, 7 * day, parts, zone)
plan.entries.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) }
val starts = plan.entries.filter { it.presentation == "test.event" && java.time.Instant.ofEpochMilli(it.startMs).atZone(zone).hour >= 21 }.groupBy { java.time.Instant.ofEpochMilli(it.startMs).atZone(zone).toLocalDate() }
.map { (date, es) -> (es.minOf { it.startMs } - date.atTime(21, 0).atZone(zone).toInstant().toEpochMilli()) / 60_000 }
assertEquals(3, starts.size)
assertTrue("late by $starts", starts.all { it in 0..20 })
assertTrue(plan.entries.all { it.media.durationMs == films.first { f -> f.id == it.seriesId }.episodes.first().durationMs })
}
@Test fun aWeightedEventStartsNearItsHour() {
fun show(t: String, minutes: Int) = PoolSeries(t, t, (1..200).map { PoolEpisode("$t-$it", "s", EpisodeMark(1, it), "E$it", minutes * 60_000L) })
val pool = listOf(show("A", 47), show("B", 58), show("C", 89), show("Event", 95))
val parts = listOf(DayPart(20, 22, listOf("Event"), days = setOf(DayOfWeek.SUNDAY), onTime = true), DayPart(0, 24, listOf("A", "B", "C")))
val plan = extendWeighted(pool, ScheduleCursor(), monday, monday + 21 * day, { TIER_SUPPORTING }, parts, zone, { _, _, _ -> false }, false, { false })
plan.entries.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) }
val starts = plan.entries.filter { it.seriesId == "Event" }.groupBy { java.time.Instant.ofEpochMilli(it.startMs).atZone(zone).toLocalDate() }
.map { (date, es) -> (es.minOf { it.startMs } - date.atTime(20, 0).atZone(zone).toInstant().toEpochMilli()) / 60_000 }
assertEquals(3, starts.size)
assertTrue("late by $starts", starts.all { it in 0..20 })
}
}
@@ -25,7 +25,8 @@ class LastDriveInTest {
episodes.forEach { e ->
val start = local(e.startMs)
assertEquals(java.time.DayOfWeek.SATURDAY, start.dayOfWeek)
assertTrue("starts in the first slot after 20:00, so around 21:00: $start", start.hour in 20..21)
// An appointment at 21:00 since 4 November 2026: the film before it is chosen to finish in time.
assertTrue("starts at 21:00 or within its grace: $start", start.hour == 21 && start.minute <= 20)
assertEquals("played whole", joeBob.episodes[e.mark.episode - 1].durationMs, e.media.durationMs)
}
}