From b51c59586b0d82c45308a1b1a2a5373858904bf0 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Fri, 6 Nov 2026 04:22:38 +0000 Subject: [PATCH] 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) --- .../java/tv/orbit/classic/ChannelSchedule.kt | 58 ++++++--- .../java/tv/orbit/classic/ChannelScheduler.kt | 2 +- .../java/tv/orbit/classic/ScheduleStore.kt | 6 +- .../src/main/java/tv/orbit/classic/Shorts.kt | 90 ++++++++++++++ .../java/tv/orbit/classic/ShortsReplayTest.kt | 114 ++++++++++++++++++ .../test/java/tv/orbit/classic/ShortsTest.kt | 60 +++++++++ 6 files changed, 309 insertions(+), 21 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/Shorts.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ShortsReplayTest.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ShortsTest.kt 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 bd095f5b..a7bf1d14 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -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 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, 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, 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, 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, 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, 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, stories: Boolean = false): ChannelPlan { + recentFiles: Map = 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() @@ -826,10 +839,10 @@ 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, 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, 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, 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, cursor: ScheduleCursor, from val waiting = mutableListOf(); val elsewhere = mutableListOf() // 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, 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, 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) } 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 d7e264c4..b79c0002 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -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 { diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 16b16e01..56e7eba5 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -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"))) diff --git a/android/app/src/main/java/tv/orbit/classic/Shorts.kt b/android/app/src/main/java/tv/orbit/classic/Shorts.kt new file mode 100644 index 00000000..05bdc91a --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/Shorts.kt @@ -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) { + /** The shows in the slot, in the order they first air in it. */ + val shows: List 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): List = buildList { + var run = mutableListOf() + 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 { + 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): List { + 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 } +} diff --git a/android/app/src/test/java/tv/orbit/classic/ShortsReplayTest.kt b/android/app/src/test/java/tv/orbit/classic/ShortsReplayTest.kt new file mode 100644 index 00000000..d4b1f14f --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ShortsReplayTest.kt @@ -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= ./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 { + 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, shorts: ShortsRule?, avoid: ProgrammeClash): List { + 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 -> 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) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/ShortsTest.kt b/android/app/src/test/java/tv/orbit/classic/ShortsTest.kt new file mode 100644 index 00000000..eafa3677 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ShortsTest.kt @@ -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) + } +}