Shorts grouping engine: short cartoons in slots of about half an hour

Episodes of 8 minutes or less gather into a slot aiming at the next :00 or :30 at least 15 minutes on. Every short stays its
own schedule entry (own start, runtime, episode, show), chosen by the usual turns, rest and clash rules, never the same show
twice in a row; a slot only adds a tag for presentation. A slot ends where its last short ends: no dead air, no stretched
runtime. A slot of one is an ordinary programme. Only new planning; nothing booked is moved or cut. Tots (Tots Little Mix by
day, Tots Story Time in the evening) and ToonZ (Cartoon Shorts) switch it on; it doesn't depend on custom channels.
ShortsReplayTest replays seven days of the box's Tots and ToonZ before and after. Not yet shown in the guide.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-06 04:22:38 +00:00
co-authored by Claude Opus 5.5
parent 8737a60a20
commit b51c59586b
6 changed files with 309 additions and 21 deletions
@@ -78,7 +78,9 @@ internal data class ChannelProgramming(val number: Int, val name: String, val se
* 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) {
val storyGrouping: Boolean = false,
/** Shorts grouping (Paul, 6 November 2026): short episodes gathered into slots of about half an hour. Null for none. */
val shorts: ShortsRule? = null) {
/** The items taken off this channel on the server signed in to: [withdrawnOnOriginal] there, none anywhere else. */
val withdrawn: Set<String> get() = if (Workspaces.originalOpen) withdrawnOnOriginal else emptySet()
/** A show's weight here, by its tier (a show the brief doesn't name counts as supporting), scaled by [catalogueScaleHours]. */
@@ -201,7 +203,7 @@ internal val SmartChannels = listOf(
// Reads every show on its list, as the other curated channels do. Its old limit of 20 dates from when the list was short.
ChannelProgramming(201, "Terra", TerraShows, seriesCount = TerraShows.size, finishTogether = true, exactTitles = true, dayParts = TerraDayParts, storyGrouping = true),
ChannelProgramming(TOTS_NUMBER, "Tots", TotsShows, seriesCount = 40, finishTogether = true, exactTitles = true, dayParts = TotsDayParts, shuffleEpisodes = true,
tierWeights = TotsTiers, catalogueScaleHours = CATALOGUE_SCALE_HOURS, storyGrouping = true),
tierWeights = TotsTiers, catalogueScaleHours = CATALOGUE_SCALE_HOURS, storyGrouping = true, shorts = TotsShorts),
ChannelProgramming(106, "Paradox", ParadoxShows, seriesCount = 20, finishTogether = true, exactTitles = true, dayParts = ParadoxDayParts, shuffleTitles = (ParadoxStandalones + ParadoxAdult).toSet(),
tierWeights = ParadoxTiers, storyGrouping = true)) +
ChannelPresets.filter { it.smartOnly }.map { ChannelProgramming(it.number, it.name, it.searches, seriesCount = if (it.films) it.searches.size else maxOf(60, it.searches.size), finishTogether = !it.films, exactTitles = true,
@@ -209,7 +211,8 @@ internal val SmartChannels = listOf(
suggestionRules = SmartChannelRules[it.number].orEmpty(), dayParts = SmartChannelParts[it.number].orEmpty(), shuffleTitles = SmartChannelMixed[it.number].orEmpty(),
channelFilms = if (it.number == 401) PpvSunday else emptyList(), tierWeights = SmartChannelTiers[it.number], adaptiveFilmRest = it.number in AdaptiveFilmRestChannels,
catalogueScaleHours = if (it.number in CatalogueScaledChannels) CATALOGUE_SCALE_HOURS else null,
catalogueScaleFloor = CatalogueScaleFloors[it.number] ?: MIN_CATALOGUE_SCALE, storyGrouping = it.number in StoryGroupingChannels) }
catalogueScaleFloor = CatalogueScaleFloors[it.number] ?: MIN_CATALOGUE_SCALE, storyGrouping = it.number in StoryGroupingChannels,
shorts = if (it.number == 605) ToonZShorts else null) }
/**
* Living Network Stage E: story grouping beyond Paradox, one channel at a time. Heroes first (4 November 2026): 119 story parts a
@@ -291,7 +294,9 @@ internal data class ScheduleEntry(val seriesId: String, val mark: EpisodeMark, v
/** Why the planner chose this, for diagnostics only. Empty for programmes planned before reasons were kept. */
val why: String = "",
/** The block's or event's presentation key, saved when the programme is booked (see [DayPart.key]). Empty for ordinary programmes and older bookings. */
val presentation: String = "") {
val presentation: String = "",
/** The shorts slot this programme was booked in ([shortsTag]), or empty. Presentation only: the programme is still its own entry. */
val group: String = "") {
val endMs get() = startMs + media.durationMs
}
@@ -654,8 +659,11 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
/** 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,
/** Story-aware grouping ([ChannelProgramming.storyGrouping]): multi-part stories are booked whole, in order, back to back. */
stories: Boolean = false): ChannelPlan {
stories: Boolean = false,
/** Shorts grouping ([ShortsRule]), or null for none. */
shorts: ShortsRule? = null): ChannelPlan {
val marks = cursor.marks.toMutableMap()
var slot: ShortsSlot? = null
val shown = cursor.filmShown.toMutableMap()
val tallies = cursor.tallies.mapValues { it.value.toMutableMap() }.toMutableMap()
val runStarted = cursor.runStarted.toMutableMap()
@@ -762,7 +770,11 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
}
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 open = unclashed.ifEmpty { available }.let { shows -> if (stories) shows.filter(::storyFits).ifEmpty { shows } else shows }
// Inside a shorts slot only the shorts that fit it take part; none fits, and the slot closes where it is.
val inSlot = slot?.let { s -> unclashed.filter { it.id != last && s.takes(start, following(it).durationMs) } }.orEmpty()
if (inSlot.isEmpty()) slot = null
val clear = if (continuing == null && inSlot.isNotEmpty()) inSlot else open
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.
@@ -789,7 +801,8 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
(if (story != null) "; story: part 1 of ${story.first}, booked whole" else "") +
(if (part?.premiere == true && series in available) "; premiere: first airing on Orbit" 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 tag = shortsTagFor(shorts, slot, series, episode, series in available, start, zone).also { slot = it.second }.first
entries += ScheduleEntry(series.id, episode.mark, ScheduledMedia(item, episode.sourceId, episode.durationMs), start, why + if (tag.isEmpty()) "" else "; shorts slot", if (series in available) part?.key.orEmpty() else "", tag)
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
@@ -803,7 +816,7 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
last = series.id
start += episode.durationMs
}
return ChannelPlan(entries, ScheduleCursor(last, marks, shown, cursor.blockLast, tallies, runStarted))
return ChannelPlan(withoutLoneShorts(entries), ScheduleCursor(last, marks, shown, cursor.blockLast, tallies, runStarted))
}
/**
@@ -813,7 +826,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, stories: Boolean = false): ChannelPlan {
recentFiles: Map<String, Long> = emptyMap(), runBefore: Int = 0, fileRestMs: Long = SAME_FILE_MS, stories: Boolean = false, shorts: ShortsRule? = null): ChannelPlan {
fun weightedAt(at: Long) = dayPartFor(pool, dayParts, at, zone).third?.weighted != false
val hour = 60 * 60_000L
val entries = mutableListOf<ScheduleEntry>()
@@ -826,10 +839,10 @@ 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, stories)
extendWeighted(pool, tail, start, minOf(end, untilMs), weightOf, dayParts, zone, avoid, shuffle, mixed, recent, fileRestMs, stories, shorts)
} 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, stories = stories).let { plan ->
extendSchedule(pool, tail, start, minOf(end, untilMs), null, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, stories = stories, shorts = shorts).let { plan ->
// Equal turns know nothing of tallies; they wait unchanged for the next weighted stretch.
plan.copy(tail = plan.tail.copy(tallies = tail.tallies, runStarted = tail.runStarted))
}
@@ -855,7 +868,9 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
/** Film channels only: see [ChannelProgramming.adaptiveFilmRest]. */
adaptiveRest: Boolean = false,
/** Story-aware mixing (Paul, 5 November 2026: part ones first, everywhere): a mixed show keeps each multi-part story whole and in order in its deck. */
stories: Boolean = false): ChannelPlan {
stories: Boolean = false,
/** Shorts grouping ([ShortsRule]), or null for none. */
shorts: ShortsRule? = null): ChannelPlan {
require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() })
if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs, dayParts, zone, avoid, adaptiveRest)
val marks = cursor.marks.toMutableMap()
@@ -892,6 +907,7 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
val mix = running(show)
return mix[(mix.indexOfFirst { it.mark == marks[show.id] } + 1) % mix.size]
}
var slot: ShortsSlot? = null
while (start < untilMs) {
val (available, block, part) = partAt(start)
// Shows only wait for others in the same block, or a daytime show could stand idle for an evening one.
@@ -902,7 +918,10 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
val waiting = mutableListOf<String>(); val elsewhere = mutableListOf<String>()
// A block carries on from its own last show. Starting from the channel's last show would begin each block at the same place every day.
val after = if (blockRotation) blockLast[block] ?: last else last
val picked = turnOrder(pool, after).firstOrNull { show ->
// Inside a shorts slot, the next short in turn that fits it; none fits, and the slot closes where it is.
val inSlot = slot?.let { open -> turnOrder(pool, after).firstOrNull { show -> show.id != last && allowed(show) && open.takes(start, following(show).durationMs) && !avoid(show, start, start + following(show).durationMs) } }
if (inSlot == null) slot = null
val picked = inSlot ?: turnOrder(pool, after).firstOrNull { show ->
when {
!allowed(show) -> { if (show in available) waiting += show.title; false }
avoid(show, start, start + following(show).durationMs) -> { elsewhere += show.title; false }
@@ -952,7 +971,8 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
}
val item = if (series.isFilm) SampleItem(series.title, "Movie", episode.durationMs / 60_000, "", episode.id, episode.durationMs) else scheduledItem(series.title, episode)
val media = ScheduledMedia(item, episode.sourceId, episode.durationMs)
entries += ScheduleEntry(series.id, episode.mark, media, start, why, if (series in available) part?.key.orEmpty() else "")
val tag = shortsTagFor(shorts, slot, series, episode, series in available, start, zone).also { slot = it.second }.first
entries += ScheduleEntry(series.id, episode.mark, media, start, why + if (tag.isEmpty()) "" else "; shorts slot", if (series in available) part?.key.orEmpty() else "", tag)
marks[series.id] = episode.mark
run = if (series.id == last) run + 1 else 1
last = series.id
@@ -960,7 +980,7 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
if (series.isFilm) shown[series.id] = start
start += episode.durationMs
}
return ChannelPlan(entries, ScheduleCursor(last, marks, shown, blockLast))
return ChannelPlan(withoutLoneShorts(entries), ScheduleCursor(last, marks, shown, blockLast))
}
internal fun scheduledItem(seriesTitle: String, episode: PoolEpisode) = SampleItem(
@@ -993,7 +1013,9 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
/** Weighted channels only: see [extendWeighted]. */
fileRestMs: Long = SAME_FILE_MS,
/** Weighted channels only: see [ChannelProgramming.storyGrouping]. */
stories: Boolean = false): ChannelPlan? {
stories: Boolean = false,
/** See [ChannelProgramming.shorts]. */
shorts: ShortsRule? = null): 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
@@ -1001,8 +1023,8 @@ 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, stories)
} else extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow, blockRotation, adaptiveRest, stories = stories)
extendByBlock(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, weightOf, dayParts, zone, avoid, shuffle, mixed, finishTogether, recent, trailing, fileRestMs, stories, shorts)
} else extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow, blockRotation, adaptiveRest, stories = stories, shorts = shorts)
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
}
@@ -310,7 +310,7 @@ internal class ChannelScheduler(private val store: ScheduleStore,
}
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, stories = programming.storyGrouping) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping, shorts = programming.shorts) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
if (plan !== existing) store.savePlan(userId, number, plan)
// Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence.
if (plan !== existing) runCatching {
@@ -116,7 +116,7 @@ internal class ScheduleStore(private val directory: File) {
fun savePlan(userId: String, number: Int, plan: ChannelPlan) {
val entries = JSONArray()
plan.entries.forEach { e -> entries.put(JSONObject().put("s", e.seriesId).put("n", JSONArray().put(e.mark.season).put(e.mark.episode))
.put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation) }) }
.put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation); if (e.group.isNotEmpty()) row.put("g", e.group) }) }
write(file("schedule", number), root(userId, number).put("tail", encodeCursor(plan.tail)).put("entries", entries))
}
/** Changes whenever the plan file is written, so a plan already read can be reused until then. */
@@ -130,7 +130,9 @@ internal class ScheduleStore(private val directory: File) {
val item = SampleItem(o.getString("t"), o.optString("k", "Episode").also { require(it in listOf("Episode", "Movie")) }, duration / 60_000, "", validId(o.getString("i")), duration)
ScheduleEntry(validId(o.getString("s")), mark, ScheduledMedia(item, validId(o.getString("c")), duration), o.getLong("a"), o.optString("w").take(MAX_REASON_CHARS),
// Absent in plans booked before presentations were kept; anything unexpected is ignored rather than refused.
o.optString("p").takeIf { PRESENTATION_KEY.matches(it) }.orEmpty())
o.optString("p").takeIf { PRESENTATION_KEY.matches(it) }.orEmpty(),
// A shorts slot's tag: absent before slots existed, and anything unexpected is ignored.
o.optString("g").takeIf { SHORTS_TAG.matches(it) }.orEmpty())
}
require(entries.zipWithNext().all { (first, second) -> first.endMs <= second.startMs })
ChannelPlan(entries, decodeCursor(root.getJSONObject("tail")))
@@ -0,0 +1,90 @@
package tv.orbit.classic
import java.time.Instant
import java.time.ZoneId
/**
* Shorts grouping (Paul, 6 November 2026): short cartoons gathered into slots of about half an hour, instead of one
* five-minute short wedged between two longer shows. The engine belongs to the planner, so any channel can switch it on
* (Tots and ToonZ do; custom channels will use it for their "blocks" style), and nothing about it depends on custom channels.
*
* The individual episodes stay the schedule: each short is booked as its own programme, with its own start, runtime,
* episode and show, by the same turns, rest and "airing elsewhere" rules as everything else. A slot only adds a shared tag
* ([ScheduleEntry.group]), so the guide can show the shorts together. Catch Up, progress, Kids rules and the Director's Chair
* still see every short. A slot is only ever filled at the end of the plan; nothing already booked is moved or cut.
*
* Inside a slot the shows take turns as everywhere else, and never the same show twice in a row; when no other short fits,
* the slot closes. A slot of one short isn't a slot ([withoutLoneShorts]).
*
* How a slot ends: it aims at the next :00 or :30 at least [SHORTS_SLOT_MIN_MS] away, and takes shorts in turn while the next
* one ends by that time, or within [SHORTS_OVERRUN_MS] of it. When none fits, the slot closes where its last short ends and
* the next programme starts straight after: no dead air, and no runtime is stretched. So a slot can finish a few minutes
* before or after the half hour, and its length in the guide is always what its shorts actually run.
*/
internal const val SHORTS_MAX_MS = 8 * 60_000L
internal const val SHORTS_SLOT_MIN_MS = 15 * 60_000L
internal const val SHORTS_OVERRUN_MS = 2 * 60_000L
/** A channel's shorts slots: what each is called at a given time. */
internal class ShortsRule(val label: (startMs: Long, zone: ZoneId) -> String)
/** Tots: calm, story-led evenings, a livelier mix by day (Paul, 6 November 2026). */
internal val TotsShorts = ShortsRule { at, zone -> if (Instant.ofEpochMilli(at).atZone(zone).hour.let { it >= 17 || it < 6 }) "Tots Story Time" else "Tots Little Mix" }
internal val ToonZShorts = ShortsRule { _, _ -> "Cartoon Shorts" }
internal fun isShort(durationMs: Long) = durationMs in 1..SHORTS_MAX_MS
/** One slot being filled: when it aims to end, and the tag its shorts carry. */
internal class ShortsSlot(val startMs: Long, val targetMs: Long, val label: String) {
val tag get() = shortsTag(startMs, label)
/** Whether a short of [durationMs] starting at [atMs] belongs in this slot. */
fun takes(atMs: Long, durationMs: Long) = isShort(durationMs) && atMs < targetMs && atMs + durationMs <= targetMs + SHORTS_OVERRUN_MS
}
/** A slot opened by a short starting at [startMs]: aiming for the next :00 or :30 at least [SHORTS_SLOT_MIN_MS] on. */
internal fun openShortsSlot(rule: ShortsRule, startMs: Long, zone: ZoneId): ShortsSlot {
val half = 30 * 60_000L
val local = Instant.ofEpochMilli(startMs).atZone(zone)
val dayStart = local.toLocalDate().atStartOfDay(zone).toInstant().toEpochMilli()
var target = dayStart + ((startMs - dayStart) / half + 1) * half
while (target - startMs < SHORTS_SLOT_MIN_MS) target += half
return ShortsSlot(startMs, target, rule.label(startMs, zone))
}
internal fun shortsTag(startMs: Long, label: String) = "shorts|$startMs|$label"
/** What a saved tag may look like. */
internal val SHORTS_TAG = Regex("shorts\\|\\d{1,15}\\|[A-Za-z' ]{1,40}")
/** A slot as it stands in a plan: its title, when it starts and ends, and the shows in it, all from what was booked. */
internal class ShortsBlock(val label: String, val startMs: Long, val endMs: Long, val entries: List<ScheduleEntry>) {
/** The shows in the slot, in the order they first air in it. */
val shows: List<String> get() = entries.map { guideTitleParts(it.media.item.title).first }.distinct()
val title get() = "$label: " + shows.take(3).joinToString(", ") + if (shows.size > 3) " and more" else ""
}
/** The shorts slots in [entries]: consecutive programmes sharing a tag. Anything without one isn't part of a slot. */
internal fun shortsBlocks(entries: List<ScheduleEntry>): List<ShortsBlock> = buildList {
var run = mutableListOf<ScheduleEntry>()
fun close() { run.firstOrNull()?.let { first -> add(ShortsBlock(first.group.split('|').getOrElse(2) { "Shorts" }, first.startMs, run.last().endMs, run.toList())) }; run = mutableListOf() }
for (entry in entries) {
if (entry.group.isEmpty() || (run.isNotEmpty() && (run.last().group != entry.group || run.last().endMs != entry.startMs))) close()
if (entry.group.isNotEmpty()) run += entry
}
close()
}
/**
* The tag for a programme just chosen, and the slot that's open after it. A short opens a slot (or carries on the one that
* fits it); anything else, or a short from outside the block's own shows, closes it.
*/
internal fun shortsTagFor(rule: ShortsRule?, slot: ShortsSlot?, series: PoolSeries, episode: PoolEpisode, inBlock: Boolean, startMs: Long, zone: ZoneId): Pair<String, ShortsSlot?> {
if (rule == null || series.isFilm || !inBlock || !isShort(episode.durationMs)) return "" to null
val open = slot?.takeIf { it.takes(startMs, episode.durationMs) } ?: openShortsSlot(rule, startMs, zone)
return open.tag to open
}
/** A slot that ended up holding one short isn't a slot: that short airs as an ordinary programme. */
internal fun withoutLoneShorts(entries: List<ScheduleEntry>): List<ScheduleEntry> {
val sizes = entries.filter { it.group.isNotEmpty() }.groupingBy { it.group }.eachCount()
return if (sizes.values.none { it == 1 }) entries else entries.map { if (it.group.isNotEmpty() && sizes[it.group] == 1) it.copy(group = "", why = it.why.removeSuffix("; shorts slot")) else it }
}