diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index de53dfea..f87cd5f8 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionCode = 142 - versionName = "0.99.12-safe-pool-refresh" + versionCode = 143 + versionName = "0.99.13-story-grouping" } buildFeatures { compose = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt index c4305d00..ec965a22 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -54,7 +54,12 @@ internal data class ChannelProgramming(val number: Int, val name: String, val se /** With [catalogueScaleHours]: the least share of its tier's weight a short catalogue keeps. */ val catalogueScaleFloor: Double = MIN_CATALOGUE_SCALE, /** Library items taken off this channel by editorial decision, by their Emby id, whichever way they reached its pool. */ - val withdrawn: Set = emptySet()) { + val withdrawn: Set = emptySet(), + /** + * Multi-part stories booked whole, in order and back to back ([storiesOf], [extendWeighted]); weighted blocks only. Paradox + * only (Living Network Stage A, approved 4 November 2026). + */ + val storyGrouping: Boolean = false) { /** A show's weight here, by its tier (a show the brief doesn't name counts as supporting), scaled by [catalogueScaleHours]. */ fun weightOf(show: PoolSeries): Double { val tier = tierWeights?.get(seriesKey(show.title)) ?: TIER_SUPPORTING @@ -174,7 +179,7 @@ internal val SmartChannels = listOf( ChannelProgramming(TOTS_NUMBER, "Tots", TotsShows, seriesCount = 40, finishTogether = true, exactTitles = true, dayParts = TotsDayParts, shuffleEpisodes = true, tierWeights = TotsTiers, catalogueScaleHours = CATALOGUE_SCALE_HOURS), ChannelProgramming(106, "Paradox", ParadoxShows, seriesCount = 20, finishTogether = true, exactTitles = true, dayParts = ParadoxDayParts, shuffleTitles = ParadoxStandalones.toSet(), - tierWeights = ParadoxTiers)) + + tierWeights = ParadoxTiers, storyGrouping = true)) + 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(), @@ -604,7 +609,9 @@ internal fun extendWeighted(pool: List, cursor: ScheduleCursor, from /** Files aired shortly before [fromMs], for the same-file guard across a top-up. */ recentFiles: Map = emptyMap(), /** How long a file rests before it may air again while another show could play. [SAME_FILE_MS] unless a channel asks for longer. */ - fileRestMs: Long = SAME_FILE_MS): ChannelPlan { + fileRestMs: Long = SAME_FILE_MS, + /** Story-aware grouping ([ChannelProgramming.storyGrouping]): multi-part stories are booked whole, in order, back to back. */ + stories: Boolean = false): ChannelPlan { val marks = cursor.marks.toMutableMap() val shown = cursor.filmShown.toMutableMap() val tallies = cursor.tallies.mapValues { it.value.toMutableMap() }.toMutableMap() @@ -615,13 +622,28 @@ internal fun extendWeighted(pool: List, cursor: ScheduleCursor, from var last = cursor.lastSeriesId 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 + val storiesByShow = HashMap() + fun storiesOf(show: PoolSeries): ShowStories? = if (stories) storiesByShow.getOrPut(show.id) { tv.orbit.classic.storiesOf(show) } else null + fun running(show: PoolSeries) = if (isMixed(show)) mixes.getOrPut(show.id) { storiesOf(show)?.let { shuffledStories(show, it) } ?: shuffledEpisodes(show) } else show.episodes + /** Whether [episode], a later part of a story, comes straight after its part before, which [show] has just played. */ + fun continuesStory(show: PoolSeries, episode: PoolEpisode): Boolean { + val story = storiesOf(show)?.of(episode) ?: return false + val part = story.parts.indexOfFirst { it.id == episode.id } + return part > 0 && last == show.id && story.parts[part - 1].mark == marks[show.id] + } // Each show's next episode, worked out once and kept until that show plays: finding it means searching its episode list. val next = HashMap() 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] } + else running(show).let { mix -> + var at = (mix.indexOfFirst { it.mark == marks[show.id] } + 1) % mix.size + // A mixed show never opens on a later part: one left behind, as when a story was cut off before grouping, waits for its whole story to come round. + if (stories) { var steps = 0; while (steps++ < mix.size && (storiesOf(show)!!.partOf(mix[at]) > 0) && !continuesStory(show, mix[at])) at = (at + 1) % mix.size } + mix[at] + } } + /** How long [show]'s next booking runs: the whole story when it opens one. */ + fun lengthOf(show: PoolSeries): Long = following(show).let { episode -> storiesOf(show)?.takeIf { it.partOf(episode) == 0 }?.of(episode)?.durationMs ?: episode.durationMs } fun hadItsTurn(available: List, at: Long) = available.any { film -> film.isFilm && shown[film.id]?.let { at - it < ONCE_A_NIGHT_MS } == true } fun partAt(at: Long): Triple, String, DayPart?> { val first = dayPartFor(pool, dayParts, at, zone) @@ -637,8 +659,22 @@ internal fun extendWeighted(pool: List, cursor: ScheduleCursor, from // A show new to the block, or back in it, joins level with the block's lowest, not at nothing. val floor = available.mapNotNull { tally[it.id] }.minOrNull() ?: 0.0 available.forEach { tally.putIfAbsent(it.id, floor) } + // A story half-told carries on before anything else, as long as it's still in its block. + val continuing = if (stories) available.firstOrNull { it.id == last && continuesStory(it, following(it)) } else null val unclashed = available.filter { !avoid(it, start, start + following(it).durationMs) } - val clear = unclashed.ifEmpty { available } + val appointmentAhead = if (stories && part?.onTime != true) nextAppointment(start, zone, partAt = ::partAt) else null + /** A show opening a story only when every part starts in this block, none clashes, and it ends before the next appointment. */ + fun storyFits(show: PoolSeries): Boolean { + val episode = following(show) + val story = storiesOf(show)?.takeIf { it.partOf(episode) == 0 }?.of(episode) ?: return true + var at = start + for (each in story.parts) { + if (partAt(at).second != block || avoid(show, at, at + each.durationMs)) return false + at += each.durationMs + } + return appointmentAhead == null || at <= appointmentAhead + ON_TIME_GRACE_MS + } + val clear = unclashed.ifEmpty { available }.let { shows -> if (stories) shows.filter(::storyFits).ifEmpty { shows } else shows } val rules = listOf<(PoolSeries) -> Boolean>( { it.id != last }, { aired[following(it).id]?.let { at -> start - at < fileRestMs } != true }, { following(it).mark != running(it).first().mark || runStarted[it.id]?.let { at -> start - at < RUN_REST_MS } != true }) // Drop the softest rules first, only as far as needed to leave a choice. @@ -650,22 +686,26 @@ internal fun extendWeighted(pool: List, cursor: ScheduleCursor, from 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 + val fitted = if (continuing != null) null else appointment?.let { at -> fun ends(show: PoolSeries) = start + lengthOf(show) fitBeforeAppointment(at, start, preferred, eligible.sortedWith(byTally), ends = ::ends) ?: fitBeforeAppointment(at, start, preferred, clear.sortedWith(byTally), ends = ::ends) } - val series = fitted ?: preferred + val series = continuing ?: 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 "") + + val story = storiesOf(series)?.let { it.of(episode)?.let { found -> found.parts.size to it.partOf(episode) + 1 } } + val why = if (continuing != null) "$block; story: part ${story!!.second} of ${story.first}, straight after the part before" else "$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 "" + } + (if (fitted != null) "; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment!!).atZone(zone).toLocalTime()}" else "") + + (if (story != null) "; story: part 1 of ${story.first}, booked whole" 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) tally[series.id] = tally[series.id]!! + episode.durationMs / 60_000.0 / weight marks[series.id] = episode.mark next.remove(series.id) + // A show whose story was cut off by its block works out its next episode again, so it doesn't pick up mid-story later. + last?.let { if (it != series.id) next.remove(it) } 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 @@ -683,7 +723,7 @@ internal fun extendWeighted(pool: List, cursor: ScheduleCursor, from */ internal fun extendByBlock(pool: List, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, weightOf: (PoolSeries) -> Double, dayParts: List, zone: java.time.ZoneId, avoid: ProgrammeClash, shuffle: Boolean, mixed: (PoolSeries) -> Boolean, finishTogether: Boolean, - recentFiles: Map = emptyMap(), runBefore: Int = 0, fileRestMs: Long = SAME_FILE_MS): ChannelPlan { + recentFiles: Map = emptyMap(), runBefore: Int = 0, fileRestMs: Long = SAME_FILE_MS, stories: Boolean = false): ChannelPlan { fun weightedAt(at: Long) = dayPartFor(pool, dayParts, at, zone).third?.weighted != false val hour = 60 * 60_000L val entries = mutableListOf() @@ -696,7 +736,7 @@ internal fun extendByBlock(pool: List, cursor: ScheduleCursor, fromM while (end < untilMs && weightedAt(end) == weighted) end += hour val stretch = if (weighted) { val recent = recentFiles + entries.filter { it.startMs >= start - fileRestMs }.associate { it.media.item.id to it.startMs } - extendWeighted(pool, tail, start, minOf(end, untilMs), weightOf, dayParts, zone, avoid, shuffle, mixed, recent, fileRestMs) + extendWeighted(pool, tail, start, minOf(end, untilMs), weightOf, dayParts, zone, avoid, shuffle, mixed, recent, fileRestMs, stories) } else { val trailing = entries.lastOrNull()?.let { t -> entries.asReversed().takeWhile { it.seriesId == t.seriesId }.size } ?: runBefore extendSchedule(pool, tail, start, minOf(end, untilMs), null, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing).let { plan -> @@ -859,7 +899,9 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List /** Film channels only: see [ChannelProgramming.adaptiveFilmRest]. */ adaptiveRest: Boolean = false, /** Weighted channels only: see [extendWeighted]. */ - fileRestMs: Long = SAME_FILE_MS): ChannelPlan? { + fileRestMs: Long = SAME_FILE_MS, + /** Weighted channels only: see [ChannelProgramming.storyGrouping]. */ + stories: 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 @@ -867,7 +909,7 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List val trailing = kept?.entries?.lastOrNull()?.let { tail -> kept.entries.asReversed().takeWhile { it.seriesId == tail.seriesId }.size } ?: 0 val added = if (weightOf != null && filmRestMs == null) { val recent = kept?.entries.orEmpty().filter { it.startMs >= from - fileRestMs }.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, fileRestMs) + extendByBlock(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, weightOf, dayParts, zone, avoid, shuffle, mixed, finishTogether, recent, trailing, fileRestMs, stories) } 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) } 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 17546805..69f72464 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -130,7 +130,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl } 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.") + weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping) ?: 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 }) diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt index 608917f6..5435845d 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt @@ -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.12\"") + connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.13\"") request.token?.let { connection.setRequestProperty("X-Emby-Token", it) } if (request.method == "POST") { val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8) diff --git a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt index b7e4d4d4..0c6b4b6c 100644 --- a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt +++ b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt @@ -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.12") + next.setRequestProperty("User-Agent", "OrbitTV/0.99.13") 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()) { diff --git a/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt b/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt new file mode 100644 index 00000000..cf10f8f0 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/StoryGroups.kt @@ -0,0 +1,67 @@ +package tv.orbit.classic + +/** + * Story-aware episode grouping (Living Network Stage A, approved by Paul on 4 November 2026): which episodes of a show form + * one multi-part story, from evidence in the library's own data only. A story is told only when every part says so: titles + * ending "(1)", "(2)" or "Part One", "Part Two" and so on, numbered from one with no gaps, two to [MAX_STORY_PARTS] parts, + * each the next episode of the show, in the same season or running from a season's last episode into the next one's first. + * Anything less certain isn't a story, and plays exactly as it did before. + */ +internal const val MAX_STORY_PARTS = 6 + +internal class Story(val parts: List) { + val durationMs get() = parts.sumOf { it.durationMs } +} + +/** A show's stories, keyed by each part's file id, so a programme can be looked up as it's booked. */ +internal class ShowStories(stories: List) { + private val byFile = stories.flatMap { story -> story.parts.map { it.id to story } }.toMap() + val stories = stories + fun of(episode: PoolEpisode): Story? = byFile[episode.id] + /** Where [episode] sits in its story, counting from 0, or -1 when it isn't part of one. */ + fun partOf(episode: PoolEpisode) = of(episode)?.parts?.indexOfFirst { it.id == episode.id } ?: -1 +} + +private val PartNumber = Regex("""(?:\((\d)\)|,?\s*\bPart\s+(\d|One|Two|Three|Four|Five|Six|I{1,3}|IV|V|VI))\s*$""", RegexOption.IGNORE_CASE) +private val PartWords = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "i" to 1, "ii" to 2, "iii" to 3, "iv" to 4, "v" to 5, "vi" to 6) + +/** The part number a title ends with, or null. */ +internal fun partNumber(title: String): Int? = PartNumber.find(title)?.let { match -> + val number = match.groupValues[1].ifEmpty { match.groupValues[2] } + number.toIntOrNull() ?: PartWords[number.lowercase()] +} + +internal fun storiesOf(show: PoolSeries): ShowStories { + if (show.isFilm) return ShowStories(emptyList()) + val episodes = show.episodes.sortedBy { it.mark } + val lastOfSeason = episodes.groupBy { it.mark.season }.mapValues { (_, it) -> it.maxOf { e -> e.mark.episode } } + fun follows(before: PoolEpisode, after: PoolEpisode) = (after.mark.season == before.mark.season && after.mark.episode == before.mark.episode + 1) || + (after.mark.season == before.mark.season + 1 && after.mark.episode == 1 && before.mark.episode == lastOfSeason[before.mark.season]) + val stories = mutableListOf() + var i = 0 + while (i < episodes.size) { + if (partNumber(episodes[i].title) != 1) { i++; continue } + val run = mutableListOf(episodes[i]) + while (i + run.size < episodes.size && partNumber(episodes[i + run.size].title) == run.size + 1 && follows(run.last(), episodes[i + run.size])) run += episodes[i + run.size] + if (run.size in 2..MAX_STORY_PARTS) stories += Story(run) + i += run.size + } + return ShowStories(stories) +} + +/** + * A show's fixed mixed deck with each story kept whole and in order, as one card: the same mix every time, so a place in it + * can be saved as an episode, as [shuffledEpisodes]. + */ +internal fun shuffledStories(series: PoolSeries, stories: ShowStories): List { + if (stories.stories.isEmpty()) return shuffledEpisodes(series) + val cards = series.episodes.mapNotNull { episode -> + val story = stories.of(episode) + when { + story == null -> listOf(episode) + story.parts.first().id == episode.id -> story.parts + else -> null + } + } + return cards.shuffled(java.util.Random(series.id.hashCode().toLong())).flatten() +} diff --git a/android/app/src/test/java/tv/orbit/classic/ReplayFingerprintTest.kt b/android/app/src/test/java/tv/orbit/classic/ReplayFingerprintTest.kt index 17abf7db..926f93c7 100644 --- a/android/app/src/test/java/tv/orbit/classic/ReplayFingerprintTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/ReplayFingerprintTest.kt @@ -51,7 +51,7 @@ class ReplayFingerprintTest { val all = committed.entries.toMutableList() while (now < end) { current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone, - shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest) ?: break + shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping) ?: break current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it } now += 6 * 60 * 60_000L } diff --git a/android/app/src/test/java/tv/orbit/classic/StoryGroupingReplayTest.kt b/android/app/src/test/java/tv/orbit/classic/StoryGroupingReplayTest.kt new file mode 100644 index 00000000..8b516551 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/StoryGroupingReplayTest.kt @@ -0,0 +1,150 @@ +package tv.orbit.classic + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File + +/** + * Living Network Stage A's check: story grouping on Paradox, from copies of the box's files. Four weeks of new bookings + * after Paradox's committed plan, without grouping (0.99.12) and with it (as built), avoiding every other channel's + * programmes as the box does, and once more with a save and reload every 18 hours. Run by hand: + * ORBIT_REPLAY_DIR= ./gradlew :app:testDebugUnitTest --tests '*StoryGroupingReplayTest*' + * Writes story-grouping-replay.txt there, and fails on any broken rule. + */ +class StoryGroupingReplayTest { + private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File) + private val zone = java.time.ZoneId.of("Europe/London") + private val day = 24 * 60 * 60_000L + private val hour = 60 * 60_000L + + private fun plan(file: File): ChannelPlan { + val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks") + val entries = (0 until rows.length()).map { i -> + val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n") + ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d), + o.getLong("a"), o.optString("w"), o.optString("p")) + } + return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"), + marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } }, + t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(), + t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty())) + } + + private fun pool(file: File): List { + val rows = JSONObject(file.readText()).getJSONArray("series") + return (0 until rows.length()).map { i -> + val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes") + PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j -> + val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5)) + }, o.optString("group")) + } + } + + private fun replay(committed: ChannelPlan, series: List, programming: ChannelProgramming, stories: Boolean, avoid: ProgrammeClash = { _, _, _ -> false }, + restartEvery: Int = 0, keepCommitted: Boolean = false): List { + var current = committed + var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS + val end = committed.endMs + 28 * day + val all = committed.entries.toMutableList() + val folder = java.nio.file.Files.createTempDirectory("stories").toFile() + var step = 0 + while (now < end) { + if (restartEvery > 0 && ++step % restartEvery == 0) { ScheduleStore(folder).savePlan("user", programming.number, current); current = ScheduleStore(folder).loadPlan("user", programming.number)!! } + current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone, avoid, + shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf }, + adaptiveRest = programming.adaptiveFilmRest, stories = stories) ?: break + current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it } + now += 6 * hour + } + all.sortBy { it.startMs } + assertEquals("${programming.name}: committed programmes kept", committed.entries, all.take(committed.entries.size)) + return if (keepCommitted) all.filter { it.startMs < end } else all.filter { it.startMs >= committed.endMs && it.startMs < end } + } + + private fun pct(x: Double) = "%.0f%%".format(100 * x) + + /** Parts booked, and how many aren't straight after their part before or straight before their next. */ + private class StoryCount(val parts: Int, val stranded: Int, val whole: Int) + private fun storyCount(entries: List, series: List, only: (PoolSeries) -> Boolean = { true }): StoryCount { + val byId = series.associateBy { it.id } + val found = series.associate { it.id to storiesOf(it) } + var parts = 0; var stranded = 0; var whole = 0 + entries.forEachIndexed { i, e -> + val show = byId[e.seriesId]?.takeIf(only) ?: return@forEachIndexed + val episode = show.episodes.firstOrNull { it.mark == e.mark } ?: return@forEachIndexed + val story = found.getValue(show.id).of(episode) ?: return@forEachIndexed + val k = story.parts.indexOfFirst { it.id == episode.id } + parts++ + val before = entries.getOrNull(i - 1); val after = entries.getOrNull(i + 1) + val joinedBefore = k == 0 || (before != null && before.seriesId == e.seriesId && before.mark == story.parts[k - 1].mark && before.endMs == e.startMs) + // The last programme of the window can't show what follows it. + val joinedAfter = k == story.parts.size - 1 || after == null || (after.seriesId == e.seriesId && after.mark == story.parts[k + 1].mark && after.startMs == e.endMs) + if (!joinedBefore || !joinedAfter) stranded++ + if (k == story.parts.size - 1 && joinedBefore && (0 until k).all { j -> entries.getOrNull(i - k + j)?.mark == story.parts[j].mark && entries[i - k + j].seriesId == e.seriesId }) whole++ + } + return StoryCount(parts, stranded, whole) + } + + @Test fun paradox() { + assumeTrue(dir != null && dir.isDirectory) + val programming = SmartChannels.first { it.number == 106 } + assertTrue(programming.storyGrouping) + val committed = plan(File(dir, "schedule-106.json")); val series = pool(File(dir, "episodes-106.json")) + val baseline = SmartChannels.filter { it.number != 106 && File(dir, "schedule-${it.number}.json").exists() && File(dir, "episodes-${it.number}.json").exists() }.map { p -> + replay(plan(File(dir, "schedule-${p.number}.json")), pool(File(dir, "episodes-${p.number}.json")), p, p.storyGrouping, keepCommitted = true) + } + val others = clashesWith(baseline.map { ChannelPlan(it, ScheduleCursor()) }) + val out = StringBuilder("Stage A: story grouping on Paradox. Four weeks of new bookings after the committed plan (ends " + + "${java.time.Instant.ofEpochMilli(committed.endMs).atZone(zone).toLocalDateTime().withNano(0)}), avoiding every other channel's programmes.\n\n") + + out.appendLine("Stories found in Paradox's pool (verified markers only):") + series.sortedBy { it.title }.forEach { s -> + val found = storiesOf(s).stories + val marked = s.episodes.count { partNumber(it.title) != null } + if (marked > 0) out.appendLine(" ${s.title}: ${s.episodes.size} episodes, $marked marked, ${found.size} stories (" + + found.groupingBy { it.parts.size }.eachCount().toSortedMap().entries.joinToString { "${it.value} of ${it.key} parts" } + "), ${marked - found.sumOf { it.parts.size }} marked but unverified, left as they are") + } + out.appendLine() + + val committedCount = storyCount(committed.entries, series) + val committedWho = storyCount(committed.entries, series) { it.title.startsWith("Doctor Who") } + out.appendLine("Committed plan (unchanged): ${committedCount.parts} story parts booked, ${committedCount.stranded} stranded; Doctor Who ${committedWho.parts} parts, ${committedWho.stranded} stranded") + + val before = replay(committed, series, programming, false, others) + val after = replay(committed, series, programming, true, others) + val restarted = replay(committed, series, programming, true, others, restartEvery = 3) + assertEquals("a restart changes nothing", after, restarted) + + val byId = series.associateBy { it.id } + fun decks(grouped: Boolean) = series.filter { programming.mixes(it) }.associate { s -> s.id to (if (grouped) shuffledStories(s, storiesOf(s)) else shuffledEpisodes(s)).map { it.mark } } + val ordered = series.filter { !programming.mixes(it) }.associateBy { it.id } + fun block(e: ScheduleEntry) = dayPartFor(series, programming.dayParts, e.startMs, zone) + val results = mutableMapOf() + for ((label, entries) in listOf("0.99.12, no grouping" to before, "Stage A, grouping" to after)) { + val all = storyCount(entries, series); val who = storyCount(entries, series) { it.title.startsWith("Doctor Who") } + val minutes = entries.groupBy { block(it).second }.mapValues { (_, es) -> es.groupBy { byId.getValue(it.seriesId).title }.mapValues { (_, x) -> x.sumOf { it.media.durationMs } / 60_000.0 } } + out.appendLine("== $label: ${entries.size} programmes") + out.appendLine(" story parts booked ${all.parts}, stranded ${all.stranded}, complete stories ${all.whole}; Doctor Who parts ${who.parts}, stranded ${who.stranded}, complete stories ${who.whole}") + minutes.toSortedMap().forEach { (b, m) -> val total = m.values.sum() + out.appendLine(" $b: " + m.entries.sortedByDescending { it.value }.joinToString { "${it.key} ${pct(it.value / total)}" }) } + val sameDay = entries.groupBy { it.media.item.id }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.startMs - a.startMs < day } } + val twice = entries.zipWithNext().count { (a, b) -> a.seriesId == b.seriesId && "story: part" !in b.why && "air elsewhere then" !in b.why && "airs elsewhere then" !in b.why } + val back = entries.filter { it.seriesId in ordered }.groupBy { it.seriesId }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.mark <= a.mark && b.mark != ordered.getValue(a.seriesId).episodes.first().mark } } + val decks = decks(label.startsWith("Stage A")) + val offDeck = entries.filter { it.seriesId in decks }.groupBy { it.seriesId }.entries.sumOf { (id, es) -> val d = decks.getValue(id); es.zipWithNext().count { (a, b) -> d[(d.indexOf(a.mark) + 1) % d.size] != b.mark } } + val gaps = entries.zipWithNext().count { (a, b) -> a.endMs != b.startMs } + val outside = entries.count { e -> block(e).first.none { it.id == e.seriesId } } + val clashes = entries.count { others(byId.getValue(it.seriesId), it.startMs, it.endMs) } + val never = series.filter { s -> programming.dayParts.any { p -> p.titles.any { seriesKey(it) == seriesKey(s.title) } } && entries.none { it.seriesId == s.id } }.map { it.title } + out.appendLine(" rules: same file within 24 h $sameDay; same show twice running (not a story) $twice; in-order stepping back $back; off the grouped deck $offDeck; gaps $gaps; outside its block $outside; on another channel at the same time $clashes; never aired ${never.ifEmpty { listOf("none") }.joinToString()}") + if (label.startsWith("Stage A")) results.putAll(mapOf("stranded" to all.stranded, "sameDay" to sameDay, "twice" to twice, "back" to back, "offDeck" to offDeck, "gaps" to gaps, "outside" to outside, "clashes" to clashes, "never" to never.size)) + } + out.appendLine("a save and reload every 18 hours gives the identical four weeks: true") + File(dir, "story-grouping-replay.txt").writeText(out.toString()) + println(out) + for (key in listOf("stranded", "sameDay", "twice", "back", "offDeck", "gaps", "outside", "clashes", "never")) assertEquals(key, 0, results[key]) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/StoryGroupingTest.kt b/android/app/src/test/java/tv/orbit/classic/StoryGroupingTest.kt new file mode 100644 index 00000000..9911f47b --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/StoryGroupingTest.kt @@ -0,0 +1,135 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.ZoneOffset + +class StoryGroupingTest { + private val zone = ZoneOffset.UTC + private val day = 24 * 60 * 60_000L + private val start = java.time.LocalDate.of(2026, 11, 10).atStartOfDay(zone).toInstant().toEpochMilli() + private fun ep(show: String, season: Int, episode: Int, title: String, minutes: Int = 45) = PoolEpisode("$show-$season-$episode", "src", EpisodeMark(season, episode), title, minutes * 60_000L) + private fun show(title: String, vararg episodes: PoolEpisode) = PoolSeries(title, title, episodes.toList()) + private fun plain(title: String, count: Int, minutes: Int = 45) = PoolSeries(title, title, (1..count).map { ep(title, 1 + (it - 1) / 10, 1 + (it - 1) % 10, "Story $it", minutes) }) + + /** A Doctor Who-like series: standalones, two-parters, a three-parter, a six-parter and a cliffhanger across seasons. */ + private val who = show("Who", + ep("Who", 1, 1, "Rose"), ep("Who", 1, 2, "Aliens of London (1)"), ep("Who", 1, 3, "World War Three (2)"), ep("Who", 1, 4, "Dalek"), + ep("Who", 1, 5, "Utopia (1)"), ep("Who", 1, 6, "The Sound of Drums (2)"), ep("Who", 1, 7, "Last of the Time Lords (3)"), ep("Who", 1, 8, "Blink"), + ep("Who", 1, 9, "Spyfall (1)", 60), ep("Who", 1, 10, "Spyfall (2)", 60), ep("Who", 1, 11, "Midnight"), ep("Who", 1, 12, "Bad Wolf (1)"), + ep("Who", 2, 1, "The Parting of the Ways (2)"), ep("Who", 2, 2, "Boom Town"), + ep("Who", 2, 3, "Flux (1)", 50), ep("Who", 2, 4, "Flux (2)", 59), ep("Who", 2, 5, "Flux (3)", 49), ep("Who", 2, 6, "Flux (4)", 56), ep("Who", 2, 7, "Flux (5)", 50), ep("Who", 2, 8, "Flux (6)", 59), + ep("Who", 2, 9, "Gridlock"), ep("Who", 2, 10, "Fear Her"), ep("Who", 2, 11, "Love and Monsters"), ep("Who", 2, 12, "42")) + + @Test fun storiesAreFoundFromVerifiedMarkersOnly() { + val found = storiesOf(who).stories.map { story -> story.parts.map { it.title } } + assertEquals(listOf( + listOf("Aliens of London (1)", "World War Three (2)"), + listOf("Utopia (1)", "The Sound of Drums (2)", "Last of the Time Lords (3)"), + listOf("Spyfall (1)", "Spyfall (2)"), + // A season's last episode into the next one's first. + listOf("Bad Wolf (1)", "The Parting of the Ways (2)"), + listOf("Flux (1)", "Flux (2)", "Flux (3)", "Flux (4)", "Flux (5)", "Flux (6)")), found) + } + + @Test fun anythingUncertainIsNotAStory() { + val odd = show("Odd", + // Orphans: a part 2 with no marked part 1, and a part 1 with no part 2. + ep("Odd", 1, 1, "The Blessing Way (2)"), ep("Odd", 1, 2, "Nisei (1)"), ep("Odd", 1, 3, "731"), + // Not consecutive. + ep("Odd", 1, 4, "Gap (1)"), ep("Odd", 1, 6, "Gap (2)"), + // Both halves in one file. + ep("Odd", 1, 7, "Encounter at Farpoint (1), Encounter at Farpoint (2)"), + // A season break that isn't a season's end. + ep("Odd", 2, 3, "Early (1)"), ep("Odd", 3, 1, "Early (2)"), ep("Odd", 2, 9, "Finale"), + // Seven parts is a serial, not a story. + *(1..7).map { ep("Odd", 4, it, "Chapter Part $it") }.toTypedArray()) + assertTrue(storiesOf(odd).stories.isEmpty()) + // "Part One" and "Part II" count as markers. + val worded = show("Worded", ep("Worded", 1, 1, "Descent, Part One"), ep("Worded", 1, 2, "Descent, Part Two"), ep("Worded", 1, 3, "Unity Part I"), ep("Worded", 1, 4, "Unity Part II")) + assertEquals(2, storiesOf(worded).stories.size) + } + + private val parts = listOf(DayPart(6, 18, listOf("Who", "Trek", "Files", "Sliders")), DayPart(18, 6, listOf("Buffy", "Fringe"))) + private val pool = listOf(who, plain("Trek", 80), plain("Files", 60), plain("Sliders", 40), plain("Buffy", 60), plain("Fringe", 60)) + private fun mixedWho(s: PoolSeries) = s.title in setOf("Who", "Trek", "Files", "Sliders") + private fun run(cursor: ScheduleCursor = ScheduleCursor(), from: Long = start, until: Long = start + 28 * day, stories: Boolean = true, pool: List = this.pool, + mixed: (PoolSeries) -> Boolean = ::mixedWho, avoid: ProgrammeClash = { _, _, _ -> false }) = + extendWeighted(pool, cursor, from, until, { TIER_SUPPORTING }, parts, zone, avoid, false, mixed, stories = stories) + + /** Every part airs straight after the part before it, every story airs whole, and none crosses out of its block. */ + private fun assertWhole(entries: List, show: PoolSeries) { + val stories = storiesOf(show) + entries.forEachIndexed { i, entry -> + val episode = show.episodes.firstOrNull { it.mark == entry.mark && entry.seriesId == show.id } ?: return@forEachIndexed + val story = stories.of(episode) ?: return@forEachIndexed + val part = stories.partOf(episode) + if (part > 0) { + val before = entries.getOrNull(i - 1) + assertTrue("${episode.title} at $i isn't straight after its part before", before != null && before.seriesId == show.id && before.mark == story.parts[part - 1].mark && before.endMs == entry.startMs) + } + if (part < story.parts.size - 1 && i < entries.size - 1) assertEquals("${episode.title} isn't followed by its next part", story.parts[part + 1].mark, entries[i + 1].mark) + val hour = java.time.Instant.ofEpochMilli(entry.startMs).atZone(zone).hour + assertTrue("${episode.title} starts outside its block at $hour", hour in 6 until 18) + } + } + + @Test fun aMixedShowAirsEachStoryWholeAndInOrder() { + val plan = run() + assertWhole(plan.entries, who) + val aired = plan.entries.filter { it.seriesId == "Who" }.map { it.mark }.toSet() + // Every story and standalone comes round in four weeks. + assertEquals(who.episodes.map { it.mark }.toSet(), aired) + assertTrue(plan.entries.any { it.why.contains("story: part 6 of 6") }) + } + + @Test fun anInOrderShowCarriesStraightOnThroughItsStory() { + val plan = run(mixed = { false }) + assertWhole(plan.entries, who) + // In order, its progression is untouched: each episode follows the one before in season order. + val marks = plan.entries.filter { it.seriesId == "Who" }.map { it.mark } + marks.zipWithNext().forEach { (a, b) -> assertTrue(b > a || b == who.episodes.first().mark) } + } + + @Test fun aStoryThatWouldCrossItsBlockOrClashWaits() { + // Another channel shows Who all afternoon, so no story may start where any of its parts would meet it. + val busy: ProgrammeClash = { s, from, to -> s.title == "Who" && java.time.Instant.ofEpochMilli(from).atZone(zone).hour.let { it in 12..17 } || + s.title == "Who" && java.time.Instant.ofEpochMilli(to - 1).atZone(zone).hour.let { it in 12..17 } } + val plan = run(avoid = busy) + assertWhole(plan.entries, who) + plan.entries.filter { it.seriesId == "Who" }.forEach { assertFalse(busy(who, it.startMs, it.endMs)) } + } + + @Test fun aTopUpPartWayThroughAStoryCarriesOn() { + val whole = run() + // Cut the plan straight after a part 1, as a top-up would, and carry on from its cursor. + val cut = whole.entries.indexOfFirst { it.why.contains("part 1 of 6") } + val first = run(until = whole.entries[cut].endMs) + assertEquals(whole.entries.take(cut + 1), first.entries) + val second = run(cursor = first.tail, from = first.entries.last().endMs) + assertEquals(whole.entries.drop(cut + 1).take(5), second.entries.take(5)) + assertTrue(second.entries.first().why.contains("story: part 2 of 6")) + } + + @Test fun aStoryCutOffBeforeGroupingNeverRestartsMidWay() { + // Today's committed plans have lone first parts; the deck carries on from one without opening on its part 2. + val stranded = ScheduleCursor(lastSeriesId = "Trek", marks = mapOf("Who" to who.episodes.first { it.title == "Aliens of London (1)" }.mark)) + val plan = run(cursor = stranded) + val whoEntries = plan.entries.filter { it.seriesId == "Who" } + assertFalse(whoEntries.first().mark == who.episodes.first { it.title == "World War Three (2)" }.mark) + assertWhole(plan.entries, who) + } + + @Test fun withoutStoriesNothingChanges() { + // A pool with no markers plans exactly the same with grouping on or off. + val unmarked = pool.map { s -> s.copy(episodes = s.episodes.map { it.copy(title = it.title.replace(Regex("""\s*\(\d\)$"""), "")) }) } + assertEquals(run(pool = unmarked, stories = false), run(pool = unmarked, stories = true)) + } + + @Test fun onlyParadoxGroupsStories() { + assertEquals(listOf(106), SmartChannels.filter { it.storyGrouping }.map { it.number }) + assertTrue(SmartChannels.first { it.number == 106 }.tierWeights != null) + } +} diff --git a/docs/VERIFICATION-0.99.13.md b/docs/VERIFICATION-0.99.13.md new file mode 100644 index 00000000..6f3b3e97 --- /dev/null +++ b/docs/VERIFICATION-0.99.13.md @@ -0,0 +1,84 @@ +# Orbit TV 0.99.13: story-aware episode grouping on Paradox (Living Network Stage A) + +Paul approved Stage A for implementation on 4 November 2026 at 13:38. Installing it needs its own approval. This release changes scheduling on Paradox (106) only. Playback, presentation, assets, the homepage, the Drive-In and the other 29 channels are unchanged. Committed bookings are never rewritten. + +## What's in it + +- **Story detection** (StoryGroups.kt, `storiesOf`). A run of episodes counts as one story only when: + - every title ends with a part marker: "(1)", "(2)" or "Part One", "Part II" and so on; + - the parts are numbered from 1 with no gaps; + - there are 2 to 6 parts; + - each part is the show's next episode, in the same season or running from a season's last episode into the next season's first. That second case covers The Best of Both Worlds and Redux. + + Anything less certain isn't a story and plays exactly as before. That includes: + - orphan parts, such as The X-Files' The Blessing Way (2), whose part 1 Anasazi has no marker; + - runs that aren't consecutive; + - both halves in one file, such as Encounter at Farpoint; + - serials of 7 parts or more. + + Story arcs with no part markers, such as Heaven Sent and the Monks trilogy, would need a hand-checked list. None is included until you approve one. +- **Mixed shows** (Doctor Who, The X-Files, Star Trek: The Next Generation and the other daytime standalones) shuffle each story as a single card in their fixed deck (`shuffledStories`), so its parts sit together in order. The deck is still the same every time, and a saved place still works. +- **Booking** (`extendWeighted`, switched on by `ChannelProgramming.storyGrouping`, which only Paradox sets): + - A story is booked whole: part 1 opens it, and each later part follows straight after, ahead of normal rotation. + - A story is only opened if: + - every part starts inside the block; + - no part clashes with the same show on another channel; + - it ends before the next appointment. + + Otherwise another show takes the slot, and the story waits. + - A mixed show never opens on a later part, so no isolated part 2 or 3 is booked to fill a slot. If a part was cut off before grouping, as in today's committed plans, its deck moves on to the next whole card. + - In-order shows (Buffy, Supernatural, Fringe, Farscape and so on) keep their order. A story's parts follow on back to back instead of waiting for the show's next turn. + - Tallies, tiers, rest rules, clash avoidance and cursors are unchanged. The booking reason says "story: part k of n". +- **Version:** 0.99.13 (versionCode 143). + +## Checks before install + +- **436 unit tests pass** (2 skipped: hand-run replays that need input files). Lint has no errors. +- **Nine new tests in StoryGroupingTest:** + - A Doctor Who-like series finds exactly its 2-, 3- and 6-part stories, including a cliffhanger across a season break. + - Every kind of uncertain link is left alone: orphans, gaps, one-file doubles, mid-season breaks and a 7-part serial. + - A mixed show airs every story whole, in order and inside its block, and every episode still comes round. + - An in-order show keeps its progression. + - A story that would meet the same show on another channel waits. + - A top-up straight after a part 1 carries on with part 2. + - A story cut off before grouping never restarts mid-way. + - With no markers, grouping on and off book identically. + - Only Paradox groups stories. +- **Four-week Paradox replay** on copies of the box's files after the cutover (docs/replays/story-grouping-replay-0.99.13.txt, StoryGroupingReplayTest). It runs from the committed plan, tops up every six hours, and avoids every other channel's programmes. + +| | 0.99.12 | 0.99.13 | +|---|---|---| +| Story parts booked | 80 | 98 | +| Parts stranded (not straight after or before their other parts) | 80 | 0 | +| Complete stories | 0 | 47 (Doctor Who 16) | +| Doctor Who parts stranded | 33 of 33 | 0 of 36 | +| Daytime shares | Doctor Who (2005) 14%, (2023) 14% | the same | +| Same file within 24 h; same show twice running outside a story; in-order stepping back; off its deck; gaps; outside block; clashes; never aired | 0 each | 0 each | + +- **Stories found in Paradox's pool:** + - Doctor Who (2005): 25 (23 two-part, 1 three-part, 1 six-part) + - Doctor Who (2023): 2 + - The X-Files: 18 + - Stargate SG-1: 19 + - Buffy: 9 + - Star Trek: The Next Generation: 8 + - Farscape: 3 + - Fringe, Sliders and Warehouse 13: 2 each + - Supernatural and both Outer Limits: 1 each + - Seven marked episodes were unverified and left as they are: TNG 2, Stargate 1, The X-Files 4. +- **A save and reload every 18 hours** gives the identical four weeks. +- **Committed plan:** kept exactly. Its 26 stranded parts, 13 of them Doctor Who, still air as booked, under the never-rewrite rule. +- **Every other channel:** a four-week replay of all 30 channels was run on 0.99.12 (built from the commit before this change) and on 0.99.13 (docs/replays/replay-fingerprints-0.99.13.txt). Every committed fingerprint is identical. Only 106 differs, as intended. + +## Known limits + +- **On air later:** Paradox's committed plan runs to about 11 November 13:45, so grouping shows on air from then, as the plan rolls forward. +- **Not covered by the replays:** + - The replays use copies of the box's files from the cutover, 4 November 13:12. + - Clash avoidance is against the other channels' replayed plans, which is close to, but not exactly, the box's top-up order. + - Tested here as scheduling logic only. What airs needs checking on the box. +- **Unmarked arcs aren't grouped** until a hand-checked list is approved. + +## Rollback + +Install 0.99.12. The story rule exists only in code, and plan files have the same format, so saved plans load unchanged. Bookings made by 0.99.13 stay as booked. diff --git a/docs/replays/replay-fingerprints-0.99.13.txt b/docs/replays/replay-fingerprints-0.99.13.txt new file mode 100644 index 00000000..331dc2bc --- /dev/null +++ b/docs/replays/replay-fingerprints-0.99.13.txt @@ -0,0 +1,62 @@ +--- 0.99.12 (baseline, HEAD before Stage A) +101 committed=ceabf650e4810201 kept=true fourWeeks=e18874a80beb3a55 programmes=2177 +102 committed=8c81144d3b36e833 kept=true fourWeeks=9709a1ca2f5535ea programmes=1322 +103 committed=7ffea57b7e1cb472 kept=true fourWeeks=647399c086fdb2e4 programmes=1822 +104 committed=e126e9ffa3955107 kept=true fourWeeks=c76da7a762869ce3 programmes=1735 +105 committed=6cade544765d2ea1 kept=true fourWeeks=018a087fb33a0c60 programmes=2557 +106 committed=0288c16eee5a2421 kept=true fourWeeks=78f278c47be573b0 programmes=1153 +107 committed=760efbb2924e4202 kept=true fourWeeks=f5647f529049aab8 programmes=1011 +201 committed=8285c8e353c30297 kept=true fourWeeks=1432d42080236f60 programmes=962 +202 committed=e5d035e62d63daab kept=true fourWeeks=f4e034a1c71ac493 programmes=1132 +203 committed=eda55bfc0c2a0322 kept=true fourWeeks=92598db1029e57a1 programmes=1138 +204 committed=34d70788b01a7f2b kept=true fourWeeks=7075e49beb136fdb programmes=1262 +301 committed=c52f04f716ebb7e6 kept=true fourWeeks=be7f588cb8f45b0b programmes=362 +302 committed=c8682948ae9da547 kept=true fourWeeks=b52216995141a77c programmes=442 +303 committed=69f9f7a1b0a600f7 kept=true fourWeeks=b78067d5fe62f8d5 programmes=419 +304 committed=00ffa5e31b47af35 kept=true fourWeeks=80a6083310a0a39f programmes=493 +305 committed=20bcd7b52807a154 kept=true fourWeeks=560742628cc8bdf3 programmes=503 +306 committed=8f0834ad01578303 kept=true fourWeeks=72af90f39e52b7ec programmes=492 +307 committed=ad3946c4d730d332 kept=true fourWeeks=c148014574309a44 programmes=441 +308 committed=5cd79b96711429dc kept=true fourWeeks=3a1336770d917f73 programmes=514 +309 committed=4a0bd1974ae8edb3 kept=true fourWeeks=10c076d0783c3c78 programmes=498 +401 committed=af07a051503088f4 kept=true fourWeeks=0afb306085ac669e programmes=880 +601 committed=7b828830b81e9e13 kept=true fourWeeks=ea118968a94a8ba9 programmes=2203 +602 committed=ae97602ec57c90a7 kept=true fourWeeks=5a0bcc83098512df programmes=2337 +603 committed=8f07d376dc34ec46 kept=true fourWeeks=869d0c295e7e7995 programmes=2316 +604 committed=67f6f095d1ec3ba8 kept=true fourWeeks=71fca98d5f2d0f6f programmes=3253 +605 committed=63d770ea8815b616 kept=true fourWeeks=b337a4f18b1f2c35 programmes=4508 +611 committed=57b262c3da28ad26 kept=true fourWeeks=40412f13bc54bd40 programmes=2754 +612 committed=8a5ace31156c9d43 kept=true fourWeeks=1675c47b4acc635e programmes=579 +613 committed=d6164e2905c0082f kept=true fourWeeks=db55ae486c4998d1 programmes=521 +614 committed=5c0ab156234c7836 kept=true fourWeeks=4c6f6d2a686b66ba programmes=3844 +--- 0.99.13 +101 committed=ceabf650e4810201 kept=true fourWeeks=e18874a80beb3a55 programmes=2177 +102 committed=8c81144d3b36e833 kept=true fourWeeks=9709a1ca2f5535ea programmes=1322 +103 committed=7ffea57b7e1cb472 kept=true fourWeeks=647399c086fdb2e4 programmes=1822 +104 committed=e126e9ffa3955107 kept=true fourWeeks=c76da7a762869ce3 programmes=1735 +105 committed=6cade544765d2ea1 kept=true fourWeeks=018a087fb33a0c60 programmes=2557 +106 committed=0288c16eee5a2421 kept=true fourWeeks=9bd2fb23de4d7feb programmes=1150 +107 committed=760efbb2924e4202 kept=true fourWeeks=f5647f529049aab8 programmes=1011 +201 committed=8285c8e353c30297 kept=true fourWeeks=1432d42080236f60 programmes=962 +202 committed=e5d035e62d63daab kept=true fourWeeks=f4e034a1c71ac493 programmes=1132 +203 committed=eda55bfc0c2a0322 kept=true fourWeeks=92598db1029e57a1 programmes=1138 +204 committed=34d70788b01a7f2b kept=true fourWeeks=7075e49beb136fdb programmes=1262 +301 committed=c52f04f716ebb7e6 kept=true fourWeeks=be7f588cb8f45b0b programmes=362 +302 committed=c8682948ae9da547 kept=true fourWeeks=b52216995141a77c programmes=442 +303 committed=69f9f7a1b0a600f7 kept=true fourWeeks=b78067d5fe62f8d5 programmes=419 +304 committed=00ffa5e31b47af35 kept=true fourWeeks=80a6083310a0a39f programmes=493 +305 committed=20bcd7b52807a154 kept=true fourWeeks=560742628cc8bdf3 programmes=503 +306 committed=8f0834ad01578303 kept=true fourWeeks=72af90f39e52b7ec programmes=492 +307 committed=ad3946c4d730d332 kept=true fourWeeks=c148014574309a44 programmes=441 +308 committed=5cd79b96711429dc kept=true fourWeeks=3a1336770d917f73 programmes=514 +309 committed=4a0bd1974ae8edb3 kept=true fourWeeks=10c076d0783c3c78 programmes=498 +401 committed=af07a051503088f4 kept=true fourWeeks=0afb306085ac669e programmes=880 +601 committed=7b828830b81e9e13 kept=true fourWeeks=ea118968a94a8ba9 programmes=2203 +602 committed=ae97602ec57c90a7 kept=true fourWeeks=5a0bcc83098512df programmes=2337 +603 committed=8f07d376dc34ec46 kept=true fourWeeks=869d0c295e7e7995 programmes=2316 +604 committed=67f6f095d1ec3ba8 kept=true fourWeeks=71fca98d5f2d0f6f programmes=3253 +605 committed=63d770ea8815b616 kept=true fourWeeks=b337a4f18b1f2c35 programmes=4508 +611 committed=57b262c3da28ad26 kept=true fourWeeks=40412f13bc54bd40 programmes=2754 +612 committed=8a5ace31156c9d43 kept=true fourWeeks=1675c47b4acc635e programmes=579 +613 committed=d6164e2905c0082f kept=true fourWeeks=db55ae486c4998d1 programmes=521 +614 committed=5c0ab156234c7836 kept=true fourWeeks=4c6f6d2a686b66ba programmes=3844 diff --git a/docs/replays/story-grouping-replay-0.99.13.txt b/docs/replays/story-grouping-replay-0.99.13.txt new file mode 100644 index 00000000..6fe323b9 --- /dev/null +++ b/docs/replays/story-grouping-replay-0.99.13.txt @@ -0,0 +1,31 @@ +Stage A: story grouping on Paradox. Four weeks of new bookings after the committed plan (ends 2026-11-11T13:45:59), avoiding every other channel's programmes. + +Stories found in Paradox's pool (verified markers only): + Buffy the Vampire Slayer: 144 episodes, 18 marked, 9 stories (9 of 2 parts), 0 marked but unverified, left as they are + Doctor Who (2005): 153 episodes, 55 marked, 25 stories (23 of 2 parts, 1 of 3 parts, 1 of 6 parts), 0 marked but unverified, left as they are + Doctor Who (2023): 16 episodes, 4 marked, 2 stories (2 of 2 parts), 0 marked but unverified, left as they are + Farscape: 90 episodes, 7 marked, 3 stories (2 of 2 parts, 1 of 3 parts), 0 marked but unverified, left as they are + Fringe: 100 episodes, 4 marked, 2 stories (2 of 2 parts), 0 marked but unverified, left as they are + Sliders: 88 episodes, 4 marked, 2 stories (2 of 2 parts), 0 marked but unverified, left as they are + Star Trek: The Next Generation: 176 episodes, 18 marked, 8 stories (8 of 2 parts), 2 marked but unverified, left as they are + Stargate SG-1: 213 episodes, 41 marked, 19 stories (17 of 2 parts, 2 of 3 parts), 1 marked but unverified, left as they are + Supernatural: 327 episodes, 2 marked, 1 stories (1 of 2 parts), 0 marked but unverified, left as they are + The Outer Limits: 152 episodes, 2 marked, 1 stories (1 of 2 parts), 0 marked but unverified, left as they are + The Outer Limits (1995): 154 episodes, 2 marked, 1 stories (1 of 2 parts), 0 marked but unverified, left as they are + The X-Files: 217 episodes, 42 marked, 18 stories (16 of 2 parts, 2 of 3 parts), 4 marked but unverified, left as they are + Warehouse 13: 64 episodes, 4 marked, 2 stories (2 of 2 parts), 0 marked but unverified, left as they are + +Committed plan (unchanged): 26 story parts booked, 26 stranded; Doctor Who 13 parts, 13 stranded +== 0.99.12, no grouping: 913 programmes + story parts booked 80, stranded 80, complete stories 0; Doctor Who parts 33, stranded 33, complete stories 0 + block 18-23: Supernatural 30%, Buffy the Vampire Slayer 30%, Angel 20%, Fringe 20% + block 23-6: The X-Files 25%, The Outer Limits (1995) 17%, Torchwood 17%, Farscape 17%, The Outer Limits 16%, Twin Peaks 8% + block 6-18: The X-Files 14%, Doctor Who (2023) 14%, Star Trek: The Next Generation 14%, Doctor Who (2005) 14%, Stargate SG-1 9%, Sliders 9%, The Twilight Zone 9%, Eureka 9%, Warehouse 13 9% + rules: same file within 24 h 0; same show twice running (not a story) 0; in-order stepping back 0; off the grouped deck 0; gaps 0; outside its block 0; on another channel at the same time 0; never aired none +== Stage A, grouping: 911 programmes + story parts booked 98, stranded 0, complete stories 47; Doctor Who parts 36, stranded 0, complete stories 16 + block 18-23: Supernatural 30%, Buffy the Vampire Slayer 30%, Angel 20%, Fringe 20% + block 23-6: The X-Files 25%, The Outer Limits (1995) 17%, Torchwood 17%, Farscape 17%, The Outer Limits 16%, Twin Peaks 8% + block 6-18: The X-Files 14%, Doctor Who (2023) 14%, Star Trek: The Next Generation 14%, Doctor Who (2005) 14%, Sliders 9%, The Twilight Zone 9%, Eureka 9%, Warehouse 13 9%, Stargate SG-1 9% + rules: same file within 24 h 0; same show twice running (not a story) 0; in-order stepping back 0; off the grouped deck 0; gaps 0; outside its block 0; on another channel at the same time 0; never aired none +a save and reload every 18 hours gives the identical four weeks: true