diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 4dadd890..9488673a 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -484,9 +484,32 @@ internal class ChannelScheduler(private val store: ScheduleStore, // A fresh pool already on the box (from another room, or turned on before) needs no reading of the library. store.loadPool(userId, programming.number)?.takeIf { clock() - it.fetchedAtMs < POOL_REFRESH_MS && it.signature == "${programming.signature}#${choices.tag}" } ?.let { cached -> loopFromPool(cached.series, programming)?.let { return it } } - val read = session.readChannelPool(programming, null, choices, checkActive) - val loop = loopFromPool(read.series, programming) ?: throw EmbyCheckException("None of ${programming.name}'s shows were found with episodes to schedule.") - store.savePool(userId, programming.number, ScheduleStore.SavedPool(read.series, clock(), keepRefound(userId, programming, read))) + val number = programming.number + val signature = "${programming.signature}#${choices.tag}" + // A first read part-way through, already on air: it carries on in the background round, not from the top here. + store.loadPool(userId, number)?.takeIf { store.loadRefresh(userId, number)?.target == signature } + ?.let { cached -> loopFromPool(cached.series, programming)?.let { return it } } + // Only as much as the channel needs to go on air (Paul, 30 November 2026: a new household's 40 channels took hours, + // each read whole before the next began). The rest of the list fills in a fair share at a time ([refreshStepwise]). + val now = clock() + val refresh = PoolRefresh(programming, choices, emptyList()) + val step = refresh.step(RefreshProgress(signature, false, now), Int.MAX_VALUE, now, pacedOut = { false }, + read = { entry -> checkActive(); readEntry(session, programming, choices, entry, checkActive) }, + save = { store.saveRefresh(userId, number, it) }, onAir = OnAirRule(programming)) + val loop = loopFromPool(step.pool, programming) ?: run { + store.deleteRefresh(number) + throw EmbyCheckException("None of ${programming.name}'s shows were found with episodes to schedule.") + } + if (step.finished) { + val read = EmbySampleSession.PoolRead(step.pool, step.progress.requests, step.progress.carried.size, step.progress.refound) + store.savePool(userId, number, ScheduleStore.SavedPool(step.pool, now, keepRefound(userId, programming, read))) + store.deleteRefresh(number) + } else { + // On air now; no signature yet, so the background round sees the list still to finish and carries on from here. + store.savePool(userId, number, ScheduleStore.SavedPool(step.pool, now, "")) + RefreshStatus.note(number, now, step.pending, now) + } + Log.i("OrbitSchedule", "channel=$number firstRead stop=${step.stop} titles=${step.pool.size} requests=${step.progress.requests} pending=${step.pending}") return loop } @@ -539,6 +562,9 @@ internal class ChannelScheduler(private val store: ScheduleStore, if (due && cached != null && !onlyWaiting && BackgroundPacing.active) { // In the background round, a list already on the box is refreshed entry by entry, a fair share at a time. pool = refreshStepwise(session, userId, programming, loop, choices, cached, signature, resuming, now, checkActive).also { requests = it.second }.first + } else if (due && resuming != null && cached != null) { + // A list being read step by step (a new channel's first read, or a refresh) is only ever carried on by the + // background round's fair share; setup and other screens plan from what it has so far. } else if (due) { if (routine && !onlyWaiting) lastRoutineRefreshMs = now val started = android.os.SystemClock.elapsedRealtime() diff --git a/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt b/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt index cac9d89d..3eaa5d23 100644 --- a/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt +++ b/android/app/src/main/java/tv/orbit/classic/PoolRefresh.kt @@ -86,12 +86,54 @@ internal class RefreshProgress(val target: String, val full: Boolean, val starte val requests: Int = 0, val rounds: Int = 0, val lastMs: Long = startedMs) /** Why a refresh step stopped. */ -internal enum class RefreshStop { FINISHED, SHARE, PACED, FAILING } +internal enum class RefreshStop { FINISHED, SHARE, PACED, FAILING, + /** A new channel's first read has enough to go on air ([OnAirRule]); the rest fills in later. */ + ENOUGH } internal class RefreshStep(val progress: RefreshProgress, val pool: List, val stop: RefreshStop, val spent: Int, val read: Int, val pending: Int) { val finished get() = stop == RefreshStop.FINISHED } +/** + * When a new channel's first read has enough to go on air (Paul, 30 November 2026: a new household setting up 40 channels + * waited hours for whole lists to be read). A day of programmes from a few titles: 15 films, or 4 series; or all of a list + * shorter than that. The rest of the list fills in afterwards, a fair share of each hour at a time. + */ +internal const val ON_AIR_FILMS = 15 +internal const val ON_AIR_SERIES = 4 +internal const val ON_AIR_HOURS = 24 +/** + * What a new channel needs before it goes on air. Every everyday block that names its titles needs a few of its own (3 films, + * or 2 series), so a morning block never fills from late-night titles just because those were read first; ratings and dayparts + * stay as approved. A block whose remaining titles the library doesn't have asks for no more. + */ +internal class OnAirRule(private val programming: ChannelProgramming) { + private val films = programming.filmRestMs != null + private val blocks = programming.dayParts.filter { it.days.isEmpty() && it.titles.isNotEmpty() } + private val perBlock = if (films) ON_AIR_PER_BLOCK_FILMS else ON_AIR_PER_BLOCK_SERIES + private fun names(part: DayPart, entry: String): Boolean { + val key = seriesKey(entry); val id = FilmIdentity.of(entry) + return part.titles.any { seriesKey(it) == key || FilmIdentity.of(it).let { f -> f.title == id.title && f.year == id.year } } + } + private fun found(pool: List, part: DayPart): Int { + val keys = part.titles.map(::seriesKey).toSet(); val ids = part.titles.map(FilmIdentity::of) + return pool.count { seriesKey(it.title) in keys || (it.isFilm && ids.any { f -> f.names(it) }) } + } + private fun short(pool: List, unread: Collection) = + blocks.filter { part -> found(pool, part) < minOf(perBlock, part.titles.size) && unread.any { names(part, it) } } + fun enough(pool: List, unread: Collection): Boolean { + val hours = pool.sumOf { show -> show.episodes.sumOf { it.durationMs } } / 3_600_000.0 + return hours >= ON_AIR_HOURS && pool.size >= (if (films) ON_AIR_FILMS else ON_AIR_SERIES) && short(pool, unread).isEmpty() + } + /** Of [unread], those a block still short of its own titles is waiting for, so they're read first. */ + fun wanted(pool: List, unread: Collection): Set { + val parts = short(pool, unread) + return unread.filterTo(HashSet()) { e -> parts.any { names(it, e) } } + } +} +internal const val ON_AIR_PER_BLOCK_FILMS = 3 +internal const val ON_AIR_PER_BLOCK_SERIES = 2 + /** A channel's share of what's left of the hour: shared equally by the channels still refreshing, never less than [REFRESH_MIN_SHARE]. */ internal const val REFRESH_MIN_SHARE = 8 /** The part of each hour's budget list refreshes leave for the rest of the round: the Drive-In, the evidence and the catalogue. */ @@ -163,12 +205,21 @@ internal class PoolRefresh(private val programming: ChannelProgramming, private * [save] is called after every entry, so nothing read is lost. */ fun step(start: RefreshProgress, share: Int, nowMs: Long, pacedOut: () -> Boolean, - read: (RefreshEntry) -> Pair, save: (RefreshProgress) -> Unit = {}): RefreshStep { + read: (RefreshEntry) -> Pair, save: (RefreshProgress) -> Unit = {}, + /** A new channel's first read: what it reads first, and when it stops, once the pool would carry the channel. */ + onAir: OnAirRule? = null): RefreshStep { var progress = RefreshProgress(start.target, start.full, start.startedMs, start.done, start.carried, start.refound, start.requests, start.rounds + 1, nowMs) var spent = 0; var count = 0; var failures = 0 var stop = RefreshStop.FINISHED while (true) { - val entry = next(progress) ?: break + var entry = next(progress) ?: break + if (onAir != null) { + val unread = entries.filter { needs(it, progress) } + val now = pool(progress) + if (onAir.enough(now, unread.map { it.text })) { stop = RefreshStop.ENOUGH; break } + val wanted = onAir.wanted(now, unread.map { it.text }) + unread.firstOrNull { it.text in wanted }?.let { entry = it } + } if (spent >= share) { stop = RefreshStop.SHARE; break } if (pacedOut()) { stop = RefreshStop.PACED; break } val result = try { read(entry) } catch (failure: EmbyCheckException) { diff --git a/android/app/src/test/java/tv/orbit/classic/FirstRunSimulationTest.kt b/android/app/src/test/java/tv/orbit/classic/FirstRunSimulationTest.kt new file mode 100644 index 00000000..6257b001 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/FirstRunSimulationTest.kt @@ -0,0 +1,85 @@ +package tv.orbit.classic + +import org.json.JSONObject +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File + +/** + * A new household switching on every channel (Paul, 30 November 2026: "40 channels would take about 10 hours"). From an empty + * TV, each channel's first read stops once it has a day's worth with every block holding its own titles ([onAirEnough]), + * paced as setup is (a request a second, 600 in an hour); then the background round fills the lists in at the household + * budget. Compared with reading every list whole first. Reads are answered from the catalogue export (SIM_CATALOGUE), with + * episode counts from a TV snapshot's pools (SIM_SNAP). Writes SIM_OUT/first-run.txt. + */ +class FirstRunSimulationTest { + private class Row(val id: String, val type: String, val title: String, val year: Int?, val imdb: String) + + @Test fun aNewHouseholdIsOnAirWithinAboutAnHour() { + val snap = System.getenv("SIM_SNAP")?.let(::File); val cat = System.getenv("SIM_CATALOGUE")?.let(::File) + assumeTrue(snap != null && snap.isDirectory && cat != null && cat.exists()) + val rows = cat!!.readLines().mapNotNull { l -> l.split('\t').takeIf { it.size >= 5 }?.let { f -> Row(f[0], f[1], f[2], f[3].toIntOrNull(), f[4]) } } + val films = rows.filter { it.type == "Movie" }.groupBy { seriesKey(it.title) } + val series = rows.filter { it.type == "Series" } + val seriesByKey = series.groupBy { seriesKey(it.title) } + val user = snap!!.listFiles()!!.first { it.name.startsWith("episodes-") && it.name.endsWith(".json") }.let { JSONObject(it.readText()).getString("user") } + val store = ScheduleStore(snap) + val known = BuiltInChannels.flatMap { store.loadPool(user, it.number)?.series.orEmpty() }.associateBy { seriesKey(it.title) } + fun answer(entry: RefreshEntry): Pair, Int> = when (entry.kind) { + RefreshEntry.Kind.FILM -> { + val identity = FilmIdentity.of(entry.text); val named = films[seriesKey(identity.title)].orEmpty() + if (named.isEmpty()) emptyList() to 0 else listOfNotNull(resolveFilm(identity, named.map { r -> FilmCandidate(r.id, r.title, r.year, r.imdb.ifEmpty { null }, + listOf(JSONObject().put("Id", "9" + r.id).put("Container", "mkv").put("RunTimeTicks", 6_000L * 10_000_000))) }).film) to 1 + } + RefreshEntry.Kind.SERIES -> { + val key = seriesKey(entry.text) + val copies = (seriesByKey[key] ?: series.filter { seriesKey(it.title).startsWith("$key ") }.take(1)).take(4) + if (copies.isEmpty()) emptyList() to 0 else { + val show = known[seriesKey(copies[0].title)] ?: PoolSeries(copies[0].id, copies[0].title, (1..20).map { PoolEpisode(copies[0].id + "%03d".format(it), "9" + copies[0].id + "%03d".format(it), EpisodeMark(1, it), "E$it", 1_800_000) }) + listOf(show) to 1 + copies.size * (show.episodes.size / WHOLE_SERIES_PAGE + 1) + } + } + RefreshEntry.Kind.CHOSEN -> emptyList() to 0 + } + fun read(entry: RefreshEntry) = answer(entry).let { (found, cost) -> EmbySampleSession.PoolRead(found, cost) to cost } + // Setup: a request a second, at most 600 in any hour. + fun setupSeconds(requests: Int): Long = if (requests <= BackgroundPacing.SETUP_HOURLY) requests.toLong() else 3_600L * (requests / BackgroundPacing.SETUP_HOURLY) + requests % BackgroundPacing.SETUP_HOURLY + val out = StringBuilder("channel\tname\tfirstReadRequests\twholeReadRequests\ttitlesOnAir\tpending\n") + var firstTotal = 0; var wholeTotal = 0 + val onAirMinutes = ArrayList() + val state = HashMap>() + val pools = HashMap>() + for (p in BuiltInChannels) { + val first = PoolRefresh(p, ChannelChoices(), emptyList()).step(RefreshProgress("sig", false, 0), Int.MAX_VALUE, 0, { false }, ::read, onAir = OnAirRule(p)) + val whole = PoolRefresh(p, ChannelChoices(), emptyList()).step(RefreshProgress("sig", false, 0), Int.MAX_VALUE, 0, { false }, ::read) + firstTotal += first.progress.requests; wholeTotal += whole.progress.requests + onAirMinutes += setupSeconds(firstTotal) / 60 + out.append("${p.number}\t${p.name}\t${first.progress.requests}\t${whole.progress.requests}\t${first.pool.size}\t${first.pending}\n") + if (!first.finished) state[p.number] = PoolRefresh(p, ChannelChoices(), first.pool) to first.progress + pools[p.number] = first.pool + } + // Then the background round fills the lists in: 100 an hour for each of two TVs, a fair share each, a tenth kept back. + var hours = 0 + val budget = BackgroundPacing.share(BackgroundPacing.HOURLY_BUDGET, 2) + while (state.isNotEmpty() && hours < 24 * 14) { + hours++ + var used = 0 + val waiting = state.keys.toMutableSet() + for (p in BuiltInChannels) { + val (refresh, progress) = state[p.number] ?: continue + val share = refreshShare(budget, used, waiting.size) + val step = refresh.step(progress, share, hours * 3_600_000L, { refreshPacedOut(budget, used) }, { e -> read(e).also { used += it.second } }) + waiting -= p.number + if (step.finished) state -= p.number else state[p.number] = PoolRefresh(p, ChannelChoices(), step.pool) to step.progress + } + } + val in10 = onAirMinutes.count { it <= 10 }; val in30 = onAirMinutes.count { it <= 30 } + val summary = "channels=${BuiltInChannels.size} firstReadRequests=$firstTotal (all on air after ${setupSeconds(firstTotal) / 60} min; $in10 within 10 min, $in30 within 30 min) " + + "wholeReadRequests=$wholeTotal (every list whole first: ${setupSeconds(wholeTotal) / 60} min) listsComplete after $hours h of background rounds; unfinished=${state.size}\n" + File(System.getenv("SIM_OUT")!!).also { it.mkdirs() }.resolve("first-run.txt").writeText(summary + out) + println(summary) + assertTrue(setupSeconds(firstTotal) <= 75 * 60L) + assertTrue(state.isEmpty()) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt b/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt index e627041e..2063a354 100644 --- a/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/PoolRefreshTest.kt @@ -172,4 +172,30 @@ class PoolRefreshTest { assertEquals("1 of 3 channel lists are catching up, 12 titles still to read, a fair share each hour; the longest has been going since 3 hours ago. " + "Each list is read again about once a week; the longest since its last full read is channel 102, 4 days ago.", refreshStatusLine(catching, now)) } + + @Test fun aNewChannelGoesOnAirOnceItHasADayAndEachBlockHasItsOwn() { + val films = (1..30).map { "Film $it" } + val parts = listOf(DayPart(6, 18, films.take(10)), DayPart(18, 6, films.drop(20))) + val p = filmChannel(*films.toTypedArray()).copy(dayParts = parts) + val found = films.associateWith { listOf(film(it)) } + val log = mutableListOf() + val step = PoolRefresh(p, ChannelChoices(), emptyList()).step(RefreshProgress("t", false, 0), Int.MAX_VALUE, 0, { false }, read(found, log = log), onAir = OnAirRule(p)) + assertEquals(RefreshStop.ENOUGH, step.stop) + // Each block's own titles first (three for the day, three for the night), then a day's worth in list order. + assertEquals(listOf("Film 1", "Film 2", "Film 3", "Film 21", "Film 22", "Film 23") + (4..13).map { "Film $it" }, log) + assertTrue(step.pending > 0) + // The rest fills in later from where it stopped. + val rest = mutableListOf() + val finish = PoolRefresh(p, ChannelChoices(), step.pool).step(step.progress, Int.MAX_VALUE, 1, { false }, read(found, log = rest)) + assertTrue(finish.finished) + assertEquals((14..20).map { "Film $it" } + (24..30).map { "Film $it" }, rest) + assertEquals(30, finish.pool.size) + } + + @Test fun aShortListIsReadWhole() { + val p = seriesChannel("A", "B") + val step = PoolRefresh(p, ChannelChoices(), emptyList()).step(RefreshProgress("t", false, 0), Int.MAX_VALUE, 0, { false }, + read(mapOf("A" to listOf(show("A", 60)), "B" to listOf(show("B", 60)))), onAir = OnAirRule(p)) + assertTrue(step.finished) + } } diff --git a/docs/roadmap.md b/docs/roadmap.md index 692873ee..a44bd6e5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -529,6 +529,16 @@ Each new channel gets its own content audit, branding, idents, dayparts, schedul documentaries (about 20) go to Odyssey as a strand. Channel families (Heroes and Heroes Live; Horror, After Dark and Horror TV; Orbit POP with the youth channels) share visual DNA, and sit near each other by number, not in new screens. +## Launch checklist: a new household's first evening (Paul, 30 November 2026) +Setting up every channel used to read each list whole before the next began: about 5,000 requests, eight hours at setup's +600 an hour. Now (after build 81) a new channel's first read stops once it has a day's worth with every everyday block holding +a few of its own titles (3 films or 2 series; `OnAirRule` in PoolRefresh.kt), reading those blocks' titles first, so ratings and +dayparts stay as approved. The rest of the list fills in through the background round's fair share, resuming across restarts. +Setup may use the whole 600 an hour while the server is quick. Simulation from the 30 Nov snapshot (FirstRunSimulationTest): +44 channels on air after 937 requests, 25 within 10 minutes and all within about 65 minutes; the lists complete over about +two days at 100 an hour per TV. Still to do before launch: a guide marker for a channel still filling in (Settings already +says so), and a first-run test on a real TV. + ## Orbit Premiere's identity pass (Paul, 26 November 2026; after the release gate) Premiere's identity (agreed 3 November) is big event films now and, later, recent releases, new library additions and first Orbit screenings. Only the first exists: a fixed list of 98 blockbusters with no blocks or events. Do it with the Director's