Shorts grouping engine: short cartoons in slots of about half an hour
Ported from the release line (not yet installed or shown in the guide). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -732,8 +737,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()
|
||||
@@ -840,7 +848,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.
|
||||
@@ -867,7 +879,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
|
||||
@@ -881,7 +894,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))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -891,7 +904,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>()
|
||||
@@ -904,10 +917,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))
|
||||
}
|
||||
@@ -935,7 +948,9 @@ internal fun extendSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor, from
|
||||
/** Film channels only: see [FixedSlot]. */
|
||||
fixed: List<FixedSlot> = emptyList(), held: (PoolSeries, Long) -> 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, fixed, held)
|
||||
val marks = cursor.marks.toMutableMap()
|
||||
@@ -972,6 +987,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.
|
||||
@@ -982,7 +998,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 }
|
||||
@@ -1032,7 +1051,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
|
||||
@@ -1040,7 +1060,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(
|
||||
@@ -1075,7 +1095,9 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
|
||||
/** Weighted channels only: see [ChannelProgramming.storyGrouping]. */
|
||||
stories: Boolean = false,
|
||||
/** Film channels only: see [FixedSlot]. */
|
||||
fixed: List<FixedSlot> = emptyList(), held: (PoolSeries, Long) -> Boolean = { _, _ -> false }): ChannelPlan? {
|
||||
fixed: List<FixedSlot> = emptyList(), held: (PoolSeries, Long) -> 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
|
||||
@@ -1083,8 +1105,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, fixed, held, 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, fixed, held, stories, shorts = shorts)
|
||||
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
|
||||
}
|
||||
|
||||
|
||||
@@ -357,7 +357,7 @@ internal class ChannelScheduler(private val store: ScheduleStore,
|
||||
(if (number == PREMIERE_NUMBER && premieres.isNotEmpty()) approvedDebutSlots(premieres) else emptyList())
|
||||
val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it + premiereRotation(number, premieres, now).filter { p -> it.none { s -> s.id == p.id } }, 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,
|
||||
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping, shorts = programming.shorts,
|
||||
fixed = fixed, held = seasonalHeld().let { seasonal -> val premiere = premiereHeld(number); { f: PoolSeries, at: Long -> seasonal(f, at) || premiere(f, at) } })
|
||||
?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
|
||||
if (plan !== existing) plan.entries.filter { (it.why.startsWith(ADVENT_WHY) || it.why.startsWith(NAUGHTY_WHY)) && existing?.entries?.none { e -> e.startMs == it.startMs } != false }
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
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
|
||||
|
||||
/**
|
||||
* Shorts grouping's before/after (Paul, 6 November 2026): seven days of new bookings after Tots' and ToonZ's committed plans,
|
||||
* from copies of the box's files, without shorts slots and with them, avoiding every other channel's programmes as the box
|
||||
* does. Run by hand:
|
||||
* ORBIT_REPLAY_DIR=<copies of the box's schedule folder> ./gradlew :app:testDebugUnitTest --tests '*ShortsReplayTest*'
|
||||
* Writes shorts-replay.txt there, and fails on any broken rule: a committed programme changed, a gap, a runtime that isn't
|
||||
* the episode's own, or a short slot member that isn't its own entry.
|
||||
*/
|
||||
class ShortsReplayTest {
|
||||
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<PoolSeries> {
|
||||
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<PoolSeries>, programming: ChannelProgramming, shorts: ShortsRule?, avoid: ProgrammeClash): List<ScheduleEntry> {
|
||||
var current = committed
|
||||
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
|
||||
val end = committed.endMs + 7 * day
|
||||
val all = committed.entries.toMutableList()
|
||||
while (now < end) {
|
||||
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 = programming.storyGrouping, shorts = shorts) ?: 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 exactly", committed.entries, all.take(committed.entries.size))
|
||||
return all.filter { it.startMs >= committed.endMs && it.startMs < end }
|
||||
}
|
||||
|
||||
private fun clock(ms: Long) = java.time.Instant.ofEpochMilli(ms).atZone(zone).let { "%s %02d:%02d".format(it.dayOfWeek.toString().take(3).lowercase().replaceFirstChar(Char::uppercase), it.hour, it.minute) }
|
||||
private fun mins(ms: Long) = "%.1f".format(ms / 60_000.0)
|
||||
private fun onHalfHour(ms: Long) = java.time.Instant.ofEpochMilli(ms).atZone(zone).let { t -> val m = t.minute % 30; m <= 2 || m >= 28 }
|
||||
|
||||
@Test fun sevenDaysBeforeAndAfter() {
|
||||
assumeTrue(dir != null && File(dir, "schedule-614.json").exists())
|
||||
val out = StringBuilder("Shorts grouping: seven days of new bookings after each committed plan, from the box's files (${java.time.LocalDate.now()}).\n")
|
||||
val plans = dir!!.listFiles().orEmpty().mapNotNull { f -> Regex("schedule-(\\d+)\\.json").matchEntire(f.name)?.groupValues?.get(1)?.toInt()?.let { it to plan(f) } }.toMap()
|
||||
for ((number, rule) in listOf(TOTS_NUMBER to TotsShorts, 605 to ToonZShorts)) {
|
||||
val programming = SmartChannels.single { it.number == number }
|
||||
val committed = plans.getValue(number)
|
||||
val series = pool(File(dir, "episodes-$number.json"))
|
||||
val avoid = clashesWith(plans.filterKeys { it != number }.values.toList())
|
||||
val before = replay(committed, series, programming, null, avoid)
|
||||
val after = replay(committed, series, programming, rule, avoid)
|
||||
val byId = series.associateBy { it.id }
|
||||
fun name(e: ScheduleEntry) = byId[e.seriesId]?.title ?: e.seriesId
|
||||
// The rules: back to back, each its episode's own runtime, every short in a slot its own entry.
|
||||
for ((label, run) in listOf("before" to before, "after" to after)) {
|
||||
assertTrue("${programming.name} $label: no gaps or overlaps", run.zipWithNext().all { (a, b) -> a.endMs == b.startMs })
|
||||
assertTrue("${programming.name} $label: runtimes are the episodes' own", run.all { e -> byId[e.seriesId]?.episodes?.firstOrNull { it.mark == e.mark }?.durationMs == e.media.durationMs })
|
||||
}
|
||||
val blocks = shortsBlocks(after)
|
||||
assertTrue(blocks.all { b -> b.entries.all { isShort(it.media.durationMs) } && b.entries.zipWithNext().all { (a, c) -> a.endMs == c.startMs } })
|
||||
val shortsBefore = before.count { isShort(it.media.durationMs) }; val shortsAfter = after.count { isShort(it.media.durationMs) }
|
||||
val loose = after.count { isShort(it.media.durationMs) && it.group.isEmpty() }
|
||||
val lengths = blocks.map { it.endMs - it.startMs }.sorted()
|
||||
val repeats = blocks.sumOf { b -> b.entries.zipWithNext().count { (a, c) -> a.seriesId == c.seriesId } }
|
||||
out.append("\n${programming.name} ($number)\n")
|
||||
out.append(" Programmes booked: ${before.size} before, ${after.size} after; shorts among them: $shortsBefore before, $shortsAfter after\n")
|
||||
out.append(" Shorts slots: ${blocks.size}, holding ${blocks.sumOf { it.entries.size }} shorts; $loose short(s) left on their own (a slot of one, or the block changed)\n")
|
||||
if (lengths.isNotEmpty()) out.append(" Slot length: shortest ${mins(lengths.first())} min, median ${mins(lengths[lengths.size / 2])}, longest ${mins(lengths.last())}; " +
|
||||
"${blocks.count { onHalfHour(it.endMs) }} of ${blocks.size} end within 2 min of :00 or :30\n")
|
||||
out.append(" Shows per slot: average ${"%.1f".format(blocks.map { it.shows.size }.average())}; the same show twice in a row inside a slot: $repeats time(s)\n")
|
||||
out.append(" Programmes starting within 2 min of :00 or :30: ${before.count { onHalfHour(it.startMs) }} of ${before.size} before, ${after.count { onHalfHour(it.startMs) }} of ${after.size} after\n")
|
||||
out.append(" Labels: ${blocks.groupingBy { it.label }.eachCount()}\n")
|
||||
val airtime = { run: List<ScheduleEntry> -> run.groupBy(::name).mapValues { (_, v) -> v.sumOf { it.media.durationMs } / 60_000 } }
|
||||
val a = airtime(before); val b = airtime(after)
|
||||
val moved = (a.keys + b.keys).associateWith { (b[it] ?: 0) - (a[it] ?: 0) }.entries.sortedByDescending { kotlin.math.abs(it.value) }.take(8)
|
||||
out.append(" Biggest airtime changes over the week (minutes): ${moved.joinToString { "${it.key} ${if (it.value >= 0) "+" else ""}${it.value}" }}\n")
|
||||
blocks.take(3).forEach { blk ->
|
||||
out.append(" Example slot ${clock(blk.startMs)} to ${clock(blk.endMs).takeLast(5)} \"${blk.title}\"\n")
|
||||
blk.entries.forEach { e -> out.append(" ${clock(e.startMs).takeLast(5)} ${guideTitleParts(e.media.item.title).first} (${mins(e.media.durationMs)} min)\n") }
|
||||
}
|
||||
val firstAfter = blocks.firstOrNull()?.let { blk -> after.firstOrNull { it.startMs == blk.endMs } }
|
||||
if (firstAfter != null) out.append(" After that first slot: ${clock(firstAfter.startMs).takeLast(5)} ${name(firstAfter)}, straight after the last short\n")
|
||||
}
|
||||
File(dir, "shorts-replay.txt").writeText(out.toString())
|
||||
println(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.time.ZoneId
|
||||
import java.time.ZonedDateTime
|
||||
|
||||
/** Shorts grouping (Paul, 6 November 2026): slots of shorts, every short still its own programme. */
|
||||
class ShortsTest {
|
||||
@get:Rule val folder = TemporaryFolder()
|
||||
private val zone = ZoneId.of("Europe/London")
|
||||
private fun at(h: Int, m: Int) = ZonedDateTime.of(2026, 11, 9, h, m, 0, 0, zone).toInstant().toEpochMilli()
|
||||
private fun show(id: String, minutes: Double, count: Int = 20) =
|
||||
PoolSeries(id, id, (1..count).map { PoolEpisode("$id-$it", "s", EpisodeMark(1, it), "Ep $it", (minutes * 60_000).toLong()) })
|
||||
|
||||
@Test fun aSlotAimsForTheNextHalfHourWithAtLeastFifteenMinutes() {
|
||||
assertEquals(at(15, 0), openShortsSlot(ToonZShorts, at(14, 40), zone).targetMs)
|
||||
assertEquals(at(15, 30), openShortsSlot(ToonZShorts, at(14, 50), zone).targetMs)
|
||||
assertEquals("Tots Little Mix", openShortsSlot(TotsShorts, at(10, 0), zone).label)
|
||||
assertEquals("Tots Story Time", openShortsSlot(TotsShorts, at(18, 0), zone).label)
|
||||
assertTrue(isShort(8 * 60_000L)); assertFalse(isShort(8 * 60_000L + 1))
|
||||
}
|
||||
|
||||
@Test fun shortsFillASlotInTurnAndEachStaysItsOwnProgramme() {
|
||||
val pool = listOf(show("long", 22.0), show("a", 7.0), show("b", 6.0), show("c", 5.0))
|
||||
val plan = extendSchedule(pool, ScheduleCursor(), at(9, 0), at(13, 0), finishTogether = true, shorts = ToonZShorts)
|
||||
val blocks = shortsBlocks(plan.entries)
|
||||
assertTrue(blocks.isNotEmpty())
|
||||
for (b in blocks) {
|
||||
assertTrue(b.entries.size > 1)
|
||||
assertTrue(b.entries.zipWithNext().none { (x, y) -> x.seriesId == y.seriesId })
|
||||
assertTrue(b.endMs <= b.startMs + 46 * 60_000)
|
||||
assertEquals(b.entries.last().endMs, b.endMs)
|
||||
}
|
||||
// Back to back, nothing stretched, and each short its own entry with its own episode.
|
||||
assertTrue(plan.entries.zipWithNext().all { (x, y) -> x.endMs == y.startMs })
|
||||
assertTrue(plan.entries.all { e -> pool.first { it.id == e.seriesId }.episodes.first { it.mark == e.mark }.durationMs == e.media.durationMs })
|
||||
// Without the rule, nothing is tagged and the plan is planned as before.
|
||||
val plain = extendSchedule(pool, ScheduleCursor(), at(9, 0), at(13, 0), finishTogether = true)
|
||||
assertTrue(plain.entries.all { it.group.isEmpty() })
|
||||
}
|
||||
|
||||
@Test fun aLoneShortIsAnOrdinaryProgramme() {
|
||||
val pool = listOf(show("long", 22.0), show("only", 5.0))
|
||||
val plan = extendSchedule(pool, ScheduleCursor(), at(9, 0), at(12, 0), finishTogether = true, shorts = ToonZShorts)
|
||||
assertTrue(plan.entries.all { it.group.isEmpty() })
|
||||
}
|
||||
|
||||
@Test fun theSlotTagIsSavedWithTheProgrammeAndCatchUpStillSeesEachShort() {
|
||||
val pool = listOf(show("long", 22.0), show("a", 7.0), show("b", 6.0))
|
||||
val plan = extendSchedule(pool, ScheduleCursor(), at(9, 0), at(11, 0), finishTogether = true, shorts = ToonZShorts)
|
||||
val store = ScheduleStore(folder.newFolder())
|
||||
store.savePlan("user", 605, plan)
|
||||
val back = store.loadPlan("user", 605)!!
|
||||
assertEquals(plan.entries.map { it.group }, back.entries.map { it.group })
|
||||
assertEquals(plan.entries.size, back.entries.size)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user