|
|
|
@@ -277,16 +277,34 @@ internal fun dayPartChoice(pool: List<PoolSeries>, parts: List<DayPart>, startMs
|
|
|
|
|
dayPartFor(pool, parts, startMs, zone).let { it.first to it.second }
|
|
|
|
|
|
|
|
|
|
/** [dayPartChoice], with the part it came from, or null for the whole pool. */
|
|
|
|
|
/**
|
|
|
|
|
* Which of a pool's shows each block may use, worked out once per pool and block rather than for every programme planned:
|
|
|
|
|
* matching titles means normalising every name, which made planning take seconds on the box. Keyed by the very pool and
|
|
|
|
|
* block objects, so a different pool or a changed block is always worked out afresh.
|
|
|
|
|
*/
|
|
|
|
|
private object PartPools {
|
|
|
|
|
private val recent = ArrayDeque<Pair<List<PoolSeries>, java.util.IdentityHashMap<DayPart, List<PoolSeries>>>>()
|
|
|
|
|
@Synchronized fun of(pool: List<PoolSeries>, part: DayPart, allowed: () -> List<PoolSeries>): List<PoolSeries> {
|
|
|
|
|
val entry = recent.firstOrNull { it.first === pool } ?: (pool to java.util.IdentityHashMap<DayPart, List<PoolSeries>>()).also {
|
|
|
|
|
recent.addFirst(it)
|
|
|
|
|
if (recent.size > 8) recent.removeLast()
|
|
|
|
|
}
|
|
|
|
|
return entry.second.getOrPut(part, allowed)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
internal fun dayPartFor(pool: List<PoolSeries>, parts: List<DayPart>, startMs: Long, zone: java.time.ZoneId): Triple<List<PoolSeries>, String, DayPart?> {
|
|
|
|
|
val local = java.time.Instant.ofEpochMilli(startMs).atZone(zone)
|
|
|
|
|
// An event with nothing to show gives way to the ordinary block for that time.
|
|
|
|
|
for (part in parts.filter { it.covers(local.hour, local.dayOfWeek) }) {
|
|
|
|
|
val name = (if (part.days.isNotEmpty()) "event " else "block ") + part.group.ifEmpty { "${part.fromHour}-${part.toHour}" }
|
|
|
|
|
if (part.titles.isEmpty() && part.group.isEmpty()) return Triple(pool, name, part)
|
|
|
|
|
val titles = part.titles.map(::seriesKey).toSet()
|
|
|
|
|
// A film is named with its year, as "Halloween (1978)"; the pool already holds that exact film under its plain title.
|
|
|
|
|
val films = part.titles.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
|
|
|
|
|
val allowed = pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || (part.group.isNotEmpty() && it.group == part.group) }
|
|
|
|
|
val allowed = PartPools.of(pool, part) {
|
|
|
|
|
val titles = part.titles.map(::seriesKey).toSet()
|
|
|
|
|
// A film is named with its year, as "Halloween (1978)"; the pool already holds that exact film under its plain title.
|
|
|
|
|
val films = part.titles.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
|
|
|
|
|
pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || (part.group.isNotEmpty() && it.group == part.group) }
|
|
|
|
|
}
|
|
|
|
|
if (allowed.isNotEmpty()) return Triple(allowed, name, part)
|
|
|
|
|
}
|
|
|
|
|
// A film saved for an event doesn't appear in everyday programming.
|
|
|
|
@@ -382,7 +400,19 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
|
|
|
|
|
val films = available.filter { it.isFilm }.ifEmpty { pool.filter { it.isFilm } }.ifEmpty { available }
|
|
|
|
|
// Events keep the channel's rest; everyday blocks, when adaptive, rest by how long their own films last.
|
|
|
|
|
val rest = if (adaptiveRest && part?.days.isNullOrEmpty()) blockRest.getOrPut(part) { sharedAdaptiveRestMs(pool, dayParts, part, restMs) } else restMs
|
|
|
|
|
val (film, why) = chooseFilm(films, shown, start, rest, avoid)
|
|
|
|
|
var (film, why) = chooseFilm(films, shown, start, rest, avoid)
|
|
|
|
|
// Before an appointment, a rested film that leaves it on time, picked in the same seeded order as any other.
|
|
|
|
|
val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, (ON_TIME_FILM_RUN_IN_MS / (60 * 60_000L)).toInt()) { at -> dayPartFor(pool, dayParts, at, zone) }
|
|
|
|
|
if (appointment != null) {
|
|
|
|
|
val clear = films.filter { f -> !avoid(f, start, start + f.episodes.first().durationMs) }
|
|
|
|
|
// Rested films in the same seeded order as any other pick; when none is rested, the longest waiting first, as the fallback would.
|
|
|
|
|
val rested = clear.filter { f -> shown[f.id]?.let { start - it >= rest } != false }.shuffled(java.util.Random(start))
|
|
|
|
|
.ifEmpty { clear.sortedBy { shown[it.id] ?: Long.MIN_VALUE } }
|
|
|
|
|
fitBeforeAppointment(appointment, start, film, rested, ON_TIME_FILM_RUN_IN_MS, followers = 2) { start + it.episodes.first().durationMs }?.let {
|
|
|
|
|
film = it
|
|
|
|
|
why = "$why; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment).atZone(zone).toLocalTime()}"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
val copy = film.episodes.first()
|
|
|
|
|
val item = SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs)
|
|
|
|
|
// Only a programme actually drawn from the event's own titles carries its presentation.
|
|
|
|
@@ -455,6 +485,55 @@ private const val ON_TIME_GRACE_MS = 20 * 60_000L
|
|
|
|
|
private const val ON_TIME_LAST_CALL_MS = 60 * 60_000L
|
|
|
|
|
/** How long before an appointment the programmes leading into it may be adjusted. */
|
|
|
|
|
private const val ON_TIME_RUN_IN_MS = 90 * 60_000L
|
|
|
|
|
/** The same for films, which are long: the last two or three before an appointment have to be chosen together for it to start in time. */
|
|
|
|
|
private const val ON_TIME_FILM_RUN_IN_MS = 6 * 60 * 60_000L
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The next on-time appointment within [lookaheadHours] after [at]: the first hour boundary whose part is an
|
|
|
|
|
* appointment with something to show. Shared by the weighted and film planners; equal turns has its own, unchanged.
|
|
|
|
|
*/
|
|
|
|
|
internal fun nextAppointment(at: Long, zone: java.time.ZoneId, lookaheadHours: Int = ON_TIME_LOOKAHEAD_HOURS, partAt: (Long) -> Triple<List<PoolSeries>, String, DayPart?>): Long? {
|
|
|
|
|
val hour = 60 * 60_000L
|
|
|
|
|
val nextHour = java.time.Instant.ofEpochMilli(at).atZone(zone).truncatedTo(java.time.temporal.ChronoUnit.HOURS).plusHours(1).toInstant().toEpochMilli()
|
|
|
|
|
return (0 until lookaheadHours).map { nextHour + it * hour }.firstOrNull { boundary ->
|
|
|
|
|
val (shows, _, part) = partAt(boundary)
|
|
|
|
|
part?.onTime == true && shows.isNotEmpty()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Before an appointment, a programme that leaves it on time, as equal turns has done since PPV Sunday: one ending at the
|
|
|
|
|
* appointment or in its first [ON_TIME_GRACE_MS], or one leaving a gap another candidate closes. Only the last
|
|
|
|
|
* [runInMs] before the appointment is adjusted ([ON_TIME_RUN_IN_MS] for series, [ON_TIME_FILM_RUN_IN_MS] for films), nothing is cut and nothing is left empty. [candidates] are in the
|
|
|
|
|
* planner's own order of preference and already satisfy its rules. Null keeps [chosen].
|
|
|
|
|
*/
|
|
|
|
|
internal fun <T> fitBeforeAppointment(appointment: Long, start: Long, chosen: T, candidates: List<T>, runInMs: Long = ON_TIME_RUN_IN_MS,
|
|
|
|
|
/** How many more programmes may follow before the appointment: 1 for series, 2 for films, which are long. */
|
|
|
|
|
followers: Int = 1, ends: (T) -> Long): T? {
|
|
|
|
|
val latest = appointment + ON_TIME_GRACE_MS
|
|
|
|
|
if (ends(chosen) <= appointment - runInMs) return null
|
|
|
|
|
val remaining = appointment - start
|
|
|
|
|
fun length(x: T) = ends(x) - start
|
|
|
|
|
/** Whether [first] can open a run of up to [followers] more different candidates that ends at the appointment or in its grace. */
|
|
|
|
|
fun opensRun(first: T): Boolean {
|
|
|
|
|
val total = length(first)
|
|
|
|
|
if (total in remaining..remaining + ON_TIME_GRACE_MS) return true
|
|
|
|
|
if (total > remaining) return false
|
|
|
|
|
val rest = candidates.filter { it != first }.map(::length)
|
|
|
|
|
if (followers >= 1 && rest.any { total + it in remaining..remaining + ON_TIME_GRACE_MS }) return true
|
|
|
|
|
if (followers >= 2) rest.forEachIndexed { i, a -> if (total + a < remaining) for (j in i + 1 until rest.size) if (total + a + rest[j] in remaining..remaining + ON_TIME_GRACE_MS) return true }
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
if (opensRun(chosen)) return null
|
|
|
|
|
val fits = candidates.filter { ends(it) <= latest }
|
|
|
|
|
// Best is one ending at the appointment, then one a single programme can follow in time, then any that opens a run.
|
|
|
|
|
return fits.firstOrNull { ends(it) >= appointment }
|
|
|
|
|
?: fits.firstOrNull { x -> ends(x) < appointment && candidates.any { it != x && ends(x) + length(it) in appointment..latest } }
|
|
|
|
|
?: fits.firstOrNull { opensRun(it) }
|
|
|
|
|
?: fits.firstOrNull().takeIf { ends(chosen) > latest }
|
|
|
|
|
// Failing that, at least something that ends while the appointment's window is still open, so it isn't missed.
|
|
|
|
|
?: candidates.firstOrNull { ends(it) < appointment + ON_TIME_LAST_CALL_MS }.takeIf { ends(chosen) >= appointment + ON_TIME_LAST_CALL_MS }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** A series on a film channel airs at most once in this long, so a long event window still holds one episode. */
|
|
|
|
|
private const val SERIES_NIGHT_MS = 12 * 60 * 60_000L
|
|
|
|
@@ -530,14 +609,20 @@ internal fun extendWeighted(pool: List<PoolSeries>, cursor: ScheduleCursor, from
|
|
|
|
|
// A show held back by the 24-hour or restart rule is brought up level, so it comes back to its share without a burst.
|
|
|
|
|
val low = eligible.minOf { tally[it.id]!! }
|
|
|
|
|
clear.filter { it.id != last && it !in eligible }.forEach { tally[it.id] = maxOf(tally[it.id]!!, low) }
|
|
|
|
|
val series = eligible.minWith(compareBy<PoolSeries> { tally[it.id]!! }.thenBy { pool.indexOf(it) })
|
|
|
|
|
val byTally = compareBy<PoolSeries> { tally[it.id]!! }.thenBy { pool.indexOf(it) }
|
|
|
|
|
val preferred = eligible.minWith(byTally)
|
|
|
|
|
// Before an appointment, the eligible show that leaves it on time, then any clear one, in tally order.
|
|
|
|
|
val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, partAt = ::partAt)
|
|
|
|
|
val fitted = appointment?.let { at -> fun ends(show: PoolSeries) = start + following(show).durationMs
|
|
|
|
|
fitBeforeAppointment(at, start, preferred, eligible.sortedWith(byTally), ends = ::ends) ?: fitBeforeAppointment(at, start, preferred, clear.sortedWith(byTally), ends = ::ends) }
|
|
|
|
|
val series = fitted ?: preferred
|
|
|
|
|
val episode = following(series)
|
|
|
|
|
val why = "$block; weighted: lowest tally for its tier (${"%.0f".format(tally[series.id])})" + (if (eligible.size < clear.size) ", others resting or just played" else "") +
|
|
|
|
|
when {
|
|
|
|
|
unclashed.isEmpty() -> "; fallback: every show here airs elsewhere then"
|
|
|
|
|
series.id == last && unclashed.size < available.size -> "; again, as the others here air elsewhere then"
|
|
|
|
|
else -> ""
|
|
|
|
|
}
|
|
|
|
|
} + if (fitted != null) "; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment!!).atZone(zone).toLocalTime()}" else ""
|
|
|
|
|
val item = if (series.isFilm) SampleItem(series.title, "Movie", episode.durationMs / 60_000, "", episode.id, episode.durationMs) else scheduledItem(series.title, episode)
|
|
|
|
|
entries += ScheduleEntry(series.id, episode.mark, ScheduledMedia(item, episode.sourceId, episode.durationMs), start, why, if (series in available) part?.key.orEmpty() else "")
|
|
|
|
|
val weight = part?.takeIf { series in available }?.weights?.get(seriesKey(series.title)) ?: weightOf(series)
|
|
|
|
|