0.99.13: story-aware episode grouping on Paradox (Living Network Stage A)
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m54s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m31s

Multi-part stories, verified from part markers and consecutive episodes only, are booked whole and back to back on
Paradox's weighted blocks; mixed decks keep each story as one card; no isolated later part is booked. Other channels
unchanged (fingerprints identical); committed bookings untouched.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 13:50:59 +00:00
co-authored by Claude Opus 5.5
parent a0ae85f669
commit 6343e8d254
12 changed files with 591 additions and 20 deletions
@@ -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<String> = emptySet()) {
val withdrawn: Set<String> = 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<PoolSeries>, cursor: ScheduleCursor, from
/** Files aired shortly before [fromMs], for the same-file guard across a top-up. */
recentFiles: Map<String, Long> = 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<PoolSeries>, 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<String, ShowStories>()
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<String, PoolEpisode>()
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<PoolSeries>, at: Long) = available.any { film -> film.isFilm && shown[film.id]?.let { at - it < ONCE_A_NIGHT_MS } == true }
fun partAt(at: Long): Triple<List<PoolSeries>, String, DayPart?> {
val first = dayPartFor(pool, dayParts, at, zone)
@@ -637,8 +659,22 @@ internal fun extendWeighted(pool: List<PoolSeries>, 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<PoolSeries>, 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<PoolSeries>, cursor: ScheduleCursor, from
*/
internal fun extendByBlock(pool: List<PoolSeries>, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, weightOf: (PoolSeries) -> Double,
dayParts: List<DayPart>, zone: java.time.ZoneId, avoid: ProgrammeClash, shuffle: Boolean, mixed: (PoolSeries) -> Boolean, finishTogether: Boolean,
recentFiles: Map<String, Long> = emptyMap(), runBefore: Int = 0, fileRestMs: Long = SAME_FILE_MS): ChannelPlan {
recentFiles: Map<String, Long> = 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<ScheduleEntry>()
@@ -696,7 +736,7 @@ internal fun extendByBlock(pool: List<PoolSeries>, 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)
}
@@ -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 })
@@ -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)
@@ -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()) {
@@ -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<PoolEpisode>) {
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<Story>) {
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<Story>()
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<PoolEpisode> {
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()
}