From c5e6d0cb354428ed8826edc35d904797eacc34f7 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Fri, 13 Nov 2026 17:14:35 +0000 Subject: [PATCH] Continuity: franchise films in release order; Doctor Who's multi-part stories kept together Paul, 13 Nov (RC3 scope, his safeguards): - franchiseOrdered: films booked back to back in one library collection (from the weekly collections read) go in release order (catalogue premiere date, else year, else id), among new bookings only; a slot's event stays with the slot; nothing else moves; no server requests. - StoryGroups: Doctor Who (2005) two- and three-part stories curated, including Heaven Sent / Hell Bent which no library numbers; numbered stories aren't counted twice; the 1963 series is left alone. Co-Authored-By: Claude Opus 5.5 --- .../java/tv/orbit/classic/CatalogueStore.kt | 7 +++ .../java/tv/orbit/classic/ChannelScheduler.kt | 29 ++++++++- .../main/java/tv/orbit/classic/Continuity.kt | 38 ++++++++++++ .../tv/orbit/classic/EmbyConnectionScreen.kt | 3 +- .../main/java/tv/orbit/classic/StoryGroups.kt | 21 ++++++- .../java/tv/orbit/classic/ContinuityTest.kt | 62 +++++++++++++++++++ 6 files changed, 154 insertions(+), 6 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/Continuity.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ContinuityTest.kt diff --git a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt index 4ccafd04..37e77dac 100644 --- a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt @@ -92,6 +92,13 @@ internal class CatalogueStore(context: Context, private val file: File) : Catalo generateSequence { if (c.moveToNext()) c.getString(0) else null }.toList() } /** Stage C: the work each of these library ids is, for telling which works a channel already holds. */ + /** Each film's place in release order ([releaseKeyOf]), for putting a franchise's films side by side in order. Read only. */ + @Synchronized fun releaseKeys(ids: Collection): Map = ids.chunked(400).flatMap { chunk -> + readableDatabase.rawQuery("SELECT id, premiere, year FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c -> + buildList { while (c.moveToNext()) add(c.getString(0) to releaseKeyOf(c.getString(1), if (c.isNull(2)) null else c.getInt(2))) } + } + }.toMap() + @Synchronized fun worksOf(ids: Collection): Map = ids.chunked(400).flatMap { chunk -> readableDatabase.rawQuery("SELECT id, title, year, provider_ids FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c -> generateSequence { if (c.moveToNext()) c else null }.map { row -> 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 7d55fb29..8ea8e733 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -32,7 +32,22 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val copies: (Collection) -> Map>? = { emptyMap() }, /** The original server, whose season plans (Advent, the Naughty List, the premieres) are Paul's own: no other server has them. */ private val original: Boolean = true, + /** Films' places in release order, from this server's catalogue (empty when it isn't read yet): see [franchiseOrdered]. */ + private val releaseKeys: (Collection) -> Map = { emptyMap() }, private val clock: () -> Long = System::currentTimeMillis) { + /** Which collection each film is in, from the weekly collections read, kept with the file's stamp. */ + private var franchises: Pair> = -1L to emptyMap() + private fun franchiseOf(): Map = synchronized(this) { + val file = store.collectionsFile() + val stamp = if (file.exists()) file.lastModified() else 0L + if (franchises.first != stamp) franchises = stamp to (if (!file.exists()) emptyMap() else HashMap().also { map -> + file.forEachLine { line -> runCatching { org.json.JSONObject(line) }.getOrNull()?.let { o -> + val name = o.optString("name").ifEmpty { return@let } + o.optJSONArray("members")?.let { a -> for (k in 0 until a.length()) map.putIfAbsent(a.optString(k), name) } + } } + }) + franchises.second + } /** When this TV last made a routine (weekly) list refresh; at most one per [POOL_ROUTINE_GAP_MS]. */ @Volatile internal var lastRoutineRefreshMs = 0L /** Disk only and quick, so the guide and player agree from the first frame after a restart. */ @@ -378,8 +393,18 @@ internal class ChannelScheduler(private val store: ScheduleStore, avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, fileRestMs = programming.fileRestMs, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon, seasonEndMs = seasonEndMs(number, now)) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") - if (plan !== existing) store.savePlan(userId, number, plan) - existing to plan + // Franchise films booked side by side go in release order, among the new bookings only (Continuity.kt). + val ordered = if (plan === existing) plan else runCatching { + val from = plan.entries.indexOfFirst { it.startMs >= (existing?.endMs ?: Long.MIN_VALUE) }.takeIf { it >= 0 } ?: plan.entries.size + val inFranchise = franchiseOf() + if (inFranchise.isEmpty()) plan else { + val films = plan.entries.drop(from).filter { it.media.item.type == "Movie" && it.media.item.id in inFranchise }.map { it.media.item.id } + val keys = if (films.size < 2) emptyMap() else releaseKeys(films) + plan.copy(entries = franchiseOrdered(plan.entries, from, { inFranchise[it] }, { keys[it] ?: "~" })) + } + }.getOrDefault(plan) + if (ordered !== existing) store.savePlan(userId, number, ordered) + existing to ordered } // Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence. if (plan !== existing) runCatching { diff --git a/android/app/src/main/java/tv/orbit/classic/Continuity.kt b/android/app/src/main/java/tv/orbit/classic/Continuity.kt new file mode 100644 index 00000000..72129939 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/Continuity.kt @@ -0,0 +1,38 @@ +package tv.orbit.classic + +/** + * Franchise films in release order (1.0 RC3, Paul, 13 November 2026: Horror played The Conjuring 2, then The Conjuring). + * + * Only films booked back to back that the library's own collections put in one franchise are touched, and only among new + * bookings, so nothing already on the guide moves and nothing is pulled forward from later. Within such a run they're put + * in release order: the release date where the catalogue has one, else the year, else the library's id, so the order is + * always the same. Being in one collection doesn't make a different film a sequel, and a collection's spin-offs simply sit + * where their release date puts them. Nothing here asks the server anything: the collections are the ones read weekly. + */ +internal fun franchiseOrdered(entries: List, fromIndex: Int, collectionOf: (String) -> String?, releaseKey: (String) -> String): List { + if (fromIndex >= entries.size) return entries + val out = entries.toMutableList() + var i = maxOf(fromIndex, 0) + while (i < out.size) { + val first = out[i] + val franchise = if (first.media.item.type == "Movie") collectionOf(first.media.item.id) else null + if (franchise == null) { i++; continue } + var end = i + 1 + while (end < out.size && out[end].media.item.type == "Movie" && out[end].startMs == out[end - 1].endMs && collectionOf(out[end].media.item.id) == franchise) end++ + if (end - i >= 2) { + val run = out.subList(i, end).toList() + val ordered = run.sortedWith(compareBy { releaseKey(it.media.item.id) }.thenBy { it.media.item.id }) + if (ordered.map { it.media.item.id } != run.map { it.media.item.id }) { + var at = run.first().startMs + // A slot's block or event (and its shorts slot) stays with the slot; the film moves. + ordered.forEachIndexed { k, e -> out[i + k] = e.copy(startMs = at, bookedStartMs = at, presentation = run[k].presentation, group = run[k].group); at += e.media.durationMs } + android.util.Log.i("OrbitSchedule", "franchiseOrder films=${run.size}") + } + } + i = end + } + return out +} + +/** A film's place in release order: yyyy-MM-dd, or the year alone, or "~" (after any dated film) when the catalogue has neither. */ +internal fun releaseKeyOf(premiere: String?, year: Int?): String = premiere?.takeIf { it.length >= 10 }?.substring(0, 10) ?: year?.toString() ?: "~" diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index 17d6428b..64707f8f 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -169,7 +169,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea remember(scheduleStore) { runCatching { scheduleStore.retryFailedOnce() }; true } // Your own channels (Create your own) are this server's, read before anything plans or restores. remember(workspace) { CustomChannels.load(workspace.scheduleDir); true } - val scheduler = remember(workspace) { ChannelScheduler(scheduleStore, copies = { if (catalogue.complete()) catalogue.idsByImdb(it) else null }, original = workspace.original) } + val scheduler = remember(workspace) { ChannelScheduler(scheduleStore, copies = { if (catalogue.complete()) catalogue.idsByImdb(it) else null }, original = workspace.original, + releaseKeys = { runCatching { catalogue.releaseKeys(it) }.getOrDefault(emptyMap()) }) } var scheduledChannels by ui::scheduledChannels var suggesting by ui::suggesting var suggestions by ui::suggestions diff --git a/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt b/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt index b8e1fcad..a3608b5c 100644 --- a/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt +++ b/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt @@ -37,14 +37,29 @@ internal fun partNumber(title: String): Int? = PartNumber.find(title)?.let { mat */ internal val LinkedEpisodes: Map>> get() = mapOf( seriesKey("Black Mirror") to listOf(listOf(EpisodeMark(4, 1), EpisodeMark(7, 6))), // USS Callister, then Into Infinity - seriesKey("Love, Death & Robots") to listOf(listOf(EpisodeMark(1, 2), EpisodeMark(3, 1)))) // Three Robots, then Exit Strategies + seriesKey("Love, Death & Robots") to listOf(listOf(EpisodeMark(1, 2), EpisodeMark(3, 1))), // Three Robots, then Exit Strategies + // Doctor Who's multi-part stories (1.0 RC3, Paul, 13 November 2026: The Empty Child must be followed by The Doctor + // Dances). Many libraries number them "(1)", "(2)", which is found anyway; these keep them together where a library + // doesn't, and add the ones no library numbers (Heaven Sent, then Hell Bent). Episode numbers as the 2005 series airs them. + // Only the 2005 series by name: plain "Doctor Who" is also the 1963 series, whose numbering is different. + seriesKey("Doctor Who (2005)") to DoctorWhoStories) + +private fun pair(season: Int, first: Int) = listOf(EpisodeMark(season, first), EpisodeMark(season, first + 1)) +private val DoctorWhoStories = listOf( + pair(1, 4), pair(1, 9), pair(1, 12), pair(2, 5), pair(2, 8), pair(2, 12), pair(3, 4), pair(3, 8), + listOf(EpisodeMark(3, 11), EpisodeMark(3, 12), EpisodeMark(3, 13)), + pair(4, 4), pair(4, 8), pair(4, 12), pair(5, 4), pair(5, 8), pair(5, 12), pair(6, 1), pair(6, 5), + pair(8, 11), pair(9, 1), pair(9, 3), pair(9, 7), pair(9, 11), pair(10, 11)) internal fun storiesOf(show: PoolSeries): ShowStories { if (show.isFilm) return ShowStories(emptyList()) val linked = LinkedEpisodes[seriesKey(show.title)].orEmpty().mapNotNull { marks -> marks.map { mark -> show.episodes.firstOrNull { it.mark == mark } ?: return@mapNotNull null }.let(::Story) } - if (linked.isNotEmpty()) return ShowStories(numberedStories(show) + linked) - return ShowStories(numberedStories(show)) + val numbered = numberedStories(show) + // A curated story the library already numbers is the same story: kept once. + val inNumbered = numbered.flatMap { s -> s.parts.map { it.id } }.toSet() + val extra = linked.filter { story -> story.parts.none { it.id in inNumbered } } + return ShowStories(numbered + extra) } private fun numberedStories(show: PoolSeries): List { diff --git a/android/app/src/test/java/tv/orbit/classic/ContinuityTest.kt b/android/app/src/test/java/tv/orbit/classic/ContinuityTest.kt new file mode 100644 index 00000000..c7fd1588 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ContinuityTest.kt @@ -0,0 +1,62 @@ +package tv.orbit.classic + +import org.junit.Assert.* +import org.junit.Test + +/** 1.0 RC3 (Paul, 13 November 2026): programmes that belong together play together, in order. */ +class ContinuityTest { + private fun episode(s: Int, e: Int, title: String) = PoolEpisode("dw${s}x$e", "src${s}x$e", EpisodeMark(s, e), title, 45 * 60_000L) + + @Test fun theEmptyChildIsFollowedByTheDoctorDancesEvenUnnumbered() { + val show = PoolSeries("dw2005", "Doctor Who (2005)", listOf(episode(1, 8, "Father's Day"), episode(1, 9, "The Empty Child"), episode(1, 10, "The Doctor Dances"), episode(1, 11, "Boom Town"))) + val story = storiesOf(show).of(show.episodes[1])!! + assertEquals(listOf("The Empty Child", "The Doctor Dances"), story.parts.map { it.title }) + assertNull(storiesOf(show).of(show.episodes[0])) + } + + @Test fun heavenSentThenHellBentAndNumberedStoriesAreNotCountedTwice() { + val show = PoolSeries("dw2005", "Doctor Who (2005)", listOf(episode(9, 11, "Heaven Sent"), episode(9, 12, "Hell Bent"), + episode(1, 9, "The Empty Child (1)"), episode(1, 10, "The Doctor Dances (2)"))) + val stories = storiesOf(show).stories + assertEquals(2, stories.size) + assertEquals(listOf("Heaven Sent", "Hell Bent"), stories.first { it.parts.first().mark.season == 9 }.parts.map { it.title }) + } + + @Test fun theClassicSeriesIsLeftAlone() { + val show = PoolSeries("dw1963", "Doctor Who", listOf(episode(1, 9, "The Keys of Marinus: The Sea of Death"), episode(1, 10, "The Keys of Marinus: The Velvet Web"))) + assertTrue(storiesOf(show).stories.isEmpty()) + } +} + +class FranchiseOrderTest { + private val min = 60_000L + private fun film(id: String, start: Long, length: Long, presentation: String = "") = + ScheduleEntry(id, EpisodeMark(1, 1), ScheduledMedia(SampleItem(id, "Movie", length / min, "", id, length), "s$id", length), start, presentation = presentation) + private val collection = mapOf("conj2" to "The Conjuring Collection", "conj1" to "The Conjuring Collection", "annab" to "The Conjuring Collection") + private val release = mapOf("conj1" to "2013-07-19", "conj2" to "2016-06-10", "annab" to "2014-10-03", "other" to "1981-08-21") + + @Test fun aDoubleBillGoesInReleaseOrderAndTheEveningKeepsItsShape() { + val p = listOf(film("other", 0, 97 * min), film("conj2", 97 * min, 134 * min, "horror.double"), film("conj1", 231 * min, 112 * min), film("next", 343 * min, 90 * min)) + val r = franchiseOrdered(p, 0, { collection[it] }, { release[it] ?: "~" }) + assertEquals(listOf("other", "conj1", "conj2", "next"), r.map { it.media.item.id }) + assertEquals(97 * min, r[1].startMs); assertEquals(209 * min, r[2].startMs) + assertEquals(343 * min, r[3].startMs) // what follows doesn't move + assertEquals("horror.double", r[1].presentation) // the event stays with its slot + assertTrue(r.zipWithNext().all { (a, b) -> a.endMs <= b.startMs }) + } + + @Test fun onlyNewBookingsAndOnlyFilmsSideBySide() { + val p = listOf(film("conj2", 0, 134 * min), film("conj1", 134 * min, 112 * min)) + assertEquals(listOf("conj2", "conj1"), franchiseOrdered(p, 2, { collection[it] }, { release[it] ?: "~" }).map { it.media.item.id }) + // A gap between them (an on-time appointment) means they aren't a double bill: left alone. + val apart = listOf(film("conj2", 0, 134 * min), film("conj1", 140 * min, 112 * min)) + assertEquals(listOf("conj2", "conj1"), franchiseOrdered(apart, 0, { collection[it] }, { release[it] ?: "~" }).map { it.media.item.id }) + } + + @Test fun spinOffsSitByReleaseDateAndUnknownDatesGoLastInTheSameOrderEveryTime() { + val p = listOf(film("conj2", 0, 134 * min), film("annab", 134 * min, 99 * min), film("conj1", 233 * min, 112 * min)) + assertEquals(listOf("conj1", "annab", "conj2"), franchiseOrdered(p, 0, { collection[it] }, { release[it] ?: "~" }).map { it.media.item.id }) + val undated = listOf(film("zz", 0, 90 * min), film("aa", 90 * min, 90 * min)) + assertEquals(listOf("aa", "zz"), franchiseOrdered(undated, 0, { "X" }, { "~" }).map { it.media.item.id }) + } +}